2 * Copyright © 2015-2020 Soren Stoutner <soren@stoutner.com>.
4 * Download cookie code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
6 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
8 * Privacy Browser is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
13 * Privacy Browser is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with Privacy Browser. If not, see <http://www.gnu.org/licenses/>.
22 package com.stoutner.privacybrowser.activities;
24 import android.Manifest;
25 import android.annotation.SuppressLint;
26 import android.app.Activity;
27 import android.app.Dialog;
28 import android.app.DownloadManager;
29 import android.app.SearchManager;
30 import android.content.ActivityNotFoundException;
31 import android.content.BroadcastReceiver;
32 import android.content.ClipData;
33 import android.content.ClipboardManager;
34 import android.content.Context;
35 import android.content.Intent;
36 import android.content.IntentFilter;
37 import android.content.SharedPreferences;
38 import android.content.pm.PackageManager;
39 import android.content.res.Configuration;
40 import android.database.Cursor;
41 import android.graphics.Bitmap;
42 import android.graphics.BitmapFactory;
43 import android.graphics.Typeface;
44 import android.graphics.drawable.BitmapDrawable;
45 import android.graphics.drawable.Drawable;
46 import android.net.Uri;
47 import android.net.http.SslCertificate;
48 import android.net.http.SslError;
49 import android.os.Build;
50 import android.os.Bundle;
51 import android.os.Handler;
52 import android.os.Message;
53 import android.preference.PreferenceManager;
54 import android.print.PrintDocumentAdapter;
55 import android.print.PrintManager;
56 import android.text.Editable;
57 import android.text.Spanned;
58 import android.text.TextWatcher;
59 import android.text.style.ForegroundColorSpan;
60 import android.util.Patterns;
61 import android.view.ContextMenu;
62 import android.view.GestureDetector;
63 import android.view.KeyEvent;
64 import android.view.Menu;
65 import android.view.MenuItem;
66 import android.view.MotionEvent;
67 import android.view.View;
68 import android.view.ViewGroup;
69 import android.view.WindowManager;
70 import android.view.inputmethod.InputMethodManager;
71 import android.webkit.CookieManager;
72 import android.webkit.HttpAuthHandler;
73 import android.webkit.SslErrorHandler;
74 import android.webkit.ValueCallback;
75 import android.webkit.WebBackForwardList;
76 import android.webkit.WebChromeClient;
77 import android.webkit.WebResourceResponse;
78 import android.webkit.WebSettings;
79 import android.webkit.WebStorage;
80 import android.webkit.WebView;
81 import android.webkit.WebViewClient;
82 import android.webkit.WebViewDatabase;
83 import android.widget.ArrayAdapter;
84 import android.widget.CursorAdapter;
85 import android.widget.EditText;
86 import android.widget.FrameLayout;
87 import android.widget.ImageView;
88 import android.widget.LinearLayout;
89 import android.widget.ListView;
90 import android.widget.ProgressBar;
91 import android.widget.RadioButton;
92 import android.widget.RelativeLayout;
93 import android.widget.TextView;
95 import androidx.annotation.NonNull;
96 import androidx.appcompat.app.ActionBar;
97 import androidx.appcompat.app.ActionBarDrawerToggle;
98 import androidx.appcompat.app.AppCompatActivity;
99 import androidx.appcompat.widget.Toolbar;
100 import androidx.coordinatorlayout.widget.CoordinatorLayout;
101 import androidx.core.app.ActivityCompat;
102 import androidx.core.content.ContextCompat;
103 import androidx.core.view.GravityCompat;
104 import androidx.drawerlayout.widget.DrawerLayout;
105 import androidx.fragment.app.DialogFragment;
106 import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
107 import androidx.viewpager.widget.ViewPager;
109 import com.google.android.material.appbar.AppBarLayout;
110 import com.google.android.material.floatingactionbutton.FloatingActionButton;
111 import com.google.android.material.navigation.NavigationView;
112 import com.google.android.material.snackbar.Snackbar;
113 import com.google.android.material.tabs.TabLayout;
115 import com.stoutner.privacybrowser.BuildConfig;
116 import com.stoutner.privacybrowser.R;
117 import com.stoutner.privacybrowser.adapters.WebViewPagerAdapter;
118 import com.stoutner.privacybrowser.asynctasks.GetHostIpAddresses;
119 import com.stoutner.privacybrowser.asynctasks.PopulateBlocklists;
120 import com.stoutner.privacybrowser.asynctasks.SaveUrl;
121 import com.stoutner.privacybrowser.asynctasks.SaveWebpageImage;
122 import com.stoutner.privacybrowser.dialogs.AdConsentDialog;
123 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
124 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
125 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
126 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
127 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
128 import com.stoutner.privacybrowser.dialogs.FontSizeDialog;
129 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
130 import com.stoutner.privacybrowser.dialogs.OpenDialog;
131 import com.stoutner.privacybrowser.dialogs.ProxyNotInstalledDialog;
132 import com.stoutner.privacybrowser.dialogs.PinnedMismatchDialog;
133 import com.stoutner.privacybrowser.dialogs.SaveDialog;
134 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
135 import com.stoutner.privacybrowser.dialogs.StoragePermissionDialog;
136 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
137 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
138 import com.stoutner.privacybrowser.dialogs.WaitingForProxyDialog;
139 import com.stoutner.privacybrowser.fragments.WebViewTabFragment;
140 import com.stoutner.privacybrowser.helpers.AdHelper;
141 import com.stoutner.privacybrowser.helpers.BlocklistHelper;
142 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
143 import com.stoutner.privacybrowser.helpers.CheckPinnedMismatchHelper;
144 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
145 import com.stoutner.privacybrowser.helpers.FileNameHelper;
146 import com.stoutner.privacybrowser.helpers.ProxyHelper;
147 import com.stoutner.privacybrowser.views.NestedScrollWebView;
149 import java.io.ByteArrayInputStream;
150 import java.io.ByteArrayOutputStream;
152 import java.io.IOException;
153 import java.io.UnsupportedEncodingException;
154 import java.net.MalformedURLException;
156 import java.net.URLDecoder;
157 import java.net.URLEncoder;
158 import java.util.ArrayList;
159 import java.util.Date;
160 import java.util.HashMap;
161 import java.util.HashSet;
162 import java.util.List;
163 import java.util.Map;
164 import java.util.Objects;
165 import java.util.Set;
167 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
168 EditBookmarkDialog.EditBookmarkListener, EditBookmarkFolderDialog.EditBookmarkFolderListener, FontSizeDialog.UpdateFontSizeListener, NavigationView.OnNavigationItemSelectedListener,
169 OpenDialog.OpenListener, PinnedMismatchDialog.PinnedMismatchListener, PopulateBlocklists.PopulateBlocklistsListener, SaveDialog.SaveWebpageListener,
170 StoragePermissionDialog.StoragePermissionDialogListener, UrlHistoryDialog.NavigateHistoryListener, WebViewTabFragment.NewTabListener {
172 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`, `onResume()`, and `applyProxy()`.
173 public static String orbotStatus = "unknown";
175 // The WebView pager adapter is accessed from `HttpAuthenticationDialog`, `PinnedMismatchDialog`, and `SslCertificateErrorDialog`. It is also used in `onCreate()`, `onResume()`, and `addTab()`.
176 public static WebViewPagerAdapter webViewPagerAdapter;
178 // The load URL on restart variables are public static so they can be accessed from `BookmarksActivity`. They are used in `onRestart()`.
179 public static boolean loadUrlOnRestart;
180 public static String urlToLoadOnRestart;
182 // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onRestart()`.
183 public static boolean restartFromBookmarksActivity;
185 // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
186 // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
187 public static String currentBookmarksFolder;
189 // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
190 public final static int UNRECOGNIZED_USER_AGENT = -1;
191 public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
192 public final static int SETTINGS_CUSTOM_USER_AGENT = 12;
193 public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
194 public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
195 public final static int DOMAINS_CUSTOM_USER_AGENT = 13;
197 // Start activity for result request codes. The public static entries are accessed from `OpenDialog()` and `SaveWebpageDialog()`.
198 public final static int BROWSE_OPEN_REQUEST_CODE = 0;
199 public final static int BROWSE_SAVE_WEBPAGE_REQUEST_CODE = 1;
200 private final int BROWSE_FILE_UPLOAD_REQUEST_CODE = 2;
202 // The proxy mode is public static so it can be accessed from `ProxyHelper()`.
203 // It is also used in `onRestart()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `applyAppSettings()`, and `applyProxy()`.
204 // It will be updated in `applyAppSettings()`, but it needs to be initialized here or the first run of `onPrepareOptionsMenu()` crashes.
205 public static String proxyMode = ProxyHelper.NONE;
208 // The permission result request codes are used in `onCreateContextMenu()`, `onRequestPermissionResult()`, `onSaveWebpage()`, `onCloseStoragePermissionDialog()`, and `initializeWebView()`.
209 private final int PERMISSION_OPEN_REQUEST_CODE = 0;
210 private final int PERMISSION_SAVE_URL_REQUEST_CODE = 1;
211 private final int PERMISSION_SAVE_AS_ARCHIVE_REQUEST_CODE = 2;
212 private final int PERMISSION_SAVE_AS_IMAGE_REQUEST_CODE = 3;
214 // The current WebView is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
215 // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, `applyProxy()`, and `applyDomainSettings()`.
216 private NestedScrollWebView currentWebView;
218 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
219 private final Map<String, String> customHeaders = new HashMap<>();
221 // The search URL is set in `applyAppSettings()` and used in `onNewIntent()`, `loadUrlFromTextBox()`, `initializeApp()`, and `initializeWebView()`.
222 private String searchURL;
224 // The options menu is set in `onCreateOptionsMenu()` and used in `onOptionsItemSelected()`, `updatePrivacyIcons()`, and `initializeWebView()`.
225 private Menu optionsMenu;
227 // The blocklists are populated in `finishedPopulatingBlocklists()` and accessed from `initializeWebView()`.
228 private ArrayList<List<String[]>> easyList;
229 private ArrayList<List<String[]>> easyPrivacy;
230 private ArrayList<List<String[]>> fanboysAnnoyanceList;
231 private ArrayList<List<String[]>> fanboysSocialList;
232 private ArrayList<List<String[]>> ultraList;
233 private ArrayList<List<String[]>> ultraPrivacy;
235 // `webViewDefaultUserAgent` is used in `onCreate()` and `onPrepareOptionsMenu()`.
236 private String webViewDefaultUserAgent;
238 // The incognito mode is set in `applyAppSettings()` and used in `initializeWebView()`.
239 private boolean incognitoModeEnabled;
241 // The full screen browsing mode tracker is set it `applyAppSettings()` and used in `initializeWebView()`.
242 private boolean fullScreenBrowsingModeEnabled;
244 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
245 private boolean inFullScreenBrowsingMode;
247 // The app bar trackers are set in `applyAppSettings()` and used in `initializeWebView()`.
248 private boolean hideAppBar;
249 private boolean scrollAppBar;
251 // The loading new intent tracker is set in `onNewIntent()` and used in `setCurrentWebView()`.
252 private boolean loadingNewIntent;
254 // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
255 private boolean reapplyDomainSettingsOnRestart;
257 // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
258 private boolean reapplyAppSettingsOnRestart;
260 // `displayingFullScreenVideo` is used in `onCreate()` and `onResume()`.
261 private boolean displayingFullScreenVideo;
263 // `orbotStatusBroadcastReceiver` is used in `onCreate()` and `onDestroy()`.
264 private BroadcastReceiver orbotStatusBroadcastReceiver;
266 // The waiting for proxy boolean is used in `onResume()`, `initializeApp()` and `applyProxy()`.
267 private boolean waitingForProxy = false;
269 // The action bar drawer toggle is initialized in `onCreate()` and used in `onResume()`.
270 private ActionBarDrawerToggle actionBarDrawerToggle;
272 // The color spans are used in `onCreate()` and `highlightUrlText()`.
273 private ForegroundColorSpan redColorSpan;
274 private ForegroundColorSpan initialGrayColorSpan;
275 private ForegroundColorSpan finalGrayColorSpan;
277 // The drawer header padding variables are used in `onCreate()` and `onConfigurationChanged()`.
278 private int drawerHeaderPaddingLeftAndRight;
279 private int drawerHeaderPaddingTop;
280 private int drawerHeaderPaddingBottom;
282 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onDestroy`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`,
283 // and `loadBookmarksFolder()`.
284 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
286 // `bookmarksCursor` is used in `onDestroy()`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
287 private Cursor bookmarksCursor;
289 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
290 private CursorAdapter bookmarksCursorAdapter;
292 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
293 private String oldFolderNameString;
295 // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
296 private ValueCallback<Uri[]> fileChooserCallback;
298 // The default progress view offsets are set in `onCreate()` and used in `initializeWebView()`.
299 private int defaultProgressViewStartOffset;
300 private int defaultProgressViewEndOffset;
302 // The swipe refresh layout top padding is used when exiting full screen browsing mode. It is used in an inner class in `initializeWebView()`.
303 private int swipeRefreshLayoutPaddingTop;
305 // The URL sanitizers are set in `applyAppSettings()` and used in `sanitizeUrl()`.
306 private boolean sanitizeGoogleAnalytics;
307 private boolean sanitizeFacebookClickIds;
308 private boolean sanitizeTwitterAmpRedirects;
310 // The file path strings are used in `onSaveWebpage()` and `onRequestPermissionResult()`
311 private String openFilePath;
312 private String saveWebpageUrl;
313 private String saveWebpageFilePath;
316 // Remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
317 @SuppressLint("ClickableViewAccessibility")
318 protected void onCreate(Bundle savedInstanceState) {
319 // Enable the drawing of the entire webpage. This makes it possible to save a website image. This must be done before anything else happens with the WebView.
320 if (Build.VERSION.SDK_INT >= 21) {
321 WebView.enableSlowWholeDocumentDraw();
324 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
325 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
327 // Get a handle for the shared preferences.
328 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
330 // Get the theme and screenshot preferences.
331 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
332 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
334 // Disable screenshots if not allowed.
335 if (!allowScreenshots) {
336 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
339 // Set the activity theme.
341 setTheme(R.style.PrivacyBrowserDark);
343 setTheme(R.style.PrivacyBrowserLight);
346 // Run the default commands.
347 super.onCreate(savedInstanceState);
349 // Set the content view.
350 setContentView(R.layout.main_framelayout);
352 // Get handles for the views that need to be modified.
353 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
354 Toolbar toolbar = findViewById(R.id.toolbar);
355 ViewPager webViewPager = findViewById(R.id.webviewpager);
357 // Set the action bar. `SupportActionBar` must be used until the minimum API is >= 21.
358 setSupportActionBar(toolbar);
360 // Get a handle for the action bar.
361 ActionBar actionBar = getSupportActionBar();
363 // This is needed to get rid of the Android Studio warning that the action bar might be null.
364 assert actionBar != null;
366 // Add the custom layout, which shows the URL text bar.
367 actionBar.setCustomView(R.layout.url_app_bar);
368 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
370 // Initially disable the sliding drawers. They will be enabled once the blocklists are loaded.
371 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
373 // Create the hamburger icon at the start of the AppBar.
374 actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
376 // Initialize the web view pager adapter.
377 webViewPagerAdapter = new WebViewPagerAdapter(getSupportFragmentManager());
379 // Set the pager adapter on the web view pager.
380 webViewPager.setAdapter(webViewPagerAdapter);
382 // Store up to 100 tabs in memory.
383 webViewPager.setOffscreenPageLimit(100);
385 // Populate the blocklists.
386 new PopulateBlocklists(this, this).execute();
390 protected void onNewIntent(Intent intent) {
391 // Run the default commands.
392 super.onNewIntent(intent);
394 // Replace the intent that started the app with this one.
397 // Process the intent here if Privacy Browser is fully initialized. If the process has been killed by the system while sitting in the background, this will be handled in `initializeWebView()`.
398 if (ultraPrivacy != null) {
399 // Get the information from the intent.
400 String intentAction = intent.getAction();
401 Uri intentUriData = intent.getData();
403 // Determine if this is a web search.
404 boolean isWebSearch = ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH));
406 // Only process the URI if it contains data or it is a web search. If the user pressed the desktop icon after the app was already running the URI will be null.
407 if (intentUriData != null || isWebSearch) {
408 // Get the shared preferences.
409 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
411 // Create a URL string.
414 // If the intent action is a web search, perform the search.
416 // Create an encoded URL string.
417 String encodedUrlString;
419 // Sanitize the search input and convert it to a search.
421 encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
422 } catch (UnsupportedEncodingException exception) {
423 encodedUrlString = "";
426 // Add the base search URL.
427 url = searchURL + encodedUrlString;
428 } else { // The intent should contain a URL.
429 // Set the intent data as the URL.
430 url = intentUriData.toString();
433 // Add a new tab if specified in the preferences.
434 if (sharedPreferences.getBoolean("open_intents_in_new_tab", true)) { // Load the URL in a new tab.
435 // Set the loading new intent flag.
436 loadingNewIntent = true;
439 addNewTab(url, true);
440 } else { // Load the URL in the current tab.
442 loadUrl(currentWebView, url);
445 // Get a handle for the drawer layout.
446 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
448 // Close the navigation drawer if it is open.
449 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
450 drawerLayout.closeDrawer(GravityCompat.START);
453 // Close the bookmarks drawer if it is open.
454 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
455 drawerLayout.closeDrawer(GravityCompat.END);
462 public void onRestart() {
463 // Run the default commands.
466 // Apply the app settings if returning from the Settings activity.
467 if (reapplyAppSettingsOnRestart) {
468 // Reset the reapply app settings on restart tracker.
469 reapplyAppSettingsOnRestart = false;
471 // Apply the app settings.
475 // Apply the domain settings if returning from the settings or domains activity.
476 if (reapplyDomainSettingsOnRestart) {
477 // Reset the reapply domain settings on restart tracker.
478 reapplyDomainSettingsOnRestart = false;
480 // Reapply the domain settings for each tab.
481 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
482 // Get the WebView tab fragment.
483 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
485 // Get the fragment view.
486 View fragmentView = webViewTabFragment.getView();
488 // Only reload the WebViews if they exist.
489 if (fragmentView != null) {
490 // Get the nested scroll WebView from the tab fragment.
491 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
493 // Reset the current domain name so the domain settings will be reapplied.
494 nestedScrollWebView.resetCurrentDomainName();
496 // Reapply the domain settings if the URL is not null, which can happen if an empty tab is active when returning from settings.
497 if (nestedScrollWebView.getUrl() != null) {
498 applyDomainSettings(nestedScrollWebView, nestedScrollWebView.getUrl(), false, true);
504 // Load the URL on restart (used when loading a bookmark).
505 if (loadUrlOnRestart) {
506 // Load the specified URL.
507 loadUrl(currentWebView, urlToLoadOnRestart);
509 // Reset the load on restart tracker.
510 loadUrlOnRestart = false;
513 // Update the bookmarks drawer if returning from the Bookmarks activity.
514 if (restartFromBookmarksActivity) {
515 // Get a handle for the drawer layout.
516 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
518 // Close the bookmarks drawer.
519 drawerLayout.closeDrawer(GravityCompat.END);
521 // Reload the bookmarks drawer.
522 loadBookmarksFolder();
524 // Reset `restartFromBookmarksActivity`.
525 restartFromBookmarksActivity = false;
528 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
529 updatePrivacyIcons(true);
532 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
534 public void onResume() {
535 // Run the default commands.
538 // Resume any WebViews.
539 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
540 // Get the WebView tab fragment.
541 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
543 // Get the fragment view.
544 View fragmentView = webViewTabFragment.getView();
546 // Only resume the WebViews if they exist (they won't when the app is first created).
547 if (fragmentView != null) {
548 // Get the nested scroll WebView from the tab fragment.
549 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
551 // Resume the nested scroll WebView JavaScript timers.
552 nestedScrollWebView.resumeTimers();
554 // Resume the nested scroll WebView.
555 nestedScrollWebView.onResume();
559 // Reapply the proxy settings if the system is using a proxy. This redisplays the appropriate alert dialog.
560 if (!proxyMode.equals(ProxyHelper.NONE)) {
564 // Reapply any system UI flags and the ad in the free flavor.
565 if (displayingFullScreenVideo || inFullScreenBrowsingMode) { // The system is displaying a website or a video in full screen mode.
566 // Get a handle for the root frame layouts.
567 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
569 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
570 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
572 /* Hide the system bars.
573 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
574 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
575 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
576 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
578 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
579 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
580 } else if (BuildConfig.FLAVOR.contentEquals("free")) { // The system in not in full screen mode.
582 AdHelper.resumeAd(findViewById(R.id.adview));
587 public void onPause() {
588 // Run the default commands.
591 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
592 // Get the WebView tab fragment.
593 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
595 // Get the fragment view.
596 View fragmentView = webViewTabFragment.getView();
598 // Only pause the WebViews if they exist (they won't when the app is first created).
599 if (fragmentView != null) {
600 // Get the nested scroll WebView from the tab fragment.
601 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
603 // Pause the nested scroll WebView.
604 nestedScrollWebView.onPause();
606 // Pause the nested scroll WebView JavaScript timers.
607 nestedScrollWebView.pauseTimers();
611 // Pause the ad or it will continue to consume resources in the background on the free flavor.
612 if (BuildConfig.FLAVOR.contentEquals("free")) {
614 AdHelper.pauseAd(findViewById(R.id.adview));
619 public void onDestroy() {
620 // Unregister the orbot status broadcast receiver.
621 this.unregisterReceiver(orbotStatusBroadcastReceiver);
623 // Close the bookmarks cursor and database.
624 bookmarksCursor.close();
625 bookmarksDatabaseHelper.close();
627 // Run the default commands.
632 public boolean onCreateOptionsMenu(Menu menu) {
633 // Inflate the menu. This adds items to the action bar if it is present.
634 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
636 // Store a handle for the options menu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons()`.
639 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
640 updatePrivacyIcons(false);
642 // Get handles for the menu items.
643 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
644 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
645 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
646 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
647 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
648 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
649 MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
651 // Only display third-party cookies if API >= 21
652 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
654 // Only display the form data menu items if the API < 26.
655 toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
656 clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
658 // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
659 clearFormDataMenuItem.setEnabled(Build.VERSION.SDK_INT < 26);
661 // Only show Ad Consent if this is the free flavor.
662 adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
664 // Get the shared preferences.
665 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
667 // Get the dark theme and app bar preferences..
668 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
669 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
671 // Set the status of the additional app bar icons. Setting the refresh menu item to `SHOW_AS_ACTION_ALWAYS` makes it appear even on small devices like phones.
672 if (displayAdditionalAppBarIcons) {
673 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
674 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
675 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
676 } else { //Do not display the additional icons.
677 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
678 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
679 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
682 // Replace Refresh with Stop if a URL is already loading.
683 if (currentWebView != null && currentWebView.getProgress() != 100) {
685 refreshMenuItem.setTitle(R.string.stop);
687 // If the icon is displayed in the AppBar, set it according to the theme.
688 if (displayAdditionalAppBarIcons) {
690 refreshMenuItem.setIcon(R.drawable.close_dark);
692 refreshMenuItem.setIcon(R.drawable.close_light);
702 public boolean onPrepareOptionsMenu(Menu menu) {
703 // Get handles for the menu items.
704 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
705 MenuItem firstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
706 MenuItem thirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
707 MenuItem domStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
708 MenuItem saveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
709 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
710 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
711 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
712 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
713 MenuItem blocklistsMenuItem = menu.findItem(R.id.blocklists);
714 MenuItem easyListMenuItem = menu.findItem(R.id.easylist);
715 MenuItem easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
716 MenuItem fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
717 MenuItem fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
718 MenuItem ultraListMenuItem = menu.findItem(R.id.ultralist);
719 MenuItem ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
720 MenuItem blockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
721 MenuItem proxyMenuItem = menu.findItem(R.id.proxy);
722 MenuItem userAgentMenuItem = menu.findItem(R.id.user_agent);
723 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
724 MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
725 MenuItem wideViewportMenuItem = menu.findItem(R.id.wide_viewport);
726 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
727 MenuItem nightModeMenuItem = menu.findItem(R.id.night_mode);
729 // Get a handle for the cookie manager.
730 CookieManager cookieManager = CookieManager.getInstance();
732 // Initialize the current user agent string and the font size.
733 String currentUserAgent = getString(R.string.user_agent_privacy_browser);
736 // Set items that require the current web view to be populated. It will be null when the program is first opened, as `onPrepareOptionsMenu()` is called before the first WebView is initialized.
737 if (currentWebView != null) {
738 // Set the add or edit domain text.
739 if (currentWebView.getDomainSettingsApplied()) {
740 addOrEditDomain.setTitle(R.string.edit_domain_settings);
742 addOrEditDomain.setTitle(R.string.add_domain_settings);
745 // Get the current user agent from the WebView.
746 currentUserAgent = currentWebView.getSettings().getUserAgentString();
748 // Get the current font size from the
749 fontSize = currentWebView.getSettings().getTextZoom();
751 // Set the status of the menu item checkboxes.
752 domStorageMenuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
753 saveFormDataMenuItem.setChecked(currentWebView.getSettings().getSaveFormData()); // Form data can be removed once the minimum API >= 26.
754 easyListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
755 easyPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
756 fanboysAnnoyanceListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
757 fanboysSocialBlockingListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
758 ultraListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
759 ultraPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
760 blockAllThirdPartyRequestsMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
761 swipeToRefreshMenuItem.setChecked(currentWebView.getSwipeToRefresh());
762 wideViewportMenuItem.setChecked(currentWebView.getSettings().getUseWideViewPort());
763 displayImagesMenuItem.setChecked(currentWebView.getSettings().getLoadsImagesAutomatically());
764 nightModeMenuItem.setChecked(currentWebView.getNightMode());
766 // Initialize the display names for the blocklists with the number of blocked requests.
767 blocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
768 easyListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYLIST) + " - " + getString(R.string.easylist));
769 easyPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYPRIVACY) + " - " + getString(R.string.easyprivacy));
770 fanboysAnnoyanceListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " + getString(R.string.fanboys_annoyance_list));
771 fanboysSocialBlockingListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " + getString(R.string.fanboys_social_blocking_list));
772 ultraListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRALIST) + " - " + getString(R.string.ultralist));
773 ultraPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRAPRIVACY) + " - " + getString(R.string.ultraprivacy));
774 blockAllThirdPartyRequestsMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " + getString(R.string.block_all_third_party_requests));
776 // Only modify third-party cookies if the API >= 21.
777 if (Build.VERSION.SDK_INT >= 21) {
778 // Set the status of the third-party cookies checkbox.
779 thirdPartyCookiesMenuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
781 // Enable third-party cookies if first-party cookies are enabled.
782 thirdPartyCookiesMenuItem.setEnabled(cookieManager.acceptCookie());
785 // Enable DOM Storage if JavaScript is enabled.
786 domStorageMenuItem.setEnabled(currentWebView.getSettings().getJavaScriptEnabled());
789 // Set the checked status of the first party cookies menu item.
790 firstPartyCookiesMenuItem.setChecked(cookieManager.acceptCookie());
792 // Enable Clear Cookies if there are any.
793 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
795 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
796 String privateDataDirectoryString = getApplicationInfo().dataDir;
798 // Get a count of the number of files in the Local Storage directory.
799 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
800 int localStorageDirectoryNumberOfFiles = 0;
801 if (localStorageDirectory.exists()) {
802 // `Objects.requireNonNull` removes a lint warning that `localStorageDirectory.list` might produce a null pointed exception if it is dereferenced.
803 localStorageDirectoryNumberOfFiles = Objects.requireNonNull(localStorageDirectory.list()).length;
806 // Get a count of the number of files in the IndexedDB directory.
807 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
808 int indexedDBDirectoryNumberOfFiles = 0;
809 if (indexedDBDirectory.exists()) {
810 // `Objects.requireNonNull` removes a lint warning that `indexedDBDirectory.list` might produce a null pointed exception if it is dereferenced.
811 indexedDBDirectoryNumberOfFiles = Objects.requireNonNull(indexedDBDirectory.list()).length;
814 // Enable Clear DOM Storage if there is any.
815 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
817 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
818 if (Build.VERSION.SDK_INT < 26) {
819 // Get the WebView database.
820 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
822 // Enable the clear form data menu item if there is anything to clear.
823 clearFormDataMenuItem.setEnabled(webViewDatabase.hasFormData());
826 // Enable Clear Data if any of the submenu items are enabled.
827 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
829 // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
830 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListMenuItem.isChecked());
832 // Set the proxy title and check the applied proxy.
834 case ProxyHelper.NONE:
835 // Set the proxy title.
836 proxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_none));
838 // Check the proxy None radio button.
839 menu.findItem(R.id.proxy_none).setChecked(true);
842 case ProxyHelper.TOR:
843 // Set the proxy title.
844 proxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_tor));
846 // Check the proxy Tor radio button.
847 menu.findItem(R.id.proxy_tor).setChecked(true);
850 case ProxyHelper.I2P:
851 // Set the proxy title.
852 proxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_i2p));
854 // Check the proxy I2P radio button.
855 menu.findItem(R.id.proxy_i2p).setChecked(true);
858 case ProxyHelper.CUSTOM:
859 // Set the proxy title.
860 proxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_custom));
862 // Check the proxy Custom radio button.
863 menu.findItem(R.id.proxy_custom).setChecked(true);
867 // Select the current user agent menu item. A switch statement cannot be used because the user agents are not compile time constants.
868 if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) { // Privacy Browser.
869 // Update the user agent menu item title.
870 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_privacy_browser));
872 // Select the Privacy Browser radio box.
873 menu.findItem(R.id.user_agent_privacy_browser).setChecked(true);
874 } else if (currentUserAgent.equals(webViewDefaultUserAgent)) { // WebView Default.
875 // Update the user agent menu item title.
876 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_webview_default));
878 // Select the WebView Default radio box.
879 menu.findItem(R.id.user_agent_webview_default).setChecked(true);
880 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) { // Firefox on Android.
881 // Update the user agent menu item title.
882 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_android));
884 // Select the Firefox on Android radio box.
885 menu.findItem(R.id.user_agent_firefox_on_android).setChecked(true);
886 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) { // Chrome on Android.
887 // Update the user agent menu item title.
888 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_android));
890 // Select the Chrome on Android radio box.
891 menu.findItem(R.id.user_agent_chrome_on_android).setChecked(true);
892 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) { // Safari on iOS.
893 // Update the user agent menu item title.
894 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_ios));
896 // Select the Safari on iOS radio box.
897 menu.findItem(R.id.user_agent_safari_on_ios).setChecked(true);
898 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) { // Firefox on Linux.
899 // Update the user agent menu item title.
900 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_linux));
902 // Select the Firefox on Linux radio box.
903 menu.findItem(R.id.user_agent_firefox_on_linux).setChecked(true);
904 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) { // Chromium on Linux.
905 // Update the user agent menu item title.
906 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chromium_on_linux));
908 // Select the Chromium on Linux radio box.
909 menu.findItem(R.id.user_agent_chromium_on_linux).setChecked(true);
910 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) { // Firefox on Windows.
911 // Update the user agent menu item title.
912 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_windows));
914 // Select the Firefox on Windows radio box.
915 menu.findItem(R.id.user_agent_firefox_on_windows).setChecked(true);
916 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) { // Chrome on Windows.
917 // Update the user agent menu item title.
918 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_windows));
920 // Select the Chrome on Windows radio box.
921 menu.findItem(R.id.user_agent_chrome_on_windows).setChecked(true);
922 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) { // Edge on Windows.
923 // Update the user agent menu item title.
924 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_edge_on_windows));
926 // Select the Edge on Windows radio box.
927 menu.findItem(R.id.user_agent_edge_on_windows).setChecked(true);
928 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) { // Internet Explorer on Windows.
929 // Update the user agent menu item title.
930 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_internet_explorer_on_windows));
932 // Select the Internet on Windows radio box.
933 menu.findItem(R.id.user_agent_internet_explorer_on_windows).setChecked(true);
934 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) { // Safari on macOS.
935 // Update the user agent menu item title.
936 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_macos));
938 // Select the Safari on macOS radio box.
939 menu.findItem(R.id.user_agent_safari_on_macos).setChecked(true);
940 } else { // Custom user agent.
941 // Update the user agent menu item title.
942 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_custom));
944 // Select the Custom radio box.
945 menu.findItem(R.id.user_agent_custom).setChecked(true);
948 // Set the font size title.
949 fontSizeMenuItem.setTitle(getString(R.string.font_size) + " - " + fontSize + "%");
951 // Run all the other default commands.
952 super.onPrepareOptionsMenu(menu);
959 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
960 @SuppressLint("SetJavaScriptEnabled")
961 public boolean onOptionsItemSelected(MenuItem menuItem) {
962 // Get the selected menu item ID.
963 int menuItemId = menuItem.getItemId();
965 // Get a handle for the shared preferences.
966 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
968 // Get a handle for the cookie manager.
969 CookieManager cookieManager = CookieManager.getInstance();
971 // Run the commands that correlate to the selected menu item.
972 switch (menuItemId) {
973 case R.id.toggle_javascript:
974 // Toggle the JavaScript status.
975 currentWebView.getSettings().setJavaScriptEnabled(!currentWebView.getSettings().getJavaScriptEnabled());
977 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
978 updatePrivacyIcons(true);
980 // Display a `Snackbar`.
981 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScrip is enabled.
982 Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
983 } else if (cookieManager.acceptCookie()) { // JavaScript is disabled, but first-party cookies are enabled.
984 Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
985 } else { // Privacy mode.
986 Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
989 // Reload the current WebView.
990 currentWebView.reload();
992 // Consume the event.
996 if (menuItem.getTitle().equals(getString(R.string.refresh))) { // The refresh button was pushed.
997 // Reload the current WebView.
998 currentWebView.reload();
999 } else { // The stop button was pushed.
1000 // Stop the loading of the WebView.
1001 currentWebView.stopLoading();
1004 // Consume the event.
1007 case R.id.bookmarks:
1008 // Get a handle for the drawer layout.
1009 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
1011 // Open the bookmarks drawer.
1012 drawerLayout.openDrawer(GravityCompat.END);
1014 // Consume the event.
1017 case R.id.toggle_first_party_cookies:
1018 // Switch the first-party cookie status.
1019 cookieManager.setAcceptCookie(!cookieManager.acceptCookie());
1021 // Store the first-party cookie status.
1022 currentWebView.setAcceptFirstPartyCookies(cookieManager.acceptCookie());
1024 // Update the menu checkbox.
1025 menuItem.setChecked(cookieManager.acceptCookie());
1027 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1028 updatePrivacyIcons(true);
1030 // Display a snackbar.
1031 if (cookieManager.acceptCookie()) { // First-party cookies are enabled.
1032 Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1033 } else if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is still enabled.
1034 Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1035 } else { // Privacy mode.
1036 Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1039 // Reload the current WebView.
1040 currentWebView.reload();
1042 // Consume the event.
1045 case R.id.toggle_third_party_cookies:
1046 if (Build.VERSION.SDK_INT >= 21) {
1047 // Switch the status of thirdPartyCookiesEnabled.
1048 cookieManager.setAcceptThirdPartyCookies(currentWebView, !cookieManager.acceptThirdPartyCookies(currentWebView));
1050 // Update the menu checkbox.
1051 menuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
1053 // Display a snackbar.
1054 if (cookieManager.acceptThirdPartyCookies(currentWebView)) {
1055 Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1057 Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1060 // Reload the current WebView.
1061 currentWebView.reload();
1062 } // Else do nothing because SDK < 21.
1064 // Consume the event.
1067 case R.id.toggle_dom_storage:
1068 // Toggle the status of domStorageEnabled.
1069 currentWebView.getSettings().setDomStorageEnabled(!currentWebView.getSettings().getDomStorageEnabled());
1071 // Update the menu checkbox.
1072 menuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1074 // Update the privacy icon. `true` refreshes the app bar icons.
1075 updatePrivacyIcons(true);
1077 // Display a snackbar.
1078 if (currentWebView.getSettings().getDomStorageEnabled()) {
1079 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1081 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1084 // Reload the current WebView.
1085 currentWebView.reload();
1087 // Consume the event.
1090 // Form data can be removed once the minimum API >= 26.
1091 case R.id.toggle_save_form_data:
1092 // Switch the status of saveFormDataEnabled.
1093 currentWebView.getSettings().setSaveFormData(!currentWebView.getSettings().getSaveFormData());
1095 // Update the menu checkbox.
1096 menuItem.setChecked(currentWebView.getSettings().getSaveFormData());
1098 // Display a snackbar.
1099 if (currentWebView.getSettings().getSaveFormData()) {
1100 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1102 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1105 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1106 updatePrivacyIcons(true);
1108 // Reload the current WebView.
1109 currentWebView.reload();
1111 // Consume the event.
1114 case R.id.clear_cookies:
1115 Snackbar.make(findViewById(R.id.webviewpager), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1116 .setAction(R.string.undo, v -> {
1117 // Do nothing because everything will be handled by `onDismissed()` below.
1119 .addCallback(new Snackbar.Callback() {
1120 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1122 public void onDismissed(Snackbar snackbar, int event) {
1123 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1124 // Delete the cookies, which command varies by SDK.
1125 if (Build.VERSION.SDK_INT < 21) {
1126 cookieManager.removeAllCookie();
1128 cookieManager.removeAllCookies(null);
1135 // Consume the event.
1138 case R.id.clear_dom_storage:
1139 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1140 .setAction(R.string.undo, v -> {
1141 // Do nothing because everything will be handled by `onDismissed()` below.
1143 .addCallback(new Snackbar.Callback() {
1144 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1146 public void onDismissed(Snackbar snackbar, int event) {
1147 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1148 // Delete the DOM Storage.
1149 WebStorage webStorage = WebStorage.getInstance();
1150 webStorage.deleteAllData();
1152 // Initialize a handler to manually delete the DOM storage files and directories.
1153 Handler deleteDomStorageHandler = new Handler();
1155 // Setup a runnable to manually delete the DOM storage files and directories.
1156 Runnable deleteDomStorageRunnable = () -> {
1158 // Get a handle for the runtime.
1159 Runtime runtime = Runtime.getRuntime();
1161 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1162 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1163 String privateDataDirectoryString = getApplicationInfo().dataDir;
1165 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1166 Process deleteLocalStorageProcess = runtime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1168 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1169 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1170 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1171 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1172 Process deleteDatabasesProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1174 // Wait for the processes to finish.
1175 deleteLocalStorageProcess.waitFor();
1176 deleteIndexProcess.waitFor();
1177 deleteQuotaManagerProcess.waitFor();
1178 deleteQuotaManagerJournalProcess.waitFor();
1179 deleteDatabasesProcess.waitFor();
1180 } catch (Exception exception) {
1181 // Do nothing if an error is thrown.
1185 // Manually delete the DOM storage files after 200 milliseconds.
1186 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
1192 // Consume the event.
1195 // Form data can be remove once the minimum API >= 26.
1196 case R.id.clear_form_data:
1197 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1198 .setAction(R.string.undo, v -> {
1199 // Do nothing because everything will be handled by `onDismissed()` below.
1201 .addCallback(new Snackbar.Callback() {
1202 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1204 public void onDismissed(Snackbar snackbar, int event) {
1205 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1206 // Delete the form data.
1207 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1208 mainWebViewDatabase.clearFormData();
1214 // Consume the event.
1218 // Toggle the EasyList status.
1219 currentWebView.enableBlocklist(NestedScrollWebView.EASYLIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
1221 // Update the menu checkbox.
1222 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
1224 // Reload the current WebView.
1225 currentWebView.reload();
1227 // Consume the event.
1230 case R.id.easyprivacy:
1231 // Toggle the EasyPrivacy status.
1232 currentWebView.enableBlocklist(NestedScrollWebView.EASYPRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
1234 // Update the menu checkbox.
1235 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
1237 // Reload the current WebView.
1238 currentWebView.reload();
1240 // Consume the event.
1243 case R.id.fanboys_annoyance_list:
1244 // Toggle Fanboy's Annoyance List status.
1245 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1247 // Update the menu checkbox.
1248 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1250 // Update the staus of Fanboy's Social Blocking List.
1251 MenuItem fanboysSocialBlockingListMenuItem = optionsMenu.findItem(R.id.fanboys_social_blocking_list);
1252 fanboysSocialBlockingListMenuItem.setEnabled(!currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1254 // Reload the current WebView.
1255 currentWebView.reload();
1257 // Consume the event.
1260 case R.id.fanboys_social_blocking_list:
1261 // Toggle Fanboy's Social Blocking List status.
1262 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1264 // Update the menu checkbox.
1265 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1267 // Reload the current WebView.
1268 currentWebView.reload();
1270 // Consume the event.
1273 case R.id.ultralist:
1274 // Toggle the UltraList status.
1275 currentWebView.enableBlocklist(NestedScrollWebView.ULTRALIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
1277 // Update the menu checkbox.
1278 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
1280 // Reload the current WebView.
1281 currentWebView.reload();
1283 // Consume the event.
1286 case R.id.ultraprivacy:
1287 // Toggle the UltraPrivacy status.
1288 currentWebView.enableBlocklist(NestedScrollWebView.ULTRAPRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
1290 // Update the menu checkbox.
1291 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
1293 // Reload the current WebView.
1294 currentWebView.reload();
1296 // Consume the event.
1299 case R.id.block_all_third_party_requests:
1300 //Toggle the third-party requests blocker status.
1301 currentWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, !currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1303 // Update the menu checkbox.
1304 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1306 // Reload the current WebView.
1307 currentWebView.reload();
1309 // Consume the event.
1312 case R.id.proxy_none:
1313 // Update the proxy mode.
1314 proxyMode = ProxyHelper.NONE;
1316 // Apply the proxy mode.
1319 // Consume the event.
1322 case R.id.proxy_tor:
1323 // Update the proxy mode.
1324 proxyMode = ProxyHelper.TOR;
1326 // Apply the proxy mode.
1329 // Consume the event.
1332 case R.id.proxy_i2p:
1333 // Update the proxy mode.
1334 proxyMode = ProxyHelper.I2P;
1336 // Apply the proxy mode.
1339 // Consume the event.
1342 case R.id.proxy_custom:
1343 // Update the proxy mode.
1344 proxyMode = ProxyHelper.CUSTOM;
1346 // Apply the proxy mode.
1349 // Consume the event.
1352 case R.id.user_agent_privacy_browser:
1353 // Update the user agent.
1354 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
1356 // Reload the current WebView.
1357 currentWebView.reload();
1359 // Consume the event.
1362 case R.id.user_agent_webview_default:
1363 // Update the user agent.
1364 currentWebView.getSettings().setUserAgentString("");
1366 // Reload the current WebView.
1367 currentWebView.reload();
1369 // Consume the event.
1372 case R.id.user_agent_firefox_on_android:
1373 // Update the user agent.
1374 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
1376 // Reload the current WebView.
1377 currentWebView.reload();
1379 // Consume the event.
1382 case R.id.user_agent_chrome_on_android:
1383 // Update the user agent.
1384 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
1386 // Reload the current WebView.
1387 currentWebView.reload();
1389 // Consume the event.
1392 case R.id.user_agent_safari_on_ios:
1393 // Update the user agent.
1394 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
1396 // Reload the current WebView.
1397 currentWebView.reload();
1399 // Consume the event.
1402 case R.id.user_agent_firefox_on_linux:
1403 // Update the user agent.
1404 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
1406 // Reload the current WebView.
1407 currentWebView.reload();
1409 // Consume the event.
1412 case R.id.user_agent_chromium_on_linux:
1413 // Update the user agent.
1414 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
1416 // Reload the current WebView.
1417 currentWebView.reload();
1419 // Consume the event.
1422 case R.id.user_agent_firefox_on_windows:
1423 // Update the user agent.
1424 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
1426 // Reload the current WebView.
1427 currentWebView.reload();
1429 // Consume the event.
1432 case R.id.user_agent_chrome_on_windows:
1433 // Update the user agent.
1434 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
1436 // Reload the current WebView.
1437 currentWebView.reload();
1439 // Consume the event.
1442 case R.id.user_agent_edge_on_windows:
1443 // Update the user agent.
1444 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
1446 // Reload the current WebView.
1447 currentWebView.reload();
1449 // Consume the event.
1452 case R.id.user_agent_internet_explorer_on_windows:
1453 // Update the user agent.
1454 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
1456 // Reload the current WebView.
1457 currentWebView.reload();
1459 // Consume the event.
1462 case R.id.user_agent_safari_on_macos:
1463 // Update the user agent.
1464 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
1466 // Reload the current WebView.
1467 currentWebView.reload();
1469 // Consume the event.
1472 case R.id.user_agent_custom:
1473 // Update the user agent.
1474 currentWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
1476 // Reload the current WebView.
1477 currentWebView.reload();
1479 // Consume the event.
1482 case R.id.font_size:
1483 // Instantiate the font size dialog.
1484 DialogFragment fontSizeDialogFragment = FontSizeDialog.displayDialog(currentWebView.getSettings().getTextZoom());
1486 // Show the font size dialog.
1487 fontSizeDialogFragment.show(getSupportFragmentManager(), getString(R.string.font_size));
1489 // Consume the event.
1492 case R.id.swipe_to_refresh:
1493 // Toggle the stored status of swipe to refresh.
1494 currentWebView.setSwipeToRefresh(!currentWebView.getSwipeToRefresh());
1496 // Get a handle for the swipe refresh layout.
1497 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
1499 // Update the swipe refresh layout.
1500 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
1501 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
1502 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
1503 } else { // Swipe to refresh is disabled.
1504 // Disable the swipe refresh layout.
1505 swipeRefreshLayout.setEnabled(false);
1508 // Consume the event.
1511 case R.id.wide_viewport:
1512 // Toggle the viewport.
1513 currentWebView.getSettings().setUseWideViewPort(!currentWebView.getSettings().getUseWideViewPort());
1515 // Consume the event.
1518 case R.id.display_images:
1519 if (currentWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1520 // Disable loading of images.
1521 currentWebView.getSettings().setLoadsImagesAutomatically(false);
1523 // Reload the website to remove existing images.
1524 currentWebView.reload();
1525 } else { // Images are not currently loaded automatically.
1526 // Enable loading of images. Missing images will be loaded without the need for a reload.
1527 currentWebView.getSettings().setLoadsImagesAutomatically(true);
1530 // Consume the event.
1533 case R.id.night_mode:
1534 // Toggle night mode.
1535 currentWebView.setNightMode(!currentWebView.getNightMode());
1537 // Enable or disable JavaScript according to night mode, the global preference, and any domain settings.
1538 if (currentWebView.getNightMode()) { // Night mode is enabled, which requires JavaScript.
1539 // Enable JavaScript.
1540 currentWebView.getSettings().setJavaScriptEnabled(true);
1541 } else if (currentWebView.getDomainSettingsApplied()) { // Night mode is disabled and domain settings are applied. Set JavaScript according to the domain settings.
1542 // Apply the JavaScript preference that was stored the last time domain settings were loaded.
1543 currentWebView.getSettings().setJavaScriptEnabled(currentWebView.getDomainSettingsJavaScriptEnabled());
1544 } else { // Night mode is disabled and domain settings are not applied. Set JavaScript according to the global preference.
1545 // Apply the JavaScript preference.
1546 currentWebView.getSettings().setJavaScriptEnabled(sharedPreferences.getBoolean("javascript", false));
1549 // Update the privacy icons.
1550 updatePrivacyIcons(false);
1552 // Reload the website.
1553 currentWebView.reload();
1555 // Consume the event.
1558 case R.id.find_on_page:
1559 // Get a handle for the views.
1560 Toolbar toolbar = findViewById(R.id.toolbar);
1561 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
1562 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
1564 // Set the minimum height of the find on page linear layout to match the toolbar.
1565 findOnPageLinearLayout.setMinimumHeight(toolbar.getHeight());
1567 // Hide the toolbar.
1568 toolbar.setVisibility(View.GONE);
1570 // Show the find on page linear layout.
1571 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1573 // Display the keyboard. The app must wait 200 ms before running the command to work around a bug in Android.
1574 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1575 findOnPageEditText.postDelayed(() -> {
1576 // Set the focus on `findOnPageEditText`.
1577 findOnPageEditText.requestFocus();
1579 // Get a handle for the input method manager.
1580 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1582 // Remove the lint warning below that the input method manager might be null.
1583 assert inputMethodManager != null;
1585 // Display the keyboard. `0` sets no input flags.
1586 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1589 // Consume the event.
1593 // Get a print manager instance.
1594 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1596 // Remove the lint error below that print manager might be null.
1597 assert printManager != null;
1599 // Create a print document adapter from the current WebView.
1600 PrintDocumentAdapter printDocumentAdapter = currentWebView.createPrintDocumentAdapter();
1602 // Print the document.
1603 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1605 // Consume the event.
1609 // Instantiate the save dialog.
1610 DialogFragment saveDialogFragment = SaveDialog.saveUrl(StoragePermissionDialog.SAVE_URL, currentWebView.getCurrentUrl(), currentWebView.getSettings().getUserAgentString(),
1611 currentWebView.getAcceptFirstPartyCookies());
1613 // Show the save dialog. It must be named `save_dialog` so that the file picked can update the file name.
1614 saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
1616 // Consume the event.
1619 case R.id.save_as_archive:
1620 // Instantiate the save webpage archive dialog.
1621 DialogFragment saveWebpageArchiveDialogFragment = SaveDialog.saveUrl(StoragePermissionDialog.SAVE_AS_ARCHIVE, currentWebView.getCurrentUrl(), currentWebView.getSettings().getUserAgentString(),
1622 currentWebView.getAcceptFirstPartyCookies());
1624 // Show the save webpage archive dialog. It must be named `save_dialog` so that the file picked can update the file name.
1625 saveWebpageArchiveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
1627 // Consume the event.
1630 case R.id.save_as_image:
1631 // Instantiate the save webpage image dialog. It must be named `save_webpage` so that the file picked can update the file name.
1632 DialogFragment saveWebpageImageDialogFragment = SaveDialog.saveUrl(StoragePermissionDialog.SAVE_AS_IMAGE, currentWebView.getCurrentUrl(), currentWebView.getSettings().getUserAgentString(),
1633 currentWebView.getAcceptFirstPartyCookies());
1635 // Show the save webpage image dialog. It must be named `save_dialog` so that the file picked can update the file name.
1636 saveWebpageImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
1638 // Consume the event.
1641 case R.id.add_to_homescreen:
1642 // Instantiate the create home screen shortcut dialog.
1643 DialogFragment createHomeScreenShortcutDialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView.getTitle(), currentWebView.getUrl(),
1644 currentWebView.getFavoriteOrDefaultIcon());
1646 // Show the create home screen shortcut dialog.
1647 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
1649 // Consume the event.
1652 case R.id.view_source:
1653 // Create an intent to launch the view source activity.
1654 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
1656 // Add the variables to the intent.
1657 viewSourceIntent.putExtra("user_agent", currentWebView.getSettings().getUserAgentString());
1658 viewSourceIntent.putExtra("current_url", currentWebView.getUrl());
1661 startActivity(viewSourceIntent);
1663 // Consume the event.
1666 case R.id.share_url:
1667 // Setup the share string.
1668 String shareString = currentWebView.getTitle() + " – " + currentWebView.getUrl();
1670 // Create the share intent.
1671 Intent shareIntent = new Intent(Intent.ACTION_SEND);
1672 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1673 shareIntent.setType("text/plain");
1676 startActivity(Intent.createChooser(shareIntent, getString(R.string.share_url)));
1678 // Consume the event.
1681 case R.id.open_with_app:
1682 // Open the URL with an outside app.
1683 openWithApp(currentWebView.getUrl());
1685 // Consume the event.
1688 case R.id.open_with_browser:
1689 // Open the URL with an outside browser.
1690 openWithBrowser(currentWebView.getUrl());
1692 // Consume the event.
1695 case R.id.add_or_edit_domain:
1696 if (currentWebView.getDomainSettingsApplied()) { // Edit the current domain settings.
1697 // Reapply the domain settings on returning to `MainWebViewActivity`.
1698 reapplyDomainSettingsOnRestart = true;
1700 // Create an intent to launch the domains activity.
1701 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1703 // Add the extra information to the intent.
1704 domainsIntent.putExtra("load_domain", currentWebView.getDomainSettingsDatabaseId());
1705 domainsIntent.putExtra("close_on_back", true);
1706 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1708 // Get the current certificate.
1709 SslCertificate sslCertificate = currentWebView.getCertificate();
1711 // Check to see if the SSL certificate is populated.
1712 if (sslCertificate != null) {
1713 // Extract the certificate to strings.
1714 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1715 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1716 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1717 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1718 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1719 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1720 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1721 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1723 // Add the certificate to the intent.
1724 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1725 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1726 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1727 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1728 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1729 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1730 domainsIntent.putExtra("ssl_start_date", startDateLong);
1731 domainsIntent.putExtra("ssl_end_date", endDateLong);
1734 // Check to see if the current IP addresses have been received.
1735 if (currentWebView.hasCurrentIpAddresses()) {
1736 // Add the current IP addresses to the intent.
1737 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1741 startActivity(domainsIntent);
1742 } else { // Add a new domain.
1743 // Apply the new domain settings on returning to `MainWebViewActivity`.
1744 reapplyDomainSettingsOnRestart = true;
1746 // Get the current domain
1747 Uri currentUri = Uri.parse(currentWebView.getUrl());
1748 String currentDomain = currentUri.getHost();
1750 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1751 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1753 // Create the domain and store the database ID.
1754 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1756 // Create an intent to launch the domains activity.
1757 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1759 // Add the extra information to the intent.
1760 domainsIntent.putExtra("load_domain", newDomainDatabaseId);
1761 domainsIntent.putExtra("close_on_back", true);
1762 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1764 // Get the current certificate.
1765 SslCertificate sslCertificate = currentWebView.getCertificate();
1767 // Check to see if the SSL certificate is populated.
1768 if (sslCertificate != null) {
1769 // Extract the certificate to strings.
1770 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1771 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1772 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1773 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1774 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1775 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1776 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1777 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1779 // Add the certificate to the intent.
1780 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1781 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1782 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1783 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1784 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1785 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1786 domainsIntent.putExtra("ssl_start_date", startDateLong);
1787 domainsIntent.putExtra("ssl_end_date", endDateLong);
1790 // Check to see if the current IP addresses have been received.
1791 if (currentWebView.hasCurrentIpAddresses()) {
1792 // Add the current IP addresses to the intent.
1793 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1797 startActivity(domainsIntent);
1800 // Consume the event.
1803 case R.id.ad_consent:
1804 // Instantiate the ad consent dialog.
1805 DialogFragment adConsentDialogFragment = new AdConsentDialog();
1807 // Display the ad consent dialog.
1808 adConsentDialogFragment.show(getSupportFragmentManager(), getString(R.string.ad_consent));
1810 // Consume the event.
1814 // Don't consume the event.
1815 return super.onOptionsItemSelected(menuItem);
1819 // removeAllCookies is deprecated, but it is required for API < 21.
1821 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1822 // Get the menu item ID.
1823 int menuItemId = menuItem.getItemId();
1825 // Get a handle for the shared preferences.
1826 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1828 // Run the commands that correspond to the selected menu item.
1829 switch (menuItemId) {
1830 case R.id.clear_and_exit:
1831 // Clear and exit Privacy Browser.
1836 // Load the homepage.
1837 loadUrl(currentWebView, sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
1841 if (currentWebView.canGoBack()) {
1842 // Get the current web back forward list.
1843 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
1845 // Get the previous entry URL.
1846 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
1848 // Apply the domain settings.
1849 applyDomainSettings(currentWebView, previousUrl, false, false);
1851 // Load the previous website in the history.
1852 currentWebView.goBack();
1857 if (currentWebView.canGoForward()) {
1858 // Get the current web back forward list.
1859 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
1861 // Get the next entry URL.
1862 String nextUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() + 1).getUrl();
1864 // Apply the domain settings.
1865 applyDomainSettings(currentWebView, nextUrl, false, false);
1867 // Load the next website in the history.
1868 currentWebView.goForward();
1873 // Instantiate the URL history dialog.
1874 DialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView.getWebViewFragmentId());
1876 // Show the URL history dialog.
1877 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
1881 // Instantiate the open file dialog.
1882 DialogFragment openDialogFragment = new OpenDialog();
1884 // Show the open file dialog.
1885 openDialogFragment.show(getSupportFragmentManager(), getString(R.string.open));
1889 // Populate the resource requests.
1890 RequestsActivity.resourceRequests = currentWebView.getResourceRequests();
1892 // Create an intent to launch the Requests activity.
1893 Intent requestsIntent = new Intent(this, RequestsActivity.class);
1895 // Add the block third-party requests status to the intent.
1896 requestsIntent.putExtra("block_all_third_party_requests", currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1899 startActivity(requestsIntent);
1902 case R.id.downloads:
1903 // Launch the system Download Manager.
1904 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1906 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1907 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1910 startActivity(downloadManagerIntent);
1914 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
1915 reapplyDomainSettingsOnRestart = true;
1917 // Launch the domains activity.
1918 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1920 // Add the extra information to the intent.
1921 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1923 // Get the current certificate.
1924 SslCertificate sslCertificate = currentWebView.getCertificate();
1926 // Check to see if the SSL certificate is populated.
1927 if (sslCertificate != null) {
1928 // Extract the certificate to strings.
1929 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1930 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1931 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1932 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1933 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1934 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1935 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1936 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1938 // Add the certificate to the intent.
1939 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1940 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1941 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1942 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1943 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1944 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1945 domainsIntent.putExtra("ssl_start_date", startDateLong);
1946 domainsIntent.putExtra("ssl_end_date", endDateLong);
1949 // Check to see if the current IP addresses have been received.
1950 if (currentWebView.hasCurrentIpAddresses()) {
1951 // Add the current IP addresses to the intent.
1952 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1956 startActivity(domainsIntent);
1960 // Set the flag to reapply app settings on restart when returning from Settings.
1961 reapplyAppSettingsOnRestart = true;
1963 // Set the flag to reapply the domain settings on restart when returning from Settings.
1964 reapplyDomainSettingsOnRestart = true;
1966 // Launch the settings activity.
1967 Intent settingsIntent = new Intent(this, SettingsActivity.class);
1968 startActivity(settingsIntent);
1971 case R.id.import_export:
1972 // Launch the import/export activity.
1973 Intent importExportIntent = new Intent (this, ImportExportActivity.class);
1974 startActivity(importExportIntent);
1978 // Launch the logcat activity.
1979 Intent logcatIntent = new Intent(this, LogcatActivity.class);
1980 startActivity(logcatIntent);
1984 // Launch `GuideActivity`.
1985 Intent guideIntent = new Intent(this, GuideActivity.class);
1986 startActivity(guideIntent);
1990 // Create an intent to launch the about activity.
1991 Intent aboutIntent = new Intent(this, AboutActivity.class);
1993 // Create a string array for the blocklist versions.
1994 String[] blocklistVersions = new String[] {easyList.get(0).get(0)[0], easyPrivacy.get(0).get(0)[0], fanboysAnnoyanceList.get(0).get(0)[0], fanboysSocialList.get(0).get(0)[0],
1995 ultraList.get(0).get(0)[0], ultraPrivacy.get(0).get(0)[0]};
1997 // Add the blocklist versions to the intent.
1998 aboutIntent.putExtra("blocklist_versions", blocklistVersions);
2001 startActivity(aboutIntent);
2005 // Get a handle for the drawer layout.
2006 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
2008 // Close the navigation drawer.
2009 drawerLayout.closeDrawer(GravityCompat.START);
2014 public void onPostCreate(Bundle savedInstanceState) {
2015 // Run the default commands.
2016 super.onPostCreate(savedInstanceState);
2018 // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished. This creates the navigation drawer icon.
2019 actionBarDrawerToggle.syncState();
2023 public void onConfigurationChanged(@NonNull Configuration newConfig) {
2024 // Run the default commands.
2025 super.onConfigurationChanged(newConfig);
2027 // Get the status bar pixel size.
2028 int statusBarResourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
2029 int statusBarPixelSize = getResources().getDimensionPixelSize(statusBarResourceId);
2031 // Get the resource density.
2032 float screenDensity = getResources().getDisplayMetrics().density;
2034 // Recalculate the drawer header padding.
2035 drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
2036 drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
2037 drawerHeaderPaddingBottom = (int) (8 * screenDensity);
2039 // Reload the ad for the free flavor if not in full screen mode.
2040 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2041 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2042 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
2045 // `invalidateOptionsMenu` should recalculate the number of action buttons from the menu to display on the app bar, but it doesn't because of the this bug:
2046 // https://code.google.com/p/android/issues/detail?id=20493#c8
2047 // ActivityCompat.invalidateOptionsMenu(this);
2051 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2052 // Store the hit test result.
2053 final WebView.HitTestResult hitTestResult = currentWebView.getHitTestResult();
2055 // Define the URL strings.
2056 final String imageUrl;
2057 final String linkUrl;
2059 // Get handles for the system managers.
2060 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2062 // Remove the lint errors below that the clipboard manager might be null.
2063 assert clipboardManager != null;
2065 // Process the link according to the type.
2066 switch (hitTestResult.getType()) {
2067 // `SRC_ANCHOR_TYPE` is a link.
2068 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2069 // Get the target URL.
2070 linkUrl = hitTestResult.getExtra();
2072 // Set the target URL as the title of the `ContextMenu`.
2073 menu.setHeaderTitle(linkUrl);
2075 // Add an Open in New Tab entry.
2076 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2077 // Load the link URL in a new tab and move to it.
2078 addNewTab(linkUrl, true);
2080 // Consume the event.
2084 // Add an Open in Background entry.
2085 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2086 // Load the link URL in a new tab but do not move to it.
2087 addNewTab(linkUrl, false);
2089 // Consume the event.
2093 // Add an Open with App entry.
2094 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2095 openWithApp(linkUrl);
2097 // Consume the event.
2101 // Add an Open with Browser entry.
2102 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2103 openWithBrowser(linkUrl);
2105 // Consume the event.
2109 // Add a Copy URL entry.
2110 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2111 // Save the link URL in a `ClipData`.
2112 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2114 // Set the `ClipData` as the clipboard's primary clip.
2115 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2117 // Consume the event.
2121 // Add a Save URL entry.
2122 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2123 // Instantiate the save dialog.
2124 DialogFragment saveDialogFragment = SaveDialog.saveUrl(StoragePermissionDialog.SAVE_URL, linkUrl, currentWebView.getSettings().getUserAgentString(),
2125 currentWebView.getAcceptFirstPartyCookies());
2127 // Show the save dialog. It must be named `save_dialog` so that the file picker can update the file name.
2128 saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
2130 // Consume the event.
2134 // Add an empty Cancel entry, which by default closes the context menu.
2135 menu.add(R.string.cancel);
2138 // `IMAGE_TYPE` is an image.
2139 case WebView.HitTestResult.IMAGE_TYPE:
2140 // Get the image URL.
2141 imageUrl = hitTestResult.getExtra();
2143 // Set the image URL as the title of the context menu.
2144 menu.setHeaderTitle(imageUrl);
2146 // Add an Open in New Tab entry.
2147 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2148 // Load the image in a new tab.
2149 addNewTab(imageUrl, true);
2151 // Consume the event.
2155 // Add an Open with App entry.
2156 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2157 // Open the image URL with an external app.
2158 openWithApp(imageUrl);
2160 // Consume the event.
2164 // Add an Open with Browser entry.
2165 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2166 // Open the image URL with an external browser.
2167 openWithBrowser(imageUrl);
2169 // Consume the event.
2173 // Add a View Image entry.
2174 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2175 // Load the image in the current tab.
2176 loadUrl(currentWebView, imageUrl);
2178 // Consume the event.
2182 // Add a Save Image entry.
2183 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2184 // Instantiate the save dialog.
2185 DialogFragment saveDialogFragment = SaveDialog.saveUrl(StoragePermissionDialog.SAVE_URL, imageUrl, currentWebView.getSettings().getUserAgentString(),
2186 currentWebView.getAcceptFirstPartyCookies());
2188 // Show the save dialog. It must be named `save_dialog` so that the file picked can update the file name.
2189 saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
2191 // Consume the event.
2195 // Add a Copy URL entry.
2196 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2197 // Save the image URL in a clip data.
2198 ClipData imageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2200 // Set the clip data as the clipboard's primary clip.
2201 clipboardManager.setPrimaryClip(imageTypeClipData);
2203 // Consume the event.
2207 // Add an empty Cancel entry, which by default closes the context menu.
2208 menu.add(R.string.cancel);
2211 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2212 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2213 // Get the image URL.
2214 imageUrl = hitTestResult.getExtra();
2216 // Instantiate a handler.
2217 Handler handler = new Handler();
2219 // Get a message from the handler.
2220 Message message = handler.obtainMessage();
2222 // Request the image details from the last touched node be returned in the message.
2223 currentWebView.requestFocusNodeHref(message);
2225 // Get the link URL from the message data.
2226 linkUrl = message.getData().getString("url");
2228 // Set the link URL as the title of the context menu.
2229 menu.setHeaderTitle(linkUrl);
2231 // Add an Open in New Tab entry.
2232 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2233 // Load the link URL in a new tab and move to it.
2234 addNewTab(linkUrl, true);
2236 // Consume the event.
2240 // Add an Open in Background entry.
2241 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2242 // Lod the link URL in a new tab but do not move to it.
2243 addNewTab(linkUrl, false);
2245 // Consume the event.
2249 // Add an Open Image in New Tab entry.
2250 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2251 // Load the image in a new tab and move to it.
2252 addNewTab(imageUrl, true);
2254 // Consume the event.
2258 // Add an Open with App entry.
2259 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2260 // Open the link URL with an external app.
2261 openWithApp(linkUrl);
2263 // Consume the event.
2267 // Add an Open with Browser entry.
2268 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2269 // Open the link URL with an external browser.
2270 openWithBrowser(linkUrl);
2272 // Consume the event.
2276 // Add a View Image entry.
2277 menu.add(R.string.view_image).setOnMenuItemClickListener((MenuItem item) -> {
2278 // View the image in the current tab.
2279 loadUrl(currentWebView, imageUrl);
2281 // Consume the event.
2285 // Add a Save Image entry.
2286 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2287 // Instantiate the save dialog.
2288 DialogFragment saveDialogFragment = SaveDialog.saveUrl(StoragePermissionDialog.SAVE_URL, imageUrl, currentWebView.getSettings().getUserAgentString(),
2289 currentWebView.getAcceptFirstPartyCookies());
2291 // Show the save raw dialog. It must be named `save_dialog` so that the file picked can update the file name.
2292 saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
2294 // Consume the event.
2298 // Add a Copy URL entry.
2299 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2300 // Save the link URL in a clip data.
2301 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2303 // Set the clip data as the clipboard's primary clip.
2304 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2306 // Consume the event.
2310 // Add a Save URL entry.
2311 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2312 // Instantiate the save dialog.
2313 DialogFragment saveDialogFragment = SaveDialog.saveUrl(StoragePermissionDialog.SAVE_URL, linkUrl, currentWebView.getSettings().getUserAgentString(),
2314 currentWebView.getAcceptFirstPartyCookies());
2316 // Show the save raw dialog. It must be named `save_dialog` so that the file picked can update the file name.
2317 saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
2319 // Consume the event.
2323 // Add an empty Cancel entry, which by default closes the context menu.
2324 menu.add(R.string.cancel);
2327 case WebView.HitTestResult.EMAIL_TYPE:
2328 // Get the target URL.
2329 linkUrl = hitTestResult.getExtra();
2331 // Set the target URL as the title of the `ContextMenu`.
2332 menu.setHeaderTitle(linkUrl);
2334 // Add a Write Email entry.
2335 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2336 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2337 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2339 // Parse the url and set it as the data for the `Intent`.
2340 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2342 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2343 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2346 startActivity(emailIntent);
2348 // Consume the event.
2352 // Add a Copy Email Address entry.
2353 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2354 // Save the email address in a `ClipData`.
2355 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2357 // Set the `ClipData` as the clipboard's primary clip.
2358 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2360 // Consume the event.
2364 // Add an empty Cancel entry, which by default closes the context menu.
2365 menu.add(R.string.cancel);
2371 public void onCreateBookmark(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2372 // Get a handle for the bookmarks list view.
2373 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2376 Dialog dialog = dialogFragment.getDialog();
2378 // Remove the incorrect lint warning below that the dialog might be null.
2379 assert dialog != null;
2381 // Get the views from the dialog fragment.
2382 EditText createBookmarkNameEditText = dialog.findViewById(R.id.create_bookmark_name_edittext);
2383 EditText createBookmarkUrlEditText = dialog.findViewById(R.id.create_bookmark_url_edittext);
2385 // Extract the strings from the edit texts.
2386 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2387 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2389 // Create a favorite icon byte array output stream.
2390 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2392 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2393 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2395 // Convert the favorite icon byte array stream to a byte array.
2396 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2398 // Display the new bookmark below the current items in the (0 indexed) list.
2399 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2401 // Create the bookmark.
2402 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2404 // Update the bookmarks cursor with the current contents of this folder.
2405 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2407 // Update the list view.
2408 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2410 // Scroll to the new bookmark.
2411 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2415 public void onCreateBookmarkFolder(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2416 // Get a handle for the bookmarks list view.
2417 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2420 Dialog dialog = dialogFragment.getDialog();
2422 // Remove the incorrect lint warning below that the dialog might be null.
2423 assert dialog != null;
2425 // Get handles for the views in the dialog fragment.
2426 EditText createFolderNameEditText = dialog.findViewById(R.id.create_folder_name_edittext);
2427 RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.create_folder_default_icon_radiobutton);
2428 ImageView folderIconImageView = dialog.findViewById(R.id.create_folder_default_icon);
2430 // Get new folder name string.
2431 String folderNameString = createFolderNameEditText.getText().toString();
2433 // Create a folder icon bitmap.
2434 Bitmap folderIconBitmap;
2436 // Set the folder icon bitmap according to the dialog.
2437 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
2438 // Get the default folder icon drawable.
2439 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2441 // Convert the folder icon drawable to a bitmap drawable.
2442 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2444 // Convert the folder icon bitmap drawable to a bitmap.
2445 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2446 } else { // Use the WebView favorite icon.
2447 // Copy the favorite icon bitmap to the folder icon bitmap.
2448 folderIconBitmap = favoriteIconBitmap;
2451 // Create a folder icon byte array output stream.
2452 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2454 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2455 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2457 // Convert the folder icon byte array stream to a byte array.
2458 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2460 // Move all the bookmarks down one in the display order.
2461 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2462 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2463 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2466 // Create the folder, which will be placed at the top of the `ListView`.
2467 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2469 // Update the bookmarks cursor with the current contents of this folder.
2470 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2472 // Update the `ListView`.
2473 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2475 // Scroll to the new folder.
2476 bookmarksListView.setSelection(0);
2480 public void onSaveBookmark(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, Bitmap favoriteIconBitmap) {
2482 Dialog dialog = dialogFragment.getDialog();
2484 // Remove the incorrect lint warning below that the dialog might be null.
2485 assert dialog != null;
2487 // Get handles for the views from the dialog.
2488 EditText editBookmarkNameEditText = dialog.findViewById(R.id.edit_bookmark_name_edittext);
2489 EditText editBookmarkUrlEditText = dialog.findViewById(R.id.edit_bookmark_url_edittext);
2490 RadioButton currentBookmarkIconRadioButton = dialog.findViewById(R.id.edit_bookmark_current_icon_radiobutton);
2492 // Store the bookmark strings.
2493 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
2494 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
2496 // Update the bookmark.
2497 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
2498 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
2499 } else { // Update the bookmark using the `WebView` favorite icon.
2500 // Create a favorite icon byte array output stream.
2501 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2503 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2504 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
2506 // Convert the favorite icon byte array stream to a byte array.
2507 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
2509 // Update the bookmark and the favorite icon.
2510 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
2513 // Update the bookmarks cursor with the current contents of this folder.
2514 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2516 // Update the list view.
2517 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2521 public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, Bitmap favoriteIconBitmap) {
2523 Dialog dialog = dialogFragment.getDialog();
2525 // Remove the incorrect lint warning below that the dialog might be null.
2526 assert dialog != null;
2528 // Get handles for the views from `dialogFragment`.
2529 EditText editFolderNameEditText = dialog.findViewById(R.id.edit_folder_name_edittext);
2530 RadioButton currentFolderIconRadioButton = dialog.findViewById(R.id.edit_folder_current_icon_radiobutton);
2531 RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.edit_folder_default_icon_radiobutton);
2532 ImageView defaultFolderIconImageView = dialog.findViewById(R.id.edit_folder_default_icon_imageview);
2534 // Get the new folder name.
2535 String newFolderNameString = editFolderNameEditText.getText().toString();
2537 // Check if the favorite icon has changed.
2538 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
2539 // Update the name in the database.
2540 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2541 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
2542 // Create the new folder icon Bitmap.
2543 Bitmap folderIconBitmap;
2545 // Populate the new folder icon bitmap.
2546 if (defaultFolderIconRadioButton.isChecked()) {
2547 // Get the default folder icon drawable.
2548 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2550 // Convert the folder icon drawable to a bitmap drawable.
2551 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2553 // Convert the folder icon bitmap drawable to a bitmap.
2554 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2555 } else { // Use the `WebView` favorite icon.
2556 // Copy the favorite icon bitmap to the folder icon bitmap.
2557 folderIconBitmap = favoriteIconBitmap;
2560 // Create a folder icon byte array output stream.
2561 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2563 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2564 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2566 // Convert the folder icon byte array stream to a byte array.
2567 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2569 // Update the folder icon in the database.
2570 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, newFolderIconByteArray);
2571 } else { // The folder icon and the name have changed.
2572 // Get the new folder icon `Bitmap`.
2573 Bitmap folderIconBitmap;
2574 if (defaultFolderIconRadioButton.isChecked()) {
2575 // Get the default folder icon drawable.
2576 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2578 // Convert the folder icon drawable to a bitmap drawable.
2579 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2581 // Convert the folder icon bitmap drawable to a bitmap.
2582 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2583 } else { // Use the `WebView` favorite icon.
2584 // Copy the favorite icon bitmap to the folder icon bitmap.
2585 folderIconBitmap = favoriteIconBitmap;
2588 // Create a folder icon byte array output stream.
2589 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2591 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2592 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2594 // Convert the folder icon byte array stream to a byte array.
2595 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2597 // Update the folder name and icon in the database.
2598 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, newFolderIconByteArray);
2601 // Update the bookmarks cursor with the current contents of this folder.
2602 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2604 // Update the `ListView`.
2605 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2608 // Override `onBackPressed` to handle the navigation drawer and and the WebViews.
2610 public void onBackPressed() {
2611 // Get a handle for the drawer layout and the tab layout.
2612 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
2613 TabLayout tabLayout = findViewById(R.id.tablayout);
2615 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
2616 // Close the navigation drawer.
2617 drawerLayout.closeDrawer(GravityCompat.START);
2618 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
2619 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
2620 // close the bookmarks drawer.
2621 drawerLayout.closeDrawer(GravityCompat.END);
2622 } else { // A subfolder is displayed.
2623 // Place the former parent folder in `currentFolder`.
2624 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolderName(currentBookmarksFolder);
2626 // Load the new folder.
2627 loadBookmarksFolder();
2629 } else if (displayingFullScreenVideo) { // A full screen video is shown.
2630 // Get a handle for the layouts.
2631 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
2632 RelativeLayout mainContentRelativeLayout = findViewById(R.id.main_content_relativelayout);
2633 FrameLayout fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
2635 // Re-enable the screen timeout.
2636 fullScreenVideoFrameLayout.setKeepScreenOn(false);
2638 // Unset the full screen video flag.
2639 displayingFullScreenVideo = false;
2641 // Remove all the views from the full screen video frame layout.
2642 fullScreenVideoFrameLayout.removeAllViews();
2644 // Hide the full screen video frame layout.
2645 fullScreenVideoFrameLayout.setVisibility(View.GONE);
2647 // Enable the sliding drawers.
2648 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
2650 // Show the main content relative layout.
2651 mainContentRelativeLayout.setVisibility(View.VISIBLE);
2653 // Apply the appropriate full screen mode flags.
2654 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
2655 // Hide the app bar if specified.
2657 // Get handles for the views.
2658 LinearLayout tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
2659 ActionBar actionBar = getSupportActionBar();