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