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