Move Refresh to the top of the options menu. https://redmine.stoutner.com/issues/526
[PrivacyBrowser.git] / app / src / main / java / com / stoutner / privacybrowser / activities / MainWebViewActivity.java
1 /*
2  * Copyright © 2015-2020 Soren Stoutner <soren@stoutner.com>.
3  *
4  * Download cookie code contributed 2017 Hendrik Knackstedt.  Copyright assigned to Soren Stoutner <soren@stoutner.com>.
5  *
6  * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
7  *
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.
12  *
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.
17  *
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/>.
20  */
21
22 package com.stoutner.privacybrowser.activities;
23
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;
94
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;
108
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;
114
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;
148
149 import java.io.ByteArrayInputStream;
150 import java.io.ByteArrayOutputStream;
151 import java.io.File;
152 import java.io.IOException;
153 import java.io.UnsupportedEncodingException;
154 import java.net.MalformedURLException;
155 import java.net.URL;
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;
166
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 {
171
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";
174
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;
177
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;
181
182     // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`.  It is also used in `onRestart()`.
183     public static boolean restartFromBookmarksActivity;
184
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;
188
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;
196
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;
201
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;
206
207
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;
213
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;
217
218     // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
219     private final Map<String, String> customHeaders = new HashMap<>();
220
221     // The search URL is set in `applyAppSettings()` and used in `onNewIntent()`, `loadUrlFromTextBox()`, `initializeApp()`, and `initializeWebView()`.
222     private String searchURL;
223
224     // The options menu is set in `onCreateOptionsMenu()` and used in `onOptionsItemSelected()`, `updatePrivacyIcons()`, and `initializeWebView()`.
225     private Menu optionsMenu;
226
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;
234
235     // `webViewDefaultUserAgent` is used in `onCreate()` and `onPrepareOptionsMenu()`.
236     private String webViewDefaultUserAgent;
237
238     // The incognito mode is set in `applyAppSettings()` and used in `initializeWebView()`.
239     private boolean incognitoModeEnabled;
240
241     // The full screen browsing mode tracker is set it `applyAppSettings()` and used in `initializeWebView()`.
242     private boolean fullScreenBrowsingModeEnabled;
243
244     // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
245     private boolean inFullScreenBrowsingMode;
246
247     // The app bar trackers are set in `applyAppSettings()` and used in `initializeWebView()`.
248     private boolean hideAppBar;
249     private boolean scrollAppBar;
250
251     // The loading new intent tracker is set in `onNewIntent()` and used in `setCurrentWebView()`.
252     private boolean loadingNewIntent;
253
254     // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
255     private boolean reapplyDomainSettingsOnRestart;
256
257     // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
258     private boolean reapplyAppSettingsOnRestart;
259
260     // `displayingFullScreenVideo` is used in `onCreate()` and `onResume()`.
261     private boolean displayingFullScreenVideo;
262
263     // `orbotStatusBroadcastReceiver` is used in `onCreate()` and `onDestroy()`.
264     private BroadcastReceiver orbotStatusBroadcastReceiver;
265
266     // The waiting for proxy boolean is used in `onResume()`, `initializeApp()` and `applyProxy()`.
267     private boolean waitingForProxy = false;
268
269     // The action bar drawer toggle is initialized in `onCreate()` and used in `onResume()`.
270     private ActionBarDrawerToggle actionBarDrawerToggle;
271
272     // The color spans are used in `onCreate()` and `highlightUrlText()`.
273     private ForegroundColorSpan redColorSpan;
274     private ForegroundColorSpan initialGrayColorSpan;
275     private ForegroundColorSpan finalGrayColorSpan;
276
277     // The drawer header padding variables are used in `onCreate()` and `onConfigurationChanged()`.
278     private int drawerHeaderPaddingLeftAndRight;
279     private int drawerHeaderPaddingTop;
280     private int drawerHeaderPaddingBottom;
281
282     // `bookmarksDatabaseHelper` is used in `onCreate()`, `onDestroy`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`,
283     // and `loadBookmarksFolder()`.
284     private BookmarksDatabaseHelper bookmarksDatabaseHelper;
285
286     // `bookmarksCursor` is used in `onDestroy()`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
287     private Cursor bookmarksCursor;
288
289     // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
290     private CursorAdapter bookmarksCursorAdapter;
291
292     // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
293     private String oldFolderNameString;
294
295     // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
296     private ValueCallback<Uri[]> fileChooserCallback;
297
298     // The default progress view offsets are set in `onCreate()` and used in `initializeWebView()`.
299     private int defaultProgressViewStartOffset;
300     private int defaultProgressViewEndOffset;
301
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;
304
305     // The URL sanitizers are set in `applyAppSettings()` and used in `sanitizeUrl()`.
306     private boolean sanitizeGoogleAnalytics;
307     private boolean sanitizeFacebookClickIds;
308     private boolean sanitizeTwitterAmpRedirects;
309
310     // The file path strings are used in `onSaveWebpage()` and `onRequestPermissionResult()`
311     private String openFilePath;
312     private String saveWebpageUrl;
313     private String saveWebpageFilePath;
314
315     @Override
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         if (Build.VERSION.SDK_INT >= 21) {
320             WebView.enableSlowWholeDocumentDraw();
321         }
322
323         // Initialize the default preference values the first time the program is run.  `false` keeps this command from resetting any current preferences back to default.
324         PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
325
326         // Get a handle for the shared preferences.
327         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
328
329         // Get the theme and screenshot preferences.
330         boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
331         boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
332
333         // Disable screenshots if not allowed.
334         if (!allowScreenshots) {
335             getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
336         }
337
338         // Set the activity theme.
339         if (darkTheme) {
340             setTheme(R.style.PrivacyBrowserDark);
341         } else {
342             setTheme(R.style.PrivacyBrowserLight);
343         }
344
345         // Run the default commands.
346         super.onCreate(savedInstanceState);
347
348         // Set the content view.
349         setContentView(R.layout.main_framelayout);
350
351         // Get handles for the views that need to be modified.
352         DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
353         Toolbar toolbar = findViewById(R.id.toolbar);
354         ViewPager webViewPager = findViewById(R.id.webviewpager);
355
356         // Set the action bar.  `SupportActionBar` must be used until the minimum API is >= 21.
357         setSupportActionBar(toolbar);
358
359         // Get a handle for the action bar.
360         ActionBar actionBar = getSupportActionBar();
361
362         // This is needed to get rid of the Android Studio warning that the action bar might be null.
363         assert actionBar != null;
364
365         // Add the custom layout, which shows the URL text bar.
366         actionBar.setCustomView(R.layout.url_app_bar);
367         actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
368
369         // Initially disable the sliding drawers.  They will be enabled once the blocklists are loaded.
370         drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
371
372         // Create the hamburger icon at the start of the AppBar.
373         actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
374
375         // Initialize the web view pager adapter.
376         webViewPagerAdapter = new WebViewPagerAdapter(getSupportFragmentManager());
377
378         // Set the pager adapter on the web view pager.
379         webViewPager.setAdapter(webViewPagerAdapter);
380
381         // Store up to 100 tabs in memory.
382         webViewPager.setOffscreenPageLimit(100);
383
384         // Populate the blocklists.
385         new PopulateBlocklists(this, this).execute();
386     }
387
388     @Override
389     protected void onNewIntent(Intent intent) {
390         // Run the default commands.
391         super.onNewIntent(intent);
392
393         // Replace the intent that started the app with this one.
394         setIntent(intent);
395
396         // 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()`.
397         if (ultraPrivacy != null) {
398             // Get the information from the intent.
399             String intentAction = intent.getAction();
400             Uri intentUriData = intent.getData();
401
402             // Determine if this is a web search.
403             boolean isWebSearch = ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH));
404
405             // 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.
406             if (intentUriData != null || isWebSearch) {
407                 // Get the shared preferences.
408                 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
409
410                 // Create a URL string.
411                 String url;
412
413                 // If the intent action is a web search, perform the search.
414                 if (isWebSearch) {
415                     // Create an encoded URL string.
416                     String encodedUrlString;
417
418                     // Sanitize the search input and convert it to a search.
419                     try {
420                         encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
421                     } catch (UnsupportedEncodingException exception) {
422                         encodedUrlString = "";
423                     }
424
425                     // Add the base search URL.
426                     url = searchURL + encodedUrlString;
427                 } else {  // The intent should contain a URL.
428                     // Set the intent data as the URL.
429                     url = intentUriData.toString();
430                 }
431
432                 // Add a new tab if specified in the preferences.
433                 if (sharedPreferences.getBoolean("open_intents_in_new_tab", true)) {  // Load the URL in a new tab.
434                     // Set the loading new intent flag.
435                     loadingNewIntent = true;
436
437                     // Add a new tab.
438                     addNewTab(url, true);
439                 } else {  // Load the URL in the current tab.
440                     // Make it so.
441                     loadUrl(currentWebView, url);
442                 }
443
444                 // Get a handle for the drawer layout.
445                 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
446
447                 // Close the navigation drawer if it is open.
448                 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
449                     drawerLayout.closeDrawer(GravityCompat.START);
450                 }
451
452                 // Close the bookmarks drawer if it is open.
453                 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
454                     drawerLayout.closeDrawer(GravityCompat.END);
455                 }
456             }
457         }
458     }
459
460     @Override
461     public void onRestart() {
462         // Run the default commands.
463         super.onRestart();
464
465         // Apply the app settings if returning from the Settings activity.
466         if (reapplyAppSettingsOnRestart) {
467             // Reset the reapply app settings on restart tracker.
468             reapplyAppSettingsOnRestart = false;
469
470             // Apply the app settings.
471             applyAppSettings();
472         }
473
474         // Apply the domain settings if returning from the settings or domains activity.
475         if (reapplyDomainSettingsOnRestart) {
476             // Reset the reapply domain settings on restart tracker.
477             reapplyDomainSettingsOnRestart = false;
478
479             // Reapply the domain settings for each tab.
480             for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
481                 // Get the WebView tab fragment.
482                 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
483
484                 // Get the fragment view.
485                 View fragmentView = webViewTabFragment.getView();
486
487                 // Only reload the WebViews if they exist.
488                 if (fragmentView != null) {
489                     // Get the nested scroll WebView from the tab fragment.
490                     NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
491
492                     // Reset the current domain name so the domain settings will be reapplied.
493                     nestedScrollWebView.resetCurrentDomainName();
494
495                     // Reapply the domain settings if the URL is not null, which can happen if an empty tab is active when returning from settings.
496                     if (nestedScrollWebView.getUrl() != null) {
497                         applyDomainSettings(nestedScrollWebView, nestedScrollWebView.getUrl(), false, true);
498                     }
499                 }
500             }
501         }
502
503         // Load the URL on restart (used when loading a bookmark).
504         if (loadUrlOnRestart) {
505             // Load the specified URL.
506             loadUrl(currentWebView, urlToLoadOnRestart);
507
508             // Reset the load on restart tracker.
509             loadUrlOnRestart = false;
510         }
511
512         // Update the bookmarks drawer if returning from the Bookmarks activity.
513         if (restartFromBookmarksActivity) {
514             // Get a handle for the drawer layout.
515             DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
516
517             // Close the bookmarks drawer.
518             drawerLayout.closeDrawer(GravityCompat.END);
519
520             // Reload the bookmarks drawer.
521             loadBookmarksFolder();
522
523             // Reset `restartFromBookmarksActivity`.
524             restartFromBookmarksActivity = false;
525         }
526
527         // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.  This can be important if the screen was rotated.
528         updatePrivacyIcons(true);
529     }
530
531     // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
532     @Override
533     public void onResume() {
534         // Run the default commands.
535         super.onResume();
536
537         // Resume any WebViews.
538         for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
539             // Get the WebView tab fragment.
540             WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
541
542             // Get the fragment view.
543             View fragmentView = webViewTabFragment.getView();
544
545             // Only resume the WebViews if they exist (they won't when the app is first created).
546             if (fragmentView != null) {
547                 // Get the nested scroll WebView from the tab fragment.
548                 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
549
550                 // Resume the nested scroll WebView JavaScript timers.
551                 nestedScrollWebView.resumeTimers();
552
553                 // Resume the nested scroll WebView.
554                 nestedScrollWebView.onResume();
555             }
556         }
557
558         // Reapply the proxy settings if the system is using a proxy.  This redisplays the appropriate alert dialog.
559         if (!proxyMode.equals(ProxyHelper.NONE)) {
560             applyProxy(false);
561         }
562
563         // Reapply any system UI flags and the ad in the free flavor.
564         if (displayingFullScreenVideo || inFullScreenBrowsingMode) {  // The system is displaying a website or a video in full screen mode.
565             // Get a handle for the root frame layouts.
566             FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
567
568             // Remove the translucent status flag.  This is necessary so the root frame layout can fill the entire screen.
569             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
570
571             /* Hide the system bars.
572              * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
573              * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
574              * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
575              * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
576              */
577             rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
578                     View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
579         } else if (BuildConfig.FLAVOR.contentEquals("free")) {  // The system in not in full screen mode.
580             // Resume the ad.
581             AdHelper.resumeAd(findViewById(R.id.adview));
582         }
583     }
584
585     @Override
586     public void onPause() {
587         // Run the default commands.
588         super.onPause();
589
590         for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
591             // Get the WebView tab fragment.
592             WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
593
594             // Get the fragment view.
595             View fragmentView = webViewTabFragment.getView();
596
597             // Only pause the WebViews if they exist (they won't when the app is first created).
598             if (fragmentView != null) {
599                 // Get the nested scroll WebView from the tab fragment.
600                 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
601
602                 // Pause the nested scroll WebView.
603                 nestedScrollWebView.onPause();
604
605                 // Pause the nested scroll WebView JavaScript timers.
606                 nestedScrollWebView.pauseTimers();
607             }
608         }
609
610         // Pause the ad or it will continue to consume resources in the background on the free flavor.
611         if (BuildConfig.FLAVOR.contentEquals("free")) {
612             // Pause the ad.
613             AdHelper.pauseAd(findViewById(R.id.adview));
614         }
615     }
616
617     @Override
618     public void onDestroy() {
619         // Unregister the orbot status broadcast receiver.
620         this.unregisterReceiver(orbotStatusBroadcastReceiver);
621
622         // Close the bookmarks cursor and database.
623         bookmarksCursor.close();
624         bookmarksDatabaseHelper.close();
625
626         // Run the default commands.
627         super.onDestroy();
628     }
629
630     @Override
631     public boolean onCreateOptionsMenu(Menu menu) {
632         // Inflate the menu.  This adds items to the action bar if it is present.
633         getMenuInflater().inflate(R.menu.webview_options_menu, menu);
634
635         // Store a handle for the options menu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons()`.
636         optionsMenu = menu;
637
638         // Set the initial status of the privacy icons.  `false` does not call `invalidateOptionsMenu` as the last step.
639         updatePrivacyIcons(false);
640
641         // Get handles for the menu items.
642         MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
643         MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
644         MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
645         MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);  // Form data can be removed once the minimum API >= 26.
646         MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);  // Form data can be removed once the minimum API >= 26.
647         MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
648         MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
649
650         // Only display third-party cookies if API >= 21
651         toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
652
653         // Only display the form data menu items if the API < 26.
654         toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
655         clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
656
657         // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
658         clearFormDataMenuItem.setEnabled(Build.VERSION.SDK_INT < 26);
659
660         // Only show Ad Consent if this is the free flavor.
661         adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
662
663         // Get the shared preferences.
664         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
665
666         // Get the dark theme and app bar preferences..
667         boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
668         boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
669
670         // 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.
671         if (displayAdditionalAppBarIcons) {
672             toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
673             toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
674             refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
675         } else { //Do not display the additional icons.
676             toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
677             toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
678             refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
679         }
680
681         // Replace Refresh with Stop if a URL is already loading.
682         if (currentWebView != null && currentWebView.getProgress() != 100) {
683             // Set the title.
684             refreshMenuItem.setTitle(R.string.stop);
685
686             // If the icon is displayed in the AppBar, set it according to the theme.
687             if (displayAdditionalAppBarIcons) {
688                 if (darkTheme) {
689                     refreshMenuItem.setIcon(R.drawable.close_dark);
690                 } else {
691                     refreshMenuItem.setIcon(R.drawable.close_light);
692                 }
693             }
694         }
695
696         // Done.
697         return true;
698     }
699
700     @Override
701     public boolean onPrepareOptionsMenu(Menu menu) {
702         // Get handles for the menu items.
703         MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
704         MenuItem firstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
705         MenuItem thirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
706         MenuItem domStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
707         MenuItem saveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);  // Form data can be removed once the minimum API >= 26.
708         MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
709         MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
710         MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
711         MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);  // Form data can be removed once the minimum API >= 26.
712         MenuItem blocklistsMenuItem = menu.findItem(R.id.blocklists);
713         MenuItem easyListMenuItem = menu.findItem(R.id.easylist);
714         MenuItem easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
715         MenuItem fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
716         MenuItem fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
717         MenuItem ultraListMenuItem = menu.findItem(R.id.ultralist);
718         MenuItem ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
719         MenuItem blockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
720         MenuItem proxyMenuItem = menu.findItem(R.id.proxy);
721         MenuItem userAgentMenuItem = menu.findItem(R.id.user_agent);
722         MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
723         MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
724         MenuItem wideViewportMenuItem = menu.findItem(R.id.wide_viewport);
725         MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
726         MenuItem nightModeMenuItem = menu.findItem(R.id.night_mode);
727
728         // Get a handle for the cookie manager.
729         CookieManager cookieManager = CookieManager.getInstance();
730
731         // Initialize the current user agent string and the font size.
732         String currentUserAgent = getString(R.string.user_agent_privacy_browser);
733         int fontSize = 100;
734
735         // 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.
736         if (currentWebView != null) {
737             // Set the add or edit domain text.
738             if (currentWebView.getDomainSettingsApplied()) {
739                 addOrEditDomain.setTitle(R.string.edit_domain_settings);
740             } else {
741                 addOrEditDomain.setTitle(R.string.add_domain_settings);
742             }
743
744             // Get the current user agent from the WebView.
745             currentUserAgent = currentWebView.getSettings().getUserAgentString();
746
747             // Get the current font size from the
748             fontSize = currentWebView.getSettings().getTextZoom();
749
750             // Set the status of the menu item checkboxes.
751             domStorageMenuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
752             saveFormDataMenuItem.setChecked(currentWebView.getSettings().getSaveFormData());  // Form data can be removed once the minimum API >= 26.
753             easyListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
754             easyPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
755             fanboysAnnoyanceListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
756             fanboysSocialBlockingListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
757             ultraListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
758             ultraPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
759             blockAllThirdPartyRequestsMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
760             swipeToRefreshMenuItem.setChecked(currentWebView.getSwipeToRefresh());
761             wideViewportMenuItem.setChecked(currentWebView.getSettings().getUseWideViewPort());
762             displayImagesMenuItem.setChecked(currentWebView.getSettings().getLoadsImagesAutomatically());
763             nightModeMenuItem.setChecked(currentWebView.getNightMode());
764
765             // Initialize the display names for the blocklists with the number of blocked requests.
766             blocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
767             easyListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYLIST) + " - " + getString(R.string.easylist));
768             easyPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYPRIVACY) + " - " + getString(R.string.easyprivacy));
769             fanboysAnnoyanceListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " + getString(R.string.fanboys_annoyance_list));
770             fanboysSocialBlockingListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " + getString(R.string.fanboys_social_blocking_list));
771             ultraListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRALIST) + " - " + getString(R.string.ultralist));
772             ultraPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRAPRIVACY) + " - " + getString(R.string.ultraprivacy));
773             blockAllThirdPartyRequestsMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " + getString(R.string.block_all_third_party_requests));
774
775             // Only modify third-party cookies if the API >= 21.
776             if (Build.VERSION.SDK_INT >= 21) {
777                 // Set the status of the third-party cookies checkbox.
778                 thirdPartyCookiesMenuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
779
780                 // Enable third-party cookies if first-party cookies are enabled.
781                 thirdPartyCookiesMenuItem.setEnabled(cookieManager.acceptCookie());
782             }
783
784             // Enable DOM Storage if JavaScript is enabled.
785             domStorageMenuItem.setEnabled(currentWebView.getSettings().getJavaScriptEnabled());
786         }
787
788         // Set the checked status of the first party cookies menu item.
789         firstPartyCookiesMenuItem.setChecked(cookieManager.acceptCookie());
790
791         // Enable Clear Cookies if there are any.
792         clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
793
794         // 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`.
795         String privateDataDirectoryString = getApplicationInfo().dataDir;
796
797         // Get a count of the number of files in the Local Storage directory.
798         File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
799         int localStorageDirectoryNumberOfFiles = 0;
800         if (localStorageDirectory.exists()) {
801             // `Objects.requireNonNull` removes a lint warning that `localStorageDirectory.list` might produce a null pointed exception if it is dereferenced.
802             localStorageDirectoryNumberOfFiles = Objects.requireNonNull(localStorageDirectory.list()).length;
803         }
804
805         // Get a count of the number of files in the IndexedDB directory.
806         File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
807         int indexedDBDirectoryNumberOfFiles = 0;
808         if (indexedDBDirectory.exists()) {
809             // `Objects.requireNonNull` removes a lint warning that `indexedDBDirectory.list` might produce a null pointed exception if it is dereferenced.
810             indexedDBDirectoryNumberOfFiles = Objects.requireNonNull(indexedDBDirectory.list()).length;
811         }
812
813         // Enable Clear DOM Storage if there is any.
814         clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
815
816         // Enable Clear Form Data is there is any.  This can be removed once the minimum API >= 26.
817         if (Build.VERSION.SDK_INT < 26) {
818             // Get the WebView database.
819             WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
820
821             // Enable the clear form data menu item if there is anything to clear.
822             clearFormDataMenuItem.setEnabled(webViewDatabase.hasFormData());
823         }
824
825         // Enable Clear Data if any of the submenu items are enabled.
826         clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
827
828         // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
829         fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListMenuItem.isChecked());
830
831         // Set the proxy title and check the applied proxy.
832         switch (proxyMode) {
833             case ProxyHelper.NONE:
834                 // Set the proxy title.
835                 proxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_none));
836
837                 // Check the proxy None radio button.
838                 menu.findItem(R.id.proxy_none).setChecked(true);
839                 break;
840
841             case ProxyHelper.TOR:
842                 // Set the proxy title.
843                 proxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_tor));
844
845                 // Check the proxy Tor radio button.
846                 menu.findItem(R.id.proxy_tor).setChecked(true);
847                 break;
848
849             case ProxyHelper.I2P:
850                 // Set the proxy title.
851                 proxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_i2p));
852
853                 // Check the proxy I2P radio button.
854                 menu.findItem(R.id.proxy_i2p).setChecked(true);
855                 break;
856
857             case ProxyHelper.CUSTOM:
858                 // Set the proxy title.
859                 proxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_custom));
860
861                 // Check the proxy Custom radio button.
862                 menu.findItem(R.id.proxy_custom).setChecked(true);
863                 break;
864         }
865
866         // Select the current user agent menu item.  A switch statement cannot be used because the user agents are not compile time constants.
867         if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) {  // Privacy Browser.
868             // Update the user agent menu item title.
869             userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_privacy_browser));
870
871             // Select the Privacy Browser radio box.
872             menu.findItem(R.id.user_agent_privacy_browser).setChecked(true);
873         } else if (currentUserAgent.equals(webViewDefaultUserAgent)) {  // WebView Default.
874             // Update the user agent menu item title.
875             userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_webview_default));
876
877             // Select the WebView Default radio box.
878             menu.findItem(R.id.user_agent_webview_default).setChecked(true);
879         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) {  // Firefox on Android.
880             // Update the user agent menu item title.
881             userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_android));
882
883             // Select the Firefox on Android radio box.
884             menu.findItem(R.id.user_agent_firefox_on_android).setChecked(true);
885         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) {  // Chrome on Android.
886             // Update the user agent menu item title.
887             userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_android));
888
889             // Select the Chrome on Android radio box.
890             menu.findItem(R.id.user_agent_chrome_on_android).setChecked(true);
891         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) {  // Safari on iOS.
892             // Update the user agent menu item title.
893             userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_ios));
894
895             // Select the Safari on iOS radio box.
896             menu.findItem(R.id.user_agent_safari_on_ios).setChecked(true);
897         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) {  // Firefox on Linux.
898             // Update the user agent menu item title.
899             userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_linux));
900
901             // Select the Firefox on Linux radio box.
902             menu.findItem(R.id.user_agent_firefox_on_linux).setChecked(true);
903         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) {  // Chromium on Linux.
904             // Update the user agent menu item title.
905             userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chromium_on_linux));
906
907             // Select the Chromium on Linux radio box.
908             menu.findItem(R.id.user_agent_chromium_on_linux).setChecked(true);
909         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) {  // Firefox on Windows.
910             // Update the user agent menu item title.
911             userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_windows));
912
913             // Select the Firefox on Windows radio box.
914             menu.findItem(R.id.user_agent_firefox_on_windows).setChecked(true);
915         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) {  // Chrome on Windows.
916             // Update the user agent menu item title.
917             userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_windows));
918
919             // Select the Chrome on Windows radio box.
920             menu.findItem(R.id.user_agent_chrome_on_windows).setChecked(true);
921         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) {  // Edge on Windows.
922             // Update the user agent menu item title.
923             userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_edge_on_windows));
924
925             // Select the Edge on Windows radio box.
926             menu.findItem(R.id.user_agent_edge_on_windows).setChecked(true);
927         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) {  // Internet Explorer on Windows.
928             // Update the user agent menu item title.
929             userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_internet_explorer_on_windows));
930
931             // Select the Internet on Windows radio box.
932             menu.findItem(R.id.user_agent_internet_explorer_on_windows).setChecked(true);
933         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) {  // Safari on macOS.
934             // Update the user agent menu item title.
935             userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_macos));
936
937             // Select the Safari on macOS radio box.
938             menu.findItem(R.id.user_agent_safari_on_macos).setChecked(true);
939         } else {  // Custom user agent.
940             // Update the user agent menu item title.
941             userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_custom));
942
943             // Select the Custom radio box.
944             menu.findItem(R.id.user_agent_custom).setChecked(true);
945         }
946
947         // Set the font size title.
948         fontSizeMenuItem.setTitle(getString(R.string.font_size) + " - " + fontSize + "%");
949
950         // Run all the other default commands.
951         super.onPrepareOptionsMenu(menu);
952
953         // Display the menu.
954         return true;
955     }
956
957     @Override
958     // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
959     @SuppressLint("SetJavaScriptEnabled")
960     public boolean onOptionsItemSelected(MenuItem menuItem) {
961         // Get the selected menu item ID.
962         int menuItemId = menuItem.getItemId();
963
964         // Get a handle for the shared preferences.
965         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
966
967         // Get a handle for the cookie manager.
968         CookieManager cookieManager = CookieManager.getInstance();
969
970         // Run the commands that correlate to the selected menu item.
971         switch (menuItemId) {
972             case R.id.toggle_javascript:
973                 // Toggle the JavaScript status.
974                 currentWebView.getSettings().setJavaScriptEnabled(!currentWebView.getSettings().getJavaScriptEnabled());
975
976                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
977                 updatePrivacyIcons(true);
978
979                 // Display a `Snackbar`.
980                 if (currentWebView.getSettings().getJavaScriptEnabled()) {  // JavaScrip is enabled.
981                     Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
982                 } else if (cookieManager.acceptCookie()) {  // JavaScript is disabled, but first-party cookies are enabled.
983                     Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
984                 } else {  // Privacy mode.
985                     Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
986                 }
987
988                 // Reload the current WebView.
989                 currentWebView.reload();
990
991                 // Consume the event.
992                 return true;
993
994             case R.id.refresh:
995                 if (menuItem.getTitle().equals(getString(R.string.refresh))) {  // The refresh button was pushed.
996                     // Reload the current WebView.
997                     currentWebView.reload();
998                 } else {  // The stop button was pushed.
999                     // Stop the loading of the WebView.
1000                     currentWebView.stopLoading();
1001                 }
1002
1003                 // Consume the event.
1004                 return true;
1005
1006             case R.id.toggle_first_party_cookies:
1007                 // Switch the first-party cookie status.
1008                 cookieManager.setAcceptCookie(!cookieManager.acceptCookie());
1009
1010                 // Store the first-party cookie status.
1011                 currentWebView.setAcceptFirstPartyCookies(cookieManager.acceptCookie());
1012
1013                 // Update the menu checkbox.
1014                 menuItem.setChecked(cookieManager.acceptCookie());
1015
1016                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1017                 updatePrivacyIcons(true);
1018
1019                 // Display a snackbar.
1020                 if (cookieManager.acceptCookie()) {  // First-party cookies are enabled.
1021                     Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1022                 } else if (currentWebView.getSettings().getJavaScriptEnabled()) {  // JavaScript is still enabled.
1023                     Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1024                 } else {  // Privacy mode.
1025                     Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1026                 }
1027
1028                 // Reload the current WebView.
1029                 currentWebView.reload();
1030
1031                 // Consume the event.
1032                 return true;
1033
1034             case R.id.toggle_third_party_cookies:
1035                 if (Build.VERSION.SDK_INT >= 21) {
1036                     // Switch the status of thirdPartyCookiesEnabled.
1037                     cookieManager.setAcceptThirdPartyCookies(currentWebView, !cookieManager.acceptThirdPartyCookies(currentWebView));
1038
1039                     // Update the menu checkbox.
1040                     menuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
1041
1042                     // Display a snackbar.
1043                     if (cookieManager.acceptThirdPartyCookies(currentWebView)) {
1044                         Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1045                     } else {
1046                         Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1047                     }
1048
1049                     // Reload the current WebView.
1050                     currentWebView.reload();
1051                 } // Else do nothing because SDK < 21.
1052
1053                 // Consume the event.
1054                 return true;
1055
1056             case R.id.toggle_dom_storage:
1057                 // Toggle the status of domStorageEnabled.
1058                 currentWebView.getSettings().setDomStorageEnabled(!currentWebView.getSettings().getDomStorageEnabled());
1059
1060                 // Update the menu checkbox.
1061                 menuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1062
1063                 // Update the privacy icon.  `true` refreshes the app bar icons.
1064                 updatePrivacyIcons(true);
1065
1066                 // Display a snackbar.
1067                 if (currentWebView.getSettings().getDomStorageEnabled()) {
1068                     Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1069                 } else {
1070                     Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1071                 }
1072
1073                 // Reload the current WebView.
1074                 currentWebView.reload();
1075
1076                 // Consume the event.
1077                 return true;
1078
1079             // Form data can be removed once the minimum API >= 26.
1080             case R.id.toggle_save_form_data:
1081                 // Switch the status of saveFormDataEnabled.
1082                 currentWebView.getSettings().setSaveFormData(!currentWebView.getSettings().getSaveFormData());
1083
1084                 // Update the menu checkbox.
1085                 menuItem.setChecked(currentWebView.getSettings().getSaveFormData());
1086
1087                 // Display a snackbar.
1088                 if (currentWebView.getSettings().getSaveFormData()) {
1089                     Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1090                 } else {
1091                     Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1092                 }
1093
1094                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1095                 updatePrivacyIcons(true);
1096
1097                 // Reload the current WebView.
1098                 currentWebView.reload();
1099
1100                 // Consume the event.
1101                 return true;
1102
1103             case R.id.clear_cookies:
1104                 Snackbar.make(findViewById(R.id.webviewpager), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1105                         .setAction(R.string.undo, v -> {
1106                             // Do nothing because everything will be handled by `onDismissed()` below.
1107                         })
1108                         .addCallback(new Snackbar.Callback() {
1109                             @SuppressLint("SwitchIntDef")  // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1110                             @Override
1111                             public void onDismissed(Snackbar snackbar, int event) {
1112                                 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) {  // The snackbar was dismissed without the undo button being pushed.
1113                                     // Delete the cookies, which command varies by SDK.
1114                                     if (Build.VERSION.SDK_INT < 21) {
1115                                         cookieManager.removeAllCookie();
1116                                     } else {
1117                                         cookieManager.removeAllCookies(null);
1118                                     }
1119                                 }
1120                             }
1121                         })
1122                         .show();
1123
1124                 // Consume the event.
1125                 return true;
1126
1127             case R.id.clear_dom_storage:
1128                 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1129                         .setAction(R.string.undo, v -> {
1130                             // Do nothing because everything will be handled by `onDismissed()` below.
1131                         })
1132                         .addCallback(new Snackbar.Callback() {
1133                             @SuppressLint("SwitchIntDef")  // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1134                             @Override
1135                             public void onDismissed(Snackbar snackbar, int event) {
1136                                 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) {  // The snackbar was dismissed without the undo button being pushed.
1137                                     // Delete the DOM Storage.
1138                                     WebStorage webStorage = WebStorage.getInstance();
1139                                     webStorage.deleteAllData();
1140
1141                                     // Initialize a handler to manually delete the DOM storage files and directories.
1142                                     Handler deleteDomStorageHandler = new Handler();
1143
1144                                     // Setup a runnable to manually delete the DOM storage files and directories.
1145                                     Runnable deleteDomStorageRunnable = () -> {
1146                                         try {
1147                                             // Get a handle for the runtime.
1148                                             Runtime runtime = Runtime.getRuntime();
1149
1150                                             // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1151                                             // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1152                                             String privateDataDirectoryString = getApplicationInfo().dataDir;
1153
1154                                             // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1155                                             Process deleteLocalStorageProcess = runtime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1156
1157                                             // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1158                                             Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1159                                             Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1160                                             Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1161                                             Process deleteDatabasesProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1162
1163                                             // Wait for the processes to finish.
1164                                             deleteLocalStorageProcess.waitFor();
1165                                             deleteIndexProcess.waitFor();
1166                                             deleteQuotaManagerProcess.waitFor();
1167                                             deleteQuotaManagerJournalProcess.waitFor();
1168                                             deleteDatabasesProcess.waitFor();
1169                                         } catch (Exception exception) {
1170                                             // Do nothing if an error is thrown.
1171                                         }
1172                                     };
1173
1174                                     // Manually delete the DOM storage files after 200 milliseconds.
1175                                     deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
1176                                 }
1177                             }
1178                         })
1179                         .show();
1180
1181                 // Consume the event.
1182                 return true;
1183
1184             // Form data can be remove once the minimum API >= 26.
1185             case R.id.clear_form_data:
1186                 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1187                         .setAction(R.string.undo, v -> {
1188                             // Do nothing because everything will be handled by `onDismissed()` below.
1189                         })
1190                         .addCallback(new Snackbar.Callback() {
1191                             @SuppressLint("SwitchIntDef")  // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1192                             @Override
1193                             public void onDismissed(Snackbar snackbar, int event) {
1194                                 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) {  // The snackbar was dismissed without the undo button being pushed.
1195                                     // Delete the form data.
1196                                     WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1197                                     mainWebViewDatabase.clearFormData();
1198                                 }
1199                             }
1200                         })
1201                         .show();
1202
1203                 // Consume the event.
1204                 return true;
1205
1206             case R.id.easylist:
1207                 // Toggle the EasyList status.
1208                 currentWebView.enableBlocklist(NestedScrollWebView.EASYLIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
1209
1210                 // Update the menu checkbox.
1211                 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
1212
1213                 // Reload the current WebView.
1214                 currentWebView.reload();
1215
1216                 // Consume the event.
1217                 return true;
1218
1219             case R.id.easyprivacy:
1220                 // Toggle the EasyPrivacy status.
1221                 currentWebView.enableBlocklist(NestedScrollWebView.EASYPRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
1222
1223                 // Update the menu checkbox.
1224                 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
1225
1226                 // Reload the current WebView.
1227                 currentWebView.reload();
1228
1229                 // Consume the event.
1230                 return true;
1231
1232             case R.id.fanboys_annoyance_list:
1233                 // Toggle Fanboy's Annoyance List status.
1234                 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1235
1236                 // Update the menu checkbox.
1237                 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1238
1239                 // Update the staus of Fanboy's Social Blocking List.
1240                 MenuItem fanboysSocialBlockingListMenuItem = optionsMenu.findItem(R.id.fanboys_social_blocking_list);
1241                 fanboysSocialBlockingListMenuItem.setEnabled(!currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1242
1243                 // Reload the current WebView.
1244                 currentWebView.reload();
1245
1246                 // Consume the event.
1247                 return true;
1248
1249             case R.id.fanboys_social_blocking_list:
1250                 // Toggle Fanboy's Social Blocking List status.
1251                 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1252
1253                 // Update the menu checkbox.
1254                 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1255
1256                 // Reload the current WebView.
1257                 currentWebView.reload();
1258
1259                 // Consume the event.
1260                 return true;
1261
1262             case R.id.ultralist:
1263                 // Toggle the UltraList status.
1264                 currentWebView.enableBlocklist(NestedScrollWebView.ULTRALIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
1265
1266                 // Update the menu checkbox.
1267                 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
1268
1269                 // Reload the current WebView.
1270                 currentWebView.reload();
1271
1272                 // Consume the event.
1273                 return true;
1274
1275             case R.id.ultraprivacy:
1276                 // Toggle the UltraPrivacy status.
1277                 currentWebView.enableBlocklist(NestedScrollWebView.ULTRAPRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
1278
1279                 // Update the menu checkbox.
1280                 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
1281
1282                 // Reload the current WebView.
1283                 currentWebView.reload();
1284
1285                 // Consume the event.
1286                 return true;
1287
1288             case R.id.block_all_third_party_requests:
1289                 //Toggle the third-party requests blocker status.
1290                 currentWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, !currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1291
1292                 // Update the menu checkbox.
1293                 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1294
1295                 // Reload the current WebView.
1296                 currentWebView.reload();
1297
1298                 // Consume the event.
1299                 return true;
1300
1301             case R.id.proxy_none:
1302                 // Update the proxy mode.
1303                 proxyMode = ProxyHelper.NONE;
1304
1305                 // Apply the proxy mode.
1306                 applyProxy(true);
1307
1308                 // Consume the event.
1309                 return true;
1310
1311             case R.id.proxy_tor:
1312                 // Update the proxy mode.
1313                 proxyMode = ProxyHelper.TOR;
1314
1315                 // Apply the proxy mode.
1316                 applyProxy(true);
1317
1318                 // Consume the event.
1319                 return true;
1320
1321             case R.id.proxy_i2p:
1322                 // Update the proxy mode.
1323                 proxyMode = ProxyHelper.I2P;
1324
1325                 // Apply the proxy mode.
1326                 applyProxy(true);
1327
1328                 // Consume the event.
1329                 return true;
1330
1331             case R.id.proxy_custom:
1332                 // Update the proxy mode.
1333                 proxyMode = ProxyHelper.CUSTOM;
1334
1335                 // Apply the proxy mode.
1336                 applyProxy(true);
1337
1338                 // Consume the event.
1339                 return true;
1340
1341             case R.id.user_agent_privacy_browser:
1342                 // Update the user agent.
1343                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
1344
1345                 // Reload the current WebView.
1346                 currentWebView.reload();
1347
1348                 // Consume the event.
1349                 return true;
1350
1351             case R.id.user_agent_webview_default:
1352                 // Update the user agent.
1353                 currentWebView.getSettings().setUserAgentString("");
1354
1355                 // Reload the current WebView.
1356                 currentWebView.reload();
1357
1358                 // Consume the event.
1359                 return true;
1360
1361             case R.id.user_agent_firefox_on_android:
1362                 // Update the user agent.
1363                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
1364
1365                 // Reload the current WebView.
1366                 currentWebView.reload();
1367
1368                 // Consume the event.
1369                 return true;
1370
1371             case R.id.user_agent_chrome_on_android:
1372                 // Update the user agent.
1373                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
1374
1375                 // Reload the current WebView.
1376                 currentWebView.reload();
1377
1378                 // Consume the event.
1379                 return true;
1380
1381             case R.id.user_agent_safari_on_ios:
1382                 // Update the user agent.
1383                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
1384
1385                 // Reload the current WebView.
1386                 currentWebView.reload();
1387
1388                 // Consume the event.
1389                 return true;
1390
1391             case R.id.user_agent_firefox_on_linux:
1392                 // Update the user agent.
1393                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
1394
1395                 // Reload the current WebView.
1396                 currentWebView.reload();
1397
1398                 // Consume the event.
1399                 return true;
1400
1401             case R.id.user_agent_chromium_on_linux:
1402                 // Update the user agent.
1403                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
1404
1405                 // Reload the current WebView.
1406                 currentWebView.reload();
1407
1408                 // Consume the event.
1409                 return true;
1410
1411             case R.id.user_agent_firefox_on_windows:
1412                 // Update the user agent.
1413                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
1414
1415                 // Reload the current WebView.
1416                 currentWebView.reload();
1417
1418                 // Consume the event.
1419                 return true;
1420
1421             case R.id.user_agent_chrome_on_windows:
1422                 // Update the user agent.
1423                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
1424
1425                 // Reload the current WebView.
1426                 currentWebView.reload();
1427
1428                 // Consume the event.
1429                 return true;
1430
1431             case R.id.user_agent_edge_on_windows:
1432                 // Update the user agent.
1433                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
1434
1435                 // Reload the current WebView.
1436                 currentWebView.reload();
1437
1438                 // Consume the event.
1439                 return true;
1440
1441             case R.id.user_agent_internet_explorer_on_windows:
1442                 // Update the user agent.
1443                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
1444
1445                 // Reload the current WebView.
1446                 currentWebView.reload();
1447
1448                 // Consume the event.
1449                 return true;
1450
1451             case R.id.user_agent_safari_on_macos:
1452                 // Update the user agent.
1453                 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
1454
1455                 // Reload the current WebView.
1456                 currentWebView.reload();
1457
1458                 // Consume the event.
1459                 return true;
1460
1461             case R.id.user_agent_custom:
1462                 // Update the user agent.
1463                 currentWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
1464
1465                 // Reload the current WebView.
1466                 currentWebView.reload();
1467
1468                 // Consume the event.
1469                 return true;
1470
1471             case R.id.font_size:
1472                 // Instantiate the font size dialog.
1473                 DialogFragment fontSizeDialogFragment = FontSizeDialog.displayDialog(currentWebView.getSettings().getTextZoom());
1474
1475                 // Show the font size dialog.
1476                 fontSizeDialogFragment.show(getSupportFragmentManager(), getString(R.string.font_size));
1477
1478                 // Consume the event.
1479                 return true;
1480
1481             case R.id.swipe_to_refresh:
1482                 // Toggle the stored status of swipe to refresh.
1483                 currentWebView.setSwipeToRefresh(!currentWebView.getSwipeToRefresh());
1484
1485                 // Get a handle for the swipe refresh layout.
1486                 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
1487
1488                 // Update the swipe refresh layout.
1489                 if (currentWebView.getSwipeToRefresh()) {  // Swipe to refresh is enabled.
1490                     // Only enable the swipe refresh layout if the WebView is scrolled to the top.  It is updated every time the scroll changes.
1491                     swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
1492                 } else {  // Swipe to refresh is disabled.
1493                     // Disable the swipe refresh layout.
1494                     swipeRefreshLayout.setEnabled(false);
1495                 }
1496
1497                 // Consume the event.
1498                 return true;
1499
1500             case R.id.wide_viewport:
1501                 // Toggle the viewport.
1502                 currentWebView.getSettings().setUseWideViewPort(!currentWebView.getSettings().getUseWideViewPort());
1503
1504                 // Consume the event.
1505                 return true;
1506
1507             case R.id.display_images:
1508                 if (currentWebView.getSettings().getLoadsImagesAutomatically()) {  // Images are currently loaded automatically.
1509                     // Disable loading of images.
1510                     currentWebView.getSettings().setLoadsImagesAutomatically(false);
1511
1512                     // Reload the website to remove existing images.
1513                     currentWebView.reload();
1514                 } else {  // Images are not currently loaded automatically.
1515                     // Enable loading of images.  Missing images will be loaded without the need for a reload.
1516                     currentWebView.getSettings().setLoadsImagesAutomatically(true);
1517                 }
1518
1519                 // Consume the event.
1520                 return true;
1521
1522             case R.id.night_mode:
1523                 // Toggle night mode.
1524                 currentWebView.setNightMode(!currentWebView.getNightMode());
1525
1526                 // Enable or disable JavaScript according to night mode, the global preference, and any domain settings.
1527                 if (currentWebView.getNightMode()) {  // Night mode is enabled, which requires JavaScript.
1528                     // Enable JavaScript.
1529                     currentWebView.getSettings().setJavaScriptEnabled(true);
1530                 } else if (currentWebView.getDomainSettingsApplied()) {  // Night mode is disabled and domain settings are applied.  Set JavaScript according to the domain settings.
1531                     // Apply the JavaScript preference that was stored the last time domain settings were loaded.
1532                     currentWebView.getSettings().setJavaScriptEnabled(currentWebView.getDomainSettingsJavaScriptEnabled());
1533                 } else {  // Night mode is disabled and domain settings are not applied.  Set JavaScript according to the global preference.
1534                     // Apply the JavaScript preference.
1535                     currentWebView.getSettings().setJavaScriptEnabled(sharedPreferences.getBoolean("javascript", false));
1536                 }
1537
1538                 // Update the privacy icons.
1539                 updatePrivacyIcons(false);
1540
1541                 // Reload the website.
1542                 currentWebView.reload();
1543
1544                 // Consume the event.
1545                 return true;
1546
1547             case R.id.find_on_page:
1548                 // Get a handle for the views.
1549                 Toolbar toolbar = findViewById(R.id.toolbar);
1550                 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
1551                 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
1552
1553                 // Set the minimum height of the find on page linear layout to match the toolbar.
1554                 findOnPageLinearLayout.setMinimumHeight(toolbar.getHeight());
1555
1556                 // Hide the toolbar.
1557                 toolbar.setVisibility(View.GONE);
1558
1559                 // Show the find on page linear layout.
1560                 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1561
1562                 // Display the keyboard.  The app must wait 200 ms before running the command to work around a bug in Android.
1563                 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1564                 findOnPageEditText.postDelayed(() -> {
1565                     // Set the focus on `findOnPageEditText`.
1566                     findOnPageEditText.requestFocus();
1567
1568                     // Get a handle for the input method manager.
1569                     InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1570
1571                     // Remove the lint warning below that the input method manager might be null.
1572                     assert inputMethodManager != null;
1573
1574                     // Display the keyboard.  `0` sets no input flags.
1575                     inputMethodManager.showSoftInput(findOnPageEditText, 0);
1576                 }, 200);
1577
1578                 // Consume the event.
1579                 return true;
1580
1581             case R.id.print:
1582                 // Get a print manager instance.
1583                 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1584
1585                 // Remove the lint error below that print manager might be null.
1586                 assert printManager != null;
1587
1588                 // Create a print document adapter from the current WebView.
1589                 PrintDocumentAdapter printDocumentAdapter = currentWebView.createPrintDocumentAdapter();
1590
1591                 // Print the document.
1592                 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1593
1594                 // Consume the event.
1595                 return true;
1596
1597             case R.id.save_url:
1598                 // Instantiate the save dialog.
1599                 DialogFragment saveDialogFragment = SaveDialog.saveUrl(StoragePermissionDialog.SAVE_URL, currentWebView.getCurrentUrl(), currentWebView.getSettings().getUserAgentString(),
1600                         currentWebView.getAcceptFirstPartyCookies());
1601
1602                 // Show the save dialog.  It must be named `save_dialog` so that the file picked can update the file name.
1603                 saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
1604
1605                 // Consume the event.
1606                 return true;
1607
1608             case R.id.save_as_archive:
1609                 // Instantiate the save webpage archive dialog.
1610                 DialogFragment saveWebpageArchiveDialogFragment = SaveDialog.saveUrl(StoragePermissionDialog.SAVE_AS_ARCHIVE, currentWebView.getCurrentUrl(), currentWebView.getSettings().getUserAgentString(),
1611                         currentWebView.getAcceptFirstPartyCookies());
1612
1613                 // Show the save webpage archive dialog.  It must be named `save_dialog` so that the file picked can update the file name.
1614                 saveWebpageArchiveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
1615
1616                 // Consume the event.
1617                 return true;
1618
1619             case R.id.save_as_image:
1620                 // Instantiate the save webpage image dialog.  It must be named `save_webpage` so that the file picked can update the file name.
1621                 DialogFragment saveWebpageImageDialogFragment = SaveDialog.saveUrl(StoragePermissionDialog.SAVE_AS_IMAGE, currentWebView.getCurrentUrl(), currentWebView.getSettings().getUserAgentString(),
1622                         currentWebView.getAcceptFirstPartyCookies());
1623
1624                 // Show the save webpage image dialog.  It must be named `save_dialog` so that the file picked can update the file name.
1625                 saveWebpageImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
1626
1627                 // Consume the event.
1628                 return true;
1629
1630             case R.id.add_to_homescreen:
1631                 // Instantiate the create home screen shortcut dialog.
1632                 DialogFragment createHomeScreenShortcutDialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView.getTitle(), currentWebView.getUrl(),
1633                         currentWebView.getFavoriteOrDefaultIcon());
1634
1635                 // Show the create home screen shortcut dialog.
1636                 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
1637
1638                 // Consume the event.
1639                 return true;
1640
1641             case R.id.view_source:
1642                 // Create an intent to launch the view source activity.
1643                 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
1644
1645                 // Add the variables to the intent.
1646                 viewSourceIntent.putExtra("user_agent", currentWebView.getSettings().getUserAgentString());
1647                 viewSourceIntent.putExtra("current_url", currentWebView.getUrl());
1648
1649                 // Make it so.
1650                 startActivity(viewSourceIntent);
1651
1652                 // Consume the event.
1653                 return true;
1654
1655             case R.id.share_url:
1656                 // Setup the share string.
1657                 String shareString = currentWebView.getTitle() + " – " + currentWebView.getUrl();
1658
1659                 // Create the share intent.
1660                 Intent shareIntent = new Intent(Intent.ACTION_SEND);
1661                 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1662                 shareIntent.setType("text/plain");
1663
1664                 // Make it so.
1665                 startActivity(Intent.createChooser(shareIntent, getString(R.string.share_url)));
1666
1667                 // Consume the event.
1668                 return true;
1669
1670             case R.id.open_with_app:
1671                 // Open the URL with an outside app.
1672                 openWithApp(currentWebView.getUrl());
1673
1674                 // Consume the event.
1675                 return true;
1676
1677             case R.id.open_with_browser:
1678                 // Open the URL with an outside browser.
1679                 openWithBrowser(currentWebView.getUrl());
1680
1681                 // Consume the event.
1682                 return true;
1683
1684             case R.id.add_or_edit_domain:
1685                 if (currentWebView.getDomainSettingsApplied()) {  // Edit the current domain settings.
1686                     // Reapply the domain settings on returning to `MainWebViewActivity`.
1687                     reapplyDomainSettingsOnRestart = true;
1688
1689                     // Create an intent to launch the domains activity.
1690                     Intent domainsIntent = new Intent(this, DomainsActivity.class);
1691
1692                     // Add the extra information to the intent.
1693                     domainsIntent.putExtra("load_domain", currentWebView.getDomainSettingsDatabaseId());
1694                     domainsIntent.putExtra("close_on_back", true);
1695                     domainsIntent.putExtra("current_url", currentWebView.getUrl());
1696
1697                     // Get the current certificate.
1698                     SslCertificate sslCertificate = currentWebView.getCertificate();
1699
1700                     // Check to see if the SSL certificate is populated.
1701                     if (sslCertificate != null) {
1702                         // Extract the certificate to strings.
1703                         String issuedToCName = sslCertificate.getIssuedTo().getCName();
1704                         String issuedToOName = sslCertificate.getIssuedTo().getOName();
1705                         String issuedToUName = sslCertificate.getIssuedTo().getUName();
1706                         String issuedByCName = sslCertificate.getIssuedBy().getCName();
1707                         String issuedByOName = sslCertificate.getIssuedBy().getOName();
1708                         String issuedByUName = sslCertificate.getIssuedBy().getUName();
1709                         long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1710                         long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1711
1712                         // Add the certificate to the intent.
1713                         domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1714                         domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1715                         domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1716                         domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1717                         domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1718                         domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1719                         domainsIntent.putExtra("ssl_start_date", startDateLong);
1720                         domainsIntent.putExtra("ssl_end_date", endDateLong);
1721                     }
1722
1723                     // Check to see if the current IP addresses have been received.
1724                     if (currentWebView.hasCurrentIpAddresses()) {
1725                         // Add the current IP addresses to the intent.
1726                         domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1727                     }
1728
1729                     // Make it so.
1730                     startActivity(domainsIntent);
1731                 } else {  // Add a new domain.
1732                     // Apply the new domain settings on returning to `MainWebViewActivity`.
1733                     reapplyDomainSettingsOnRestart = true;
1734
1735                     // Get the current domain
1736                     Uri currentUri = Uri.parse(currentWebView.getUrl());
1737                     String currentDomain = currentUri.getHost();
1738
1739                     // Initialize the database handler.  The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1740                     DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1741
1742                     // Create the domain and store the database ID.
1743                     int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1744
1745                     // Create an intent to launch the domains activity.
1746                     Intent domainsIntent = new Intent(this, DomainsActivity.class);
1747
1748                     // Add the extra information to the intent.
1749                     domainsIntent.putExtra("load_domain", newDomainDatabaseId);
1750                     domainsIntent.putExtra("close_on_back", true);
1751                     domainsIntent.putExtra("current_url", currentWebView.getUrl());
1752
1753                     // Get the current certificate.
1754                     SslCertificate sslCertificate = currentWebView.getCertificate();
1755
1756                     // Check to see if the SSL certificate is populated.
1757                     if (sslCertificate != null) {
1758                         // Extract the certificate to strings.
1759                         String issuedToCName = sslCertificate.getIssuedTo().getCName();
1760                         String issuedToOName = sslCertificate.getIssuedTo().getOName();
1761                         String issuedToUName = sslCertificate.getIssuedTo().getUName();
1762                         String issuedByCName = sslCertificate.getIssuedBy().getCName();
1763                         String issuedByOName = sslCertificate.getIssuedBy().getOName();
1764                         String issuedByUName = sslCertificate.getIssuedBy().getUName();
1765                         long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1766                         long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1767
1768                         // Add the certificate to the intent.
1769                         domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1770                         domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1771                         domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1772                         domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1773                         domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1774                         domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1775                         domainsIntent.putExtra("ssl_start_date", startDateLong);
1776                         domainsIntent.putExtra("ssl_end_date", endDateLong);
1777                     }
1778
1779                     // Check to see if the current IP addresses have been received.
1780                     if (currentWebView.hasCurrentIpAddresses()) {
1781                         // Add the current IP addresses to the intent.
1782                         domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1783                     }
1784
1785                     // Make it so.
1786                     startActivity(domainsIntent);
1787                 }
1788
1789                 // Consume the event.
1790                 return true;
1791
1792             case R.id.ad_consent:
1793                 // Instantiate the ad consent dialog.
1794                 DialogFragment adConsentDialogFragment = new AdConsentDialog();
1795
1796                 // Display the ad consent dialog.
1797                 adConsentDialogFragment.show(getSupportFragmentManager(), getString(R.string.ad_consent));
1798
1799                 // Consume the event.
1800                 return true;
1801
1802             default:
1803                 // Don't consume the event.
1804                 return super.onOptionsItemSelected(menuItem);
1805         }
1806     }
1807
1808     // removeAllCookies is deprecated, but it is required for API < 21.
1809     @Override
1810     public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1811         // Get the menu item ID.
1812         int menuItemId = menuItem.getItemId();
1813
1814         // Get a handle for the shared preferences.
1815         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1816
1817         // Run the commands that correspond to the selected menu item.
1818         switch (menuItemId) {
1819             case R.id.clear_and_exit:
1820                 // Clear and exit Privacy Browser.
1821                 clearAndExit();
1822                 break;
1823
1824             case R.id.home:
1825                 // Load the homepage.
1826                 loadUrl(currentWebView, sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
1827                 break;
1828
1829             case R.id.back:
1830                 if (currentWebView.canGoBack()) {
1831                     // Get the current web back forward list.
1832                     WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
1833
1834                     // Get the previous entry URL.
1835                     String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
1836
1837                     // Apply the domain settings.
1838                     applyDomainSettings(currentWebView, previousUrl, false, false);
1839
1840                     // Load the previous website in the history.
1841                     currentWebView.goBack();
1842                 }
1843                 break;
1844
1845             case R.id.forward:
1846                 if (currentWebView.canGoForward()) {
1847                     // Get the current web back forward list.
1848                     WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
1849
1850                     // Get the next entry URL.
1851                     String nextUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() + 1).getUrl();
1852
1853                     // Apply the domain settings.
1854                     applyDomainSettings(currentWebView, nextUrl, false, false);
1855
1856                     // Load the next website in the history.
1857                     currentWebView.goForward();
1858                 }
1859                 break;
1860
1861             case R.id.history:
1862                 // Instantiate the URL history dialog.
1863                 DialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView.getWebViewFragmentId());
1864
1865                 // Show the URL history dialog.
1866                 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
1867                 break;
1868
1869             case R.id.open:
1870                 // Instantiate the open file dialog.
1871                 DialogFragment openDialogFragment = new OpenDialog();
1872
1873                 // Show the open file dialog.
1874                 openDialogFragment.show(getSupportFragmentManager(), getString(R.string.open));
1875                 break;
1876
1877             case R.id.requests:
1878                 // Populate the resource requests.
1879                 RequestsActivity.resourceRequests = currentWebView.getResourceRequests();
1880
1881                 // Create an intent to launch the Requests activity.
1882                 Intent requestsIntent = new Intent(this, RequestsActivity.class);
1883
1884                 // Add the block third-party requests status to the intent.
1885                 requestsIntent.putExtra("block_all_third_party_requests", currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1886
1887                 // Make it so.
1888                 startActivity(requestsIntent);
1889                 break;
1890
1891             case R.id.downloads:
1892                 // Launch the system Download Manager.
1893                 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1894
1895                 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1896                 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1897
1898                 // Make it so.
1899                 startActivity(downloadManagerIntent);
1900                 break;
1901
1902             case R.id.domains:
1903                 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
1904                 reapplyDomainSettingsOnRestart = true;
1905
1906                 // Launch the domains activity.
1907                 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1908
1909                 // Add the extra information to the intent.
1910                 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1911
1912                 // Get the current certificate.
1913                 SslCertificate sslCertificate = currentWebView.getCertificate();
1914
1915                 // Check to see if the SSL certificate is populated.
1916                 if (sslCertificate != null) {
1917                     // Extract the certificate to strings.
1918                     String issuedToCName = sslCertificate.getIssuedTo().getCName();
1919                     String issuedToOName = sslCertificate.getIssuedTo().getOName();
1920                     String issuedToUName = sslCertificate.getIssuedTo().getUName();
1921                     String issuedByCName = sslCertificate.getIssuedBy().getCName();
1922                     String issuedByOName = sslCertificate.getIssuedBy().getOName();
1923                     String issuedByUName = sslCertificate.getIssuedBy().getUName();
1924                     long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1925                     long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1926
1927                     // Add the certificate to the intent.
1928                     domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1929                     domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1930                     domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1931                     domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1932                     domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1933                     domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1934                     domainsIntent.putExtra("ssl_start_date", startDateLong);
1935                     domainsIntent.putExtra("ssl_end_date", endDateLong);
1936                 }
1937
1938                 // Check to see if the current IP addresses have been received.
1939                 if (currentWebView.hasCurrentIpAddresses()) {
1940                     // Add the current IP addresses to the intent.
1941                     domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1942                 }
1943
1944                 // Make it so.
1945                 startActivity(domainsIntent);
1946                 break;
1947
1948             case R.id.settings:
1949                 // Set the flag to reapply app settings on restart when returning from Settings.
1950                 reapplyAppSettingsOnRestart = true;
1951
1952                 // Set the flag to reapply the domain settings on restart when returning from Settings.
1953                 reapplyDomainSettingsOnRestart = true;
1954
1955                 // Launch the settings activity.
1956                 Intent settingsIntent = new Intent(this, SettingsActivity.class);
1957                 startActivity(settingsIntent);
1958                 break;
1959
1960             case R.id.import_export:
1961                 // Launch the import/export activity.
1962                 Intent importExportIntent = new Intent (this, ImportExportActivity.class);
1963                 startActivity(importExportIntent);
1964                 break;
1965
1966             case R.id.logcat:
1967                 // Launch the logcat activity.
1968                 Intent logcatIntent = new Intent(this, LogcatActivity.class);
1969                 startActivity(logcatIntent);
1970                 break;
1971
1972             case R.id.guide:
1973                 // Launch `GuideActivity`.
1974                 Intent guideIntent = new Intent(this, GuideActivity.class);
1975                 startActivity(guideIntent);
1976                 break;
1977
1978             case R.id.about:
1979                 // Create an intent to launch the about activity.
1980                 Intent aboutIntent = new Intent(this, AboutActivity.class);
1981
1982                 // Create a string array for the blocklist versions.
1983                 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],
1984                         ultraList.get(0).get(0)[0], ultraPrivacy.get(0).get(0)[0]};
1985
1986                 // Add the blocklist versions to the intent.
1987                 aboutIntent.putExtra("blocklist_versions", blocklistVersions);
1988
1989                 // Make it so.
1990                 startActivity(aboutIntent);
1991                 break;
1992         }
1993
1994         // Get a handle for the drawer layout.
1995         DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
1996
1997         // Close the navigation drawer.
1998         drawerLayout.closeDrawer(GravityCompat.START);
1999         return true;
2000     }
2001
2002     @Override
2003     public void onPostCreate(Bundle savedInstanceState) {
2004         // Run the default commands.
2005         super.onPostCreate(savedInstanceState);
2006
2007         // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished.  This creates the navigation drawer icon.
2008         actionBarDrawerToggle.syncState();
2009     }
2010
2011     @Override
2012     public void onConfigurationChanged(@NonNull Configuration newConfig) {
2013         // Run the default commands.
2014         super.onConfigurationChanged(newConfig);
2015
2016         // Get the status bar pixel size.
2017         int statusBarResourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
2018         int statusBarPixelSize = getResources().getDimensionPixelSize(statusBarResourceId);
2019
2020         // Get the resource density.
2021         float screenDensity = getResources().getDisplayMetrics().density;
2022
2023         // Recalculate the drawer header padding.
2024         drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
2025         drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
2026         drawerHeaderPaddingBottom = (int) (8 * screenDensity);
2027
2028         // Reload the ad for the free flavor if not in full screen mode.
2029         if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2030             // Reload the ad.  The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2031             AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
2032         }
2033
2034         // `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:
2035         // https://code.google.com/p/android/issues/detail?id=20493#c8
2036         // ActivityCompat.invalidateOptionsMenu(this);
2037     }
2038
2039     @Override
2040     public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2041         // Store the hit test result.
2042         final WebView.HitTestResult hitTestResult = currentWebView.getHitTestResult();
2043
2044         // Define the URL strings.
2045         final String imageUrl;
2046         final String linkUrl;
2047
2048         // Get handles for the system managers.
2049         final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2050
2051         // Remove the lint errors below that the clipboard manager might be null.
2052         assert clipboardManager != null;
2053
2054         // Process the link according to the type.
2055         switch (hitTestResult.getType()) {
2056             // `SRC_ANCHOR_TYPE` is a link.
2057             case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2058                 // Get the target URL.
2059                 linkUrl = hitTestResult.getExtra();
2060
2061                 // Set the target URL as the title of the `ContextMenu`.
2062                 menu.setHeaderTitle(linkUrl);
2063
2064                 // Add an Open in New Tab entry.
2065                 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2066                     // Load the link URL in a new tab and move to it.
2067                     addNewTab(linkUrl, true);
2068
2069                     // Consume the event.
2070                     return true;
2071                 });
2072
2073                 // Add an Open in Background entry.
2074                 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2075                     // Load the link URL in a new tab but do not move to it.
2076                     addNewTab(linkUrl, false);
2077
2078                     // Consume the event.
2079                     return true;
2080                 });
2081
2082                 // Add an Open with App entry.
2083                 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2084                     openWithApp(linkUrl);
2085
2086                     // Consume the event.
2087                     return true;
2088                 });
2089
2090                 // Add an Open with Browser entry.
2091                 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2092                     openWithBrowser(linkUrl);
2093
2094                     // Consume the event.
2095                     return true;
2096                 });
2097
2098                 // Add a Copy URL entry.
2099                 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2100                     // Save the link URL in a `ClipData`.
2101                     ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2102
2103                     // Set the `ClipData` as the clipboard's primary clip.
2104                     clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2105
2106                     // Consume the event.
2107                     return true;
2108                 });
2109
2110                 // Add a Save URL entry.
2111                 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2112                     // Instantiate the save dialog.
2113                     DialogFragment saveDialogFragment = SaveDialog.saveUrl(StoragePermissionDialog.SAVE_URL, linkUrl, currentWebView.getSettings().getUserAgentString(),
2114                             currentWebView.getAcceptFirstPartyCookies());
2115
2116                     // Show the save dialog.  It must be named `save_dialog` so that the file picker can update the file name.
2117                     saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
2118
2119                     // Consume the event.
2120                     return true;
2121                 });
2122
2123                 // Add a Cancel entry, which by default closes the context menu.
2124                 menu.add(R.string.cancel);
2125                 break;
2126
2127             case WebView.HitTestResult.EMAIL_TYPE:
2128                 // Get the target URL.
2129                 linkUrl = hitTestResult.getExtra();
2130
2131                 // Set the target URL as the title of the `ContextMenu`.
2132                 menu.setHeaderTitle(linkUrl);
2133
2134                 // Add a Write Email entry.
2135                 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2136                     // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2137                     Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2138
2139                     // Parse the url and set it as the data for the `Intent`.
2140                     emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2141
2142                     // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2143                     emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2144
2145                     // Make it so.
2146                     startActivity(emailIntent);
2147
2148                     // Consume the event.
2149                     return true;
2150                 });
2151
2152                 // Add a Copy Email Address entry.
2153                 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2154                     // Save the email address in a `ClipData`.
2155                     ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2156
2157                     // Set the `ClipData` as the clipboard's primary clip.
2158                     clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2159
2160                     // Consume the event.
2161                     return true;
2162                 });
2163
2164                 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2165                 menu.add(R.string.cancel);
2166                 break;
2167
2168             // `IMAGE_TYPE` is an image.
2169             case WebView.HitTestResult.IMAGE_TYPE:
2170                 // Get the image URL.
2171                 imageUrl = hitTestResult.getExtra();
2172
2173                 // Set the image URL as the title of the context menu.
2174                 menu.setHeaderTitle(imageUrl);
2175
2176                 // Add an Open in New Tab entry.
2177                 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2178                     // Load the image in a new tab.
2179                     addNewTab(imageUrl, true);
2180
2181                     // Consume the event.
2182                     return true;
2183                 });
2184
2185                 // Add a View Image entry.
2186                 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2187                     // Load the image in the current tab.
2188                     loadUrl(currentWebView, imageUrl);
2189
2190                     // Consume the event.
2191                     return true;
2192                 });
2193
2194                 // Add a Save Image entry.
2195                 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2196                    // Instantiate the save dialog.
2197                    DialogFragment saveDialogFragment = SaveDialog.saveUrl(StoragePermissionDialog.SAVE_URL, imageUrl, currentWebView.getSettings().getUserAgentString(),
2198                            currentWebView.getAcceptFirstPartyCookies());
2199
2200                    // Show the save dialog.  It must be named `save_dialog` so that the file picked can update the file name.
2201                     saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
2202
2203                     // Consume the event.
2204                     return true;
2205                 });
2206
2207                 // Add a Copy URL entry.
2208                 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2209                     // Save the image URL in a clip data.
2210                     ClipData imageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2211
2212                     // Set the clip data as the clipboard's primary clip.
2213                     clipboardManager.setPrimaryClip(imageTypeClipData);
2214
2215                     // Consume the event.
2216                     return true;
2217                 });
2218
2219                 // Add an Open with App entry.
2220                 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2221                     // Open the image URL with an external app.
2222                     openWithApp(imageUrl);
2223
2224                     // Consume the event.
2225                     return true;
2226                 });
2227
2228                 // Add an Open with Browser entry.
2229                 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2230                     // Open the image URL with an external browser.
2231                     openWithBrowser(imageUrl);
2232
2233                     // Consume the event.
2234                     return true;
2235                 });
2236
2237                 // Add a Cancel entry, which by default closes the context menu.
2238                 menu.add(R.string.cancel);
2239                 break;
2240
2241             // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2242             case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2243                 // Get the image URL.
2244                 imageUrl = hitTestResult.getExtra();
2245
2246                 // Instantiate a handler.
2247                 Handler handler = new Handler();
2248
2249                 // Get a message from the handler.
2250                 Message message = handler.obtainMessage();
2251
2252                 // Request the image details from the last touched node be returned in the message.
2253                 currentWebView.requestFocusNodeHref(message);
2254
2255                 // Get the link URL from the message data.
2256                 linkUrl = message.getData().getString("url");
2257
2258                 // Set the link URL as the title of the context menu.
2259                 menu.setHeaderTitle(linkUrl);
2260
2261                 // Add an Open in New Tab entry.
2262                 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2263                     // Load the link URL in a new tab and move to it.
2264                     addNewTab(linkUrl, true);
2265
2266                     // Consume the event.
2267                     return true;
2268                 });
2269
2270                 // Add an Open in Background entry.
2271                 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2272                     // Lod the link URL in a new tab but do not move to it.
2273                     addNewTab(linkUrl, false);
2274
2275                     // Consume the event.
2276                     return true;
2277                 });
2278
2279                 // Add an Open Image in New Tab entry.
2280                 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2281                     // Load the image in a new tab and move to it.
2282                     addNewTab(imageUrl, true);
2283
2284                     // Consume the event.
2285                     return true;
2286                 });
2287
2288                 // Add a View Image entry.
2289                 menu.add(R.string.view_image).setOnMenuItemClickListener((MenuItem item) -> {
2290                    // View the image in the current tab.
2291                    loadUrl(currentWebView, imageUrl);
2292
2293                    // Consume the event.
2294                    return true;
2295                 });
2296
2297                 // Add a Copy URL entry.
2298                 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2299                     // Save the link URL in a clip data.
2300                     ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2301
2302                     // Set the clip data as the clipboard's primary clip.
2303                     clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2304
2305                     // Consume the event.
2306                     return true;
2307                 });
2308
2309                 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2310                     // Instantiate the save  dialog.
2311                     DialogFragment saveDialogFragment = SaveDialog.saveUrl(StoragePermissionDialog.SAVE_URL, imageUrl, currentWebView.getSettings().getUserAgentString(),
2312                             currentWebView.getAcceptFirstPartyCookies());
2313
2314                     // Show the save raw dialog.  It must be named `save_dialog` so that the file picked can update the file name.
2315                     saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
2316
2317                     // Consume the event.
2318                     return true;
2319                 });
2320
2321                 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2322                     // Instantiate the save dialog.
2323                     DialogFragment saveDialogFragment = SaveDialog.saveUrl(StoragePermissionDialog.SAVE_URL, linkUrl, currentWebView.getSettings().getUserAgentString(),
2324                             currentWebView.getAcceptFirstPartyCookies());
2325
2326                     // Show the save raw dialog.  It must be named `save_dialog` so that the file picked can update the file name.
2327                     saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
2328
2329                     // Consume the event.
2330                     return true;
2331                 });
2332
2333                 // Add an Open with App entry.
2334                 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2335                     // Open the link URL with an external app.
2336                     openWithApp(linkUrl);
2337
2338                     // Consume the event.
2339                     return true;
2340                 });
2341
2342                 // Add an Open with Browser entry.
2343                 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2344                     // Open the link URL with an external browser.
2345                     openWithBrowser(linkUrl);
2346
2347                     // Consume the event.
2348                     return true;
2349                 });
2350
2351                 // Add a cancel entry, which by default closes the context menu.
2352                 menu.add(R.string.cancel);
2353                 break;
2354         }
2355     }
2356
2357     @Override
2358     public void onCreateBookmark(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2359         // Get a handle for the bookmarks list view.
2360         ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2361
2362         // Get the dialog.
2363         Dialog dialog = dialogFragment.getDialog();
2364
2365         // Remove the incorrect lint warning below that the dialog might be null.
2366         assert dialog != null;
2367
2368         // Get the views from the dialog fragment.
2369         EditText createBookmarkNameEditText = dialog.findViewById(R.id.create_bookmark_name_edittext);
2370         EditText createBookmarkUrlEditText = dialog.findViewById(R.id.create_bookmark_url_edittext);
2371
2372         // Extract the strings from the edit texts.
2373         String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2374         String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2375
2376         // Create a favorite icon byte array output stream.
2377         ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2378
2379         // Convert the favorite icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
2380         favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2381
2382         // Convert the favorite icon byte array stream to a byte array.
2383         byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2384
2385         // Display the new bookmark below the current items in the (0 indexed) list.
2386         int newBookmarkDisplayOrder = bookmarksListView.getCount();
2387
2388         // Create the bookmark.
2389         bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2390
2391         // Update the bookmarks cursor with the current contents of this folder.
2392         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2393
2394         // Update the list view.
2395         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2396
2397         // Scroll to the new bookmark.
2398         bookmarksListView.setSelection(newBookmarkDisplayOrder);
2399     }
2400
2401     @Override
2402     public void onCreateBookmarkFolder(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2403         // Get a handle for the bookmarks list view.
2404         ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2405
2406         // Get the dialog.
2407         Dialog dialog = dialogFragment.getDialog();
2408
2409         // Remove the incorrect lint warning below that the dialog might be null.
2410         assert dialog != null;
2411
2412         // Get handles for the views in the dialog fragment.
2413         EditText createFolderNameEditText = dialog.findViewById(R.id.create_folder_name_edittext);
2414         RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.create_folder_default_icon_radiobutton);
2415         ImageView folderIconImageView = dialog.findViewById(R.id.create_folder_default_icon);
2416
2417         // Get new folder name string.
2418         String folderNameString = createFolderNameEditText.getText().toString();
2419
2420         // Create a folder icon bitmap.
2421         Bitmap folderIconBitmap;
2422
2423         // Set the folder icon bitmap according to the dialog.
2424         if (defaultFolderIconRadioButton.isChecked()) {  // Use the default folder icon.
2425             // Get the default folder icon drawable.
2426             Drawable folderIconDrawable = folderIconImageView.getDrawable();
2427
2428             // Convert the folder icon drawable to a bitmap drawable.
2429             BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2430
2431             // Convert the folder icon bitmap drawable to a bitmap.
2432             folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2433         } else {  // Use the WebView favorite icon.
2434             // Copy the favorite icon bitmap to the folder icon bitmap.
2435             folderIconBitmap = favoriteIconBitmap;
2436         }
2437
2438         // Create a folder icon byte array output stream.
2439         ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2440
2441         // Convert the folder icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
2442         folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2443
2444         // Convert the folder icon byte array stream to a byte array.
2445         byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2446
2447         // Move all the bookmarks down one in the display order.
2448         for (int i = 0; i < bookmarksListView.getCount(); i++) {
2449             int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2450             bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2451         }
2452
2453         // Create the folder, which will be placed at the top of the `ListView`.
2454         bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2455
2456         // Update the bookmarks cursor with the current contents of this folder.
2457         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2458
2459         // Update the `ListView`.
2460         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2461
2462         // Scroll to the new folder.
2463         bookmarksListView.setSelection(0);
2464     }
2465
2466     @Override
2467     public void onSaveBookmark(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, Bitmap favoriteIconBitmap) {
2468         // Get the dialog.
2469         Dialog dialog = dialogFragment.getDialog();
2470
2471         // Remove the incorrect lint warning below that the dialog might be null.
2472         assert dialog != null;
2473
2474         // Get handles for the views from the dialog.
2475         EditText editBookmarkNameEditText = dialog.findViewById(R.id.edit_bookmark_name_edittext);
2476         EditText editBookmarkUrlEditText = dialog.findViewById(R.id.edit_bookmark_url_edittext);
2477         RadioButton currentBookmarkIconRadioButton = dialog.findViewById(R.id.edit_bookmark_current_icon_radiobutton);
2478
2479         // Store the bookmark strings.
2480         String bookmarkNameString = editBookmarkNameEditText.getText().toString();
2481         String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
2482
2483         // Update the bookmark.
2484         if (currentBookmarkIconRadioButton.isChecked()) {  // Update the bookmark without changing the favorite icon.
2485             bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
2486         } else {  // Update the bookmark using the `WebView` favorite icon.
2487             // Create a favorite icon byte array output stream.
2488             ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2489
2490             // Convert the favorite icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
2491             favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
2492
2493             // Convert the favorite icon byte array stream to a byte array.
2494             byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
2495
2496             //  Update the bookmark and the favorite icon.
2497             bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
2498         }
2499
2500         // Update the bookmarks cursor with the current contents of this folder.
2501         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2502
2503         // Update the list view.
2504         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2505     }
2506
2507     @Override
2508     public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, Bitmap favoriteIconBitmap) {
2509         // Get the dialog.
2510         Dialog dialog = dialogFragment.getDialog();
2511
2512         // Remove the incorrect lint warning below that the dialog might be null.
2513         assert dialog != null;
2514
2515         // Get handles for the views from `dialogFragment`.
2516         EditText editFolderNameEditText = dialog.findViewById(R.id.edit_folder_name_edittext);
2517         RadioButton currentFolderIconRadioButton = dialog.findViewById(R.id.edit_folder_current_icon_radiobutton);
2518         RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.edit_folder_default_icon_radiobutton);
2519         ImageView defaultFolderIconImageView = dialog.findViewById(R.id.edit_folder_default_icon_imageview);
2520
2521         // Get the new folder name.
2522         String newFolderNameString = editFolderNameEditText.getText().toString();
2523
2524         // Check if the favorite icon has changed.
2525         if (currentFolderIconRadioButton.isChecked()) {  // Only the name has changed.
2526             // Update the name in the database.
2527             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2528         } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) {  // Only the icon has changed.
2529             // Create the new folder icon Bitmap.
2530             Bitmap folderIconBitmap;
2531
2532             // Populate the new folder icon bitmap.
2533             if (defaultFolderIconRadioButton.isChecked()) {
2534                 // Get the default folder icon drawable.
2535                 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2536
2537                 // Convert the folder icon drawable to a bitmap drawable.
2538                 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2539
2540                 // Convert the folder icon bitmap drawable to a bitmap.
2541                 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2542             } else {  // Use the `WebView` favorite icon.
2543                 // Copy the favorite icon bitmap to the folder icon bitmap.
2544                 folderIconBitmap = favoriteIconBitmap;
2545             }
2546
2547             // Create a folder icon byte array output stream.
2548             ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2549
2550             // Convert the folder icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
2551             folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2552
2553             // Convert the folder icon byte array stream to a byte array.
2554             byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2555
2556             // Update the folder icon in the database.
2557             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, newFolderIconByteArray);
2558         } else {  // The folder icon and the name have changed.
2559             // Get the new folder icon `Bitmap`.
2560             Bitmap folderIconBitmap;
2561             if (defaultFolderIconRadioButton.isChecked()) {
2562                 // Get the default folder icon drawable.
2563                 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2564
2565                 // Convert the folder icon drawable to a bitmap drawable.
2566                 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2567
2568                 // Convert the folder icon bitmap drawable to a bitmap.
2569                 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2570             } else {  // Use the `WebView` favorite icon.
2571                 // Copy the favorite icon bitmap to the folder icon bitmap.
2572                 folderIconBitmap = favoriteIconBitmap;
2573             }
2574
2575             // Create a folder icon byte array output stream.
2576             ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2577
2578             // Convert the folder icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
2579             folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2580
2581             // Convert the folder icon byte array stream to a byte array.
2582             byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2583
2584             // Update the folder name and icon in the database.
2585             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, newFolderIconByteArray);
2586         }
2587
2588         // Update the bookmarks cursor with the current contents of this folder.
2589         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2590
2591         // Update the `ListView`.
2592         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2593     }
2594
2595     // Override `onBackPressed` to handle the navigation drawer and and the WebViews.
2596     @Override
2597     public void onBackPressed() {
2598         // Get a handle for the drawer layout and the tab layout.
2599         DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
2600         TabLayout tabLayout = findViewById(R.id.tablayout);
2601
2602         if (drawerLayout.isDrawerVisible(GravityCompat.START)) {  // The navigation drawer is open.
2603             // Close the navigation drawer.
2604             drawerLayout.closeDrawer(GravityCompat.START);
2605         } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){  // The bookmarks drawer is open.
2606             if (currentBookmarksFolder.isEmpty()) {  // The home folder is displayed.
2607                 // close the bookmarks drawer.
2608                 drawerLayout.closeDrawer(GravityCompat.END);
2609             } else {  // A subfolder is displayed.
2610                 // Place the former parent folder in `currentFolder`.
2611                 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolderName(currentBookmarksFolder);
2612
2613                 // Load the new folder.
2614                 loadBookmarksFolder();
2615             }
2616         } else if (displayingFullScreenVideo) {  // A full screen video is shown.
2617             // Get a handle for the layouts.
2618             FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
2619             RelativeLayout mainContentRelativeLayout = findViewById(R.id.main_content_relativelayout);
2620             FrameLayout fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
2621
2622             // Re-enable the screen timeout.
2623             fullScreenVideoFrameLayout.setKeepScreenOn(false);
2624
2625             // Unset the full screen video flag.
2626             displayingFullScreenVideo = false;
2627
2628             // Remove all the views from the full screen video frame layout.
2629             fullScreenVideoFrameLayout.removeAllViews();
2630
2631             // Hide the full screen video frame layout.
2632             fullScreenVideoFrameLayout.setVisibility(View.GONE);
2633
2634             // Enable the sliding drawers.
2635             drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
2636
2637             // Show the main content relative layout.
2638             mainContentRelativeLayout.setVisibility(View.VISIBLE);
2639
2640             // Apply the appropriate full screen mode flags.
2641             if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {  // Privacy Browser is currently in full screen browsing mode.
2642                 // Hide the app bar if specified.
2643                 if (hideAppBar) {
2644                     // Get handles for the views.
2645                     LinearLayout tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
2646                     ActionBar actionBar = getSupportActionBar();
2647
2648                     // Remove the incorrect lint warning below that the action bar might be null.
2649                     assert actionBar != null;
2650
2651                     // Hide the tab linear layout.
2652                     tabsLinearLayout.setVisibility(View.GONE);
2653
2654                     // Hide the action bar.
2655                     actionBar.hide();
2656                 }
2657
2658                 // Hide the banner ad in the free flavor.
2659                 if (BuildConfig.FLAVOR.contentEquals("free")) {
2660