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