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