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