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