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