]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/activities/MainWebViewActivity.java
cd5a3d8444e6ac6cae3de63abe226dae5fd71066
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / activities / MainWebViewActivity.java
1 /*
2  * Copyright © 2015-2022 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 Android <https://www.stoutner.com/privacy-browser-android>.
7  *
8  * Privacy Browser Android 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 Android 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 Android.  If not, see <http://www.gnu.org/licenses/>.
20  */
21
22 package com.stoutner.privacybrowser.activities;
23
24 import android.animation.ObjectAnimator;
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.AsyncTask;
50 import android.os.Build;
51 import android.os.Bundle;
52 import android.os.Environment;
53 import android.os.Handler;
54 import android.os.Message;
55 import android.preference.PreferenceManager;
56 import android.print.PrintDocumentAdapter;
57 import android.print.PrintManager;
58 import android.provider.DocumentsContract;
59 import android.provider.OpenableColumns;
60 import android.text.Editable;
61 import android.text.Spanned;
62 import android.text.TextWatcher;
63 import android.text.style.ForegroundColorSpan;
64 import android.util.Patterns;
65 import android.util.TypedValue;
66 import android.view.ContextMenu;
67 import android.view.GestureDetector;
68 import android.view.KeyEvent;
69 import android.view.Menu;
70 import android.view.MenuItem;
71 import android.view.MotionEvent;
72 import android.view.View;
73 import android.view.ViewGroup;
74 import android.view.WindowManager;
75 import android.view.inputmethod.InputMethodManager;
76 import android.webkit.CookieManager;
77 import android.webkit.HttpAuthHandler;
78 import android.webkit.SslErrorHandler;
79 import android.webkit.ValueCallback;
80 import android.webkit.WebBackForwardList;
81 import android.webkit.WebChromeClient;
82 import android.webkit.WebResourceRequest;
83 import android.webkit.WebResourceResponse;
84 import android.webkit.WebSettings;
85 import android.webkit.WebStorage;
86 import android.webkit.WebView;
87 import android.webkit.WebViewClient;
88 import android.webkit.WebViewDatabase;
89 import android.widget.ArrayAdapter;
90 import android.widget.CheckBox;
91 import android.widget.CursorAdapter;
92 import android.widget.EditText;
93 import android.widget.FrameLayout;
94 import android.widget.ImageView;
95 import android.widget.LinearLayout;
96 import android.widget.ListView;
97 import android.widget.ProgressBar;
98 import android.widget.RadioButton;
99 import android.widget.RelativeLayout;
100 import android.widget.TextView;
101
102 import androidx.activity.result.ActivityResultCallback;
103 import androidx.activity.result.ActivityResultLauncher;
104 import androidx.activity.result.contract.ActivityResultContracts;
105 import androidx.annotation.NonNull;
106 import androidx.appcompat.app.ActionBar;
107 import androidx.appcompat.app.ActionBarDrawerToggle;
108 import androidx.appcompat.app.AppCompatActivity;
109 import androidx.appcompat.app.AppCompatDelegate;
110 import androidx.appcompat.widget.Toolbar;
111 import androidx.coordinatorlayout.widget.CoordinatorLayout;
112 import androidx.core.content.res.ResourcesCompat;
113 import androidx.core.view.GravityCompat;
114 import androidx.drawerlayout.widget.DrawerLayout;
115 import androidx.fragment.app.DialogFragment;
116 import androidx.fragment.app.Fragment;
117 import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
118 import androidx.viewpager.widget.ViewPager;
119 import androidx.webkit.WebSettingsCompat;
120 import androidx.webkit.WebViewFeature;
121
122 import com.google.android.material.appbar.AppBarLayout;
123 import com.google.android.material.floatingactionbutton.FloatingActionButton;
124 import com.google.android.material.navigation.NavigationView;
125 import com.google.android.material.snackbar.Snackbar;
126 import com.google.android.material.tabs.TabLayout;
127
128 import com.stoutner.privacybrowser.R;
129 import com.stoutner.privacybrowser.adapters.WebViewPagerAdapter;
130 import com.stoutner.privacybrowser.asynctasks.GetHostIpAddresses;
131 import com.stoutner.privacybrowser.asynctasks.PopulateBlocklists;
132 import com.stoutner.privacybrowser.asynctasks.PrepareSaveDialog;
133 import com.stoutner.privacybrowser.asynctasks.SaveUrl;
134 import com.stoutner.privacybrowser.asynctasks.SaveWebpageImage;
135 import com.stoutner.privacybrowser.dataclasses.PendingDialog;
136 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
137 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
138 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
139 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
140 import com.stoutner.privacybrowser.dialogs.FontSizeDialog;
141 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
142 import com.stoutner.privacybrowser.dialogs.OpenDialog;
143 import com.stoutner.privacybrowser.dialogs.ProxyNotInstalledDialog;
144 import com.stoutner.privacybrowser.dialogs.PinnedMismatchDialog;
145 import com.stoutner.privacybrowser.dialogs.SaveDialog;
146 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
147 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
148 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
149 import com.stoutner.privacybrowser.dialogs.WaitingForProxyDialog;
150 import com.stoutner.privacybrowser.fragments.WebViewTabFragment;
151 import com.stoutner.privacybrowser.helpers.BlocklistHelper;
152 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
153 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
154 import com.stoutner.privacybrowser.helpers.ProxyHelper;
155 import com.stoutner.privacybrowser.helpers.SanitizeUrlHelper;
156 import com.stoutner.privacybrowser.views.NestedScrollWebView;
157
158 import java.io.ByteArrayInputStream;
159 import java.io.ByteArrayOutputStream;
160 import java.io.File;
161 import java.io.FileInputStream;
162 import java.io.FileOutputStream;
163 import java.io.IOException;
164 import java.io.InputStream;
165 import java.io.OutputStream;
166 import java.io.UnsupportedEncodingException;
167
168 import java.net.MalformedURLException;
169 import java.net.URL;
170 import java.net.URLDecoder;
171 import java.net.URLEncoder;
172
173 import java.text.NumberFormat;
174
175 import java.util.ArrayList;
176 import java.util.Date;
177 import java.util.HashMap;
178 import java.util.HashSet;
179 import java.util.List;
180 import java.util.Map;
181 import java.util.Objects;
182 import java.util.Set;
183 import java.util.concurrent.ExecutorService;
184 import java.util.concurrent.Executors;
185
186 import kotlin.Pair;
187
188 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
189         EditBookmarkFolderDialog.EditBookmarkFolderListener, FontSizeDialog.UpdateFontSizeListener, NavigationView.OnNavigationItemSelectedListener, OpenDialog.OpenListener,
190         PinnedMismatchDialog.PinnedMismatchListener, PopulateBlocklists.PopulateBlocklistsListener, SaveDialog.SaveListener, UrlHistoryDialog.NavigateHistoryListener,
191         WebViewTabFragment.NewTabListener {
192
193     // Define the public static variables.
194     public static ExecutorService executorService = Executors.newFixedThreadPool(4);
195     public static String orbotStatus = "unknown";
196     public static ArrayList<PendingDialog> pendingDialogsArrayList =  new ArrayList<>();
197     public static String proxyMode = ProxyHelper.NONE;
198
199     // Declare the public static variables.
200     public static String currentBookmarksFolder = "";
201     public static boolean restartFromBookmarksActivity;
202     public static WebViewPagerAdapter webViewPagerAdapter;
203
204     // Declare the public static views.
205     public static AppBarLayout appBarLayout;
206
207     // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
208     public final static int UNRECOGNIZED_USER_AGENT = -1;
209     public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
210     public final static int SETTINGS_CUSTOM_USER_AGENT = 11;
211     public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
212     public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
213     public final static int DOMAINS_CUSTOM_USER_AGENT = 12;
214
215     // Define the start activity for result request codes.  The public static entry is accessed from `OpenDialog()`.
216     private final int BROWSE_FILE_UPLOAD_REQUEST_CODE = 0;
217     public final static int BROWSE_OPEN_REQUEST_CODE = 1;
218
219     // Define the saved instance state constants.
220     private final String SAVED_STATE_ARRAY_LIST = "saved_state_array_list";
221     private final String SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST = "saved_nested_scroll_webview_state_array_list";
222     private final String SAVED_TAB_POSITION = "saved_tab_position";
223     private final String PROXY_MODE = "proxy_mode";
224
225     // Define the saved instance state variables.
226     private ArrayList<Bundle> savedStateArrayList;
227     private ArrayList<Bundle> savedNestedScrollWebViewStateArrayList;
228     private int savedTabPosition;
229     private String savedProxyMode;
230
231     // Define the class variables.
232     @SuppressWarnings("rawtypes")
233     AsyncTask populateBlocklists;
234
235     // The current WebView is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
236     // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, `applyProxy()`, and `applyDomainSettings()`.
237     private NestedScrollWebView currentWebView;
238
239     // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
240     private final Map<String, String> customHeaders = new HashMap<>();
241
242     // The search URL is set in `applyAppSettings()` and used in `onNewIntent()`, `loadUrlFromTextBox()`, `initializeApp()`, and `initializeWebView()`.
243     private String searchURL;
244
245     // The blocklists are populated in `finishedPopulatingBlocklists()` and accessed from `initializeWebView()`.
246     private ArrayList<List<String[]>> easyList;
247     private ArrayList<List<String[]>> easyPrivacy;
248     private ArrayList<List<String[]>> fanboysAnnoyanceList;
249     private ArrayList<List<String[]>> fanboysSocialList;
250     private ArrayList<List<String[]>> ultraList;
251     private ArrayList<List<String[]>> ultraPrivacy;
252
253     // The action bar drawer toggle is initialized in `onCreate()` and used in `onResume()`.
254     private ActionBarDrawerToggle actionBarDrawerToggle;
255
256     // The color spans are used in `onCreate()` and `highlightUrlText()`.
257     private ForegroundColorSpan redColorSpan;
258     private ForegroundColorSpan initialGrayColorSpan;
259     private ForegroundColorSpan finalGrayColorSpan;
260
261     // `bookmarksCursor` is used in `onDestroy()`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
262     private Cursor bookmarksCursor;
263
264     // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
265     private CursorAdapter bookmarksCursorAdapter;
266
267     // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
268     private String oldFolderNameString;
269
270     // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
271     private ValueCallback<Uri[]> fileChooserCallback;
272
273     // The default progress view offsets are set in `onCreate()` and used in `initializeWebView()`.
274     private int appBarHeight;
275     private int defaultProgressViewStartOffset;
276     private int defaultProgressViewEndOffset;
277
278     // Declare the helpers.
279     private BookmarksDatabaseHelper bookmarksDatabaseHelper;
280     private DomainsDatabaseHelper domainsDatabaseHelper;
281     private ProxyHelper proxyHelper;
282     private SanitizeUrlHelper sanitizeUrlHelper;
283
284     // Declare the class variables
285     private boolean bottomAppBar;
286     private boolean displayingFullScreenVideo;
287     private boolean downloadWithExternalApp;
288     private boolean fullScreenBrowsingModeEnabled;
289     private boolean hideAppBar;
290     private boolean incognitoModeEnabled;
291     private boolean inFullScreenBrowsingMode;
292     private boolean loadingNewIntent;
293     private BroadcastReceiver orbotStatusBroadcastReceiver;
294     private boolean reapplyAppSettingsOnRestart;
295     private boolean reapplyDomainSettingsOnRestart;
296     private boolean sanitizeAmpRedirects;
297     private boolean sanitizeTrackingQueries;
298     private boolean scrollAppBar;
299     private boolean waitingForProxy;
300     private String webViewDefaultUserAgent;
301
302     // Define the class variables.
303     private ObjectAnimator objectAnimator = new ObjectAnimator();
304     private String saveUrlString = "";
305
306     // Declare the class views.
307     private FrameLayout rootFrameLayout;
308     private DrawerLayout drawerLayout;
309     private CoordinatorLayout coordinatorLayout;
310     private Toolbar toolbar;
311     private RelativeLayout urlRelativeLayout;
312     private EditText urlEditText;
313     private ActionBar actionBar;
314     private LinearLayout findOnPageLinearLayout;
315     private LinearLayout tabsLinearLayout;
316     private TabLayout tabLayout;
317     private SwipeRefreshLayout swipeRefreshLayout;
318     private ViewPager webViewPager;
319     private FrameLayout fullScreenVideoFrameLayout;
320
321     // Declare the class menus.
322     private Menu optionsMenu;
323
324     // Declare the class menu items.
325     private MenuItem navigationBackMenuItem;
326     private MenuItem navigationForwardMenuItem;
327     private MenuItem navigationHistoryMenuItem;
328     private MenuItem navigationRequestsMenuItem;
329     private MenuItem optionsPrivacyMenuItem;
330     private MenuItem optionsRefreshMenuItem;
331     private MenuItem optionsCookiesMenuItem;
332     private MenuItem optionsDomStorageMenuItem;
333     private MenuItem optionsSaveFormDataMenuItem;
334     private MenuItem optionsClearDataMenuItem;
335     private MenuItem optionsClearCookiesMenuItem;
336     private MenuItem optionsClearDomStorageMenuItem;
337     private MenuItem optionsClearFormDataMenuItem;
338     private MenuItem optionsBlocklistsMenuItem;
339     private MenuItem optionsEasyListMenuItem;
340     private MenuItem optionsEasyPrivacyMenuItem;
341     private MenuItem optionsFanboysAnnoyanceListMenuItem;
342     private MenuItem optionsFanboysSocialBlockingListMenuItem;
343     private MenuItem optionsUltraListMenuItem;
344     private MenuItem optionsUltraPrivacyMenuItem;
345     private MenuItem optionsBlockAllThirdPartyRequestsMenuItem;
346     private MenuItem optionsProxyMenuItem;
347     private MenuItem optionsProxyNoneMenuItem;
348     private MenuItem optionsProxyTorMenuItem;
349     private MenuItem optionsProxyI2pMenuItem;
350     private MenuItem optionsProxyCustomMenuItem;
351     private MenuItem optionsUserAgentMenuItem;
352     private MenuItem optionsUserAgentPrivacyBrowserMenuItem;
353     private MenuItem optionsUserAgentWebViewDefaultMenuItem;
354     private MenuItem optionsUserAgentFirefoxOnAndroidMenuItem;
355     private MenuItem optionsUserAgentChromeOnAndroidMenuItem;
356     private MenuItem optionsUserAgentSafariOnIosMenuItem;
357     private MenuItem optionsUserAgentFirefoxOnLinuxMenuItem;
358     private MenuItem optionsUserAgentChromiumOnLinuxMenuItem;
359     private MenuItem optionsUserAgentFirefoxOnWindowsMenuItem;
360     private MenuItem optionsUserAgentChromeOnWindowsMenuItem;
361     private MenuItem optionsUserAgentEdgeOnWindowsMenuItem;
362     private MenuItem optionsUserAgentInternetExplorerOnWindowsMenuItem;
363     private MenuItem optionsUserAgentSafariOnMacosMenuItem;
364     private MenuItem optionsUserAgentCustomMenuItem;
365     private MenuItem optionsSwipeToRefreshMenuItem;
366     private MenuItem optionsWideViewportMenuItem;
367     private MenuItem optionsDisplayImagesMenuItem;
368     private MenuItem optionsDarkWebViewMenuItem;
369     private MenuItem optionsFontSizeMenuItem;
370     private MenuItem optionsAddOrEditDomainMenuItem;
371
372     // This variable won't be needed once the class is migrated to Kotlin, as can be seen in LogcatActivity or AboutVersionFragment.
373     private Activity resultLauncherActivityHandle;
374
375     // Define the save URL activity result launcher.  It must be defined before `onCreate()` is run or the app will crash.
376     private final ActivityResultLauncher<String> saveUrlActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.CreateDocument(),
377             new ActivityResultCallback<Uri>() {
378                 @Override
379                 public void onActivityResult(Uri fileUri) {
380                     // Only save the URL if the file URI is not null, which happens if the user exited the file picker by pressing back.
381                     if (fileUri != null) {
382                         new SaveUrl(getApplicationContext(), resultLauncherActivityHandle, fileUri, currentWebView.getSettings().getUserAgentString(), currentWebView.getAcceptCookies()).execute(saveUrlString);
383                     }
384
385                     // Reset the save URL string.
386                     saveUrlString = "";
387                 }
388             });
389
390     // Define the save webpage archive activity result launcher.  It must be defined before `onCreate()` is run or the app will crash.
391     private final ActivityResultLauncher<String> saveWebpageArchiveActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.CreateDocument(),
392             new ActivityResultCallback<Uri>() {
393                 @Override
394                 public void onActivityResult(Uri fileUri) {
395                     // Only save the webpage archive if the file URI is not null, which happens if the user exited the file picker by pressing back.
396                     if (fileUri != null) {
397                         try {
398                             // Create a temporary MHT file.
399                             File temporaryMhtFile = File.createTempFile("temporary_mht_file", ".mht", getCacheDir());
400
401                             // Save the temporary MHT file.
402                             currentWebView.saveWebArchive(temporaryMhtFile.toString(), false, callbackValue -> {
403                                 if (callbackValue != null) {  // The temporary MHT file was saved successfully.
404                                     try {
405                                         // Create a temporary MHT file input stream.
406                                         FileInputStream temporaryMhtFileInputStream = new FileInputStream(temporaryMhtFile);
407
408                                         // Get an output stream for the save webpage file path.
409                                         OutputStream mhtOutputStream = getContentResolver().openOutputStream(fileUri);
410
411                                         // Create a transfer byte array.
412                                         byte[] transferByteArray = new byte[1024];
413
414                                         // Create an integer to track the number of bytes read.
415                                         int bytesRead;
416
417                                         // Copy the temporary MHT file input stream to the MHT output stream.
418                                         while ((bytesRead = temporaryMhtFileInputStream.read(transferByteArray)) > 0) {
419                                             mhtOutputStream.write(transferByteArray, 0, bytesRead);
420                                         }
421
422                                         // Close the streams.
423                                         mhtOutputStream.close();
424                                         temporaryMhtFileInputStream.close();
425
426                                         // Initialize the file name string from the file URI last path segment.
427                                         String fileNameString = fileUri.getLastPathSegment();
428
429                                         // Query the exact file name if the API >= 26.
430                                         if (Build.VERSION.SDK_INT >= 26) {
431                                             // Get a cursor from the content resolver.
432                                             Cursor contentResolverCursor = resultLauncherActivityHandle.getContentResolver().query(fileUri, null, null, null);
433
434                                             // Move to the fist row.
435                                             contentResolverCursor.moveToFirst();
436
437                                             // Get the file name from the cursor.
438                                             fileNameString = contentResolverCursor.getString(contentResolverCursor.getColumnIndexOrThrow(OpenableColumns.DISPLAY_NAME));
439
440                                             // Close the cursor.
441                                             contentResolverCursor.close();
442                                         }
443
444                                         // Display a snackbar.
445                                         Snackbar.make(currentWebView, getString(R.string.file_saved) + "  " + fileNameString, Snackbar.LENGTH_SHORT).show();
446                                     } catch (Exception exception) {
447                                         // Display a snackbar with the exception.
448                                         Snackbar.make(currentWebView, getString(R.string.error_saving_file) + "  " + exception, Snackbar.LENGTH_INDEFINITE).show();
449                                     } finally {
450                                         // Delete the temporary MHT file.
451                                         //noinspection ResultOfMethodCallIgnored
452                                         temporaryMhtFile.delete();
453                                     }
454                                 } else {  // There was an unspecified error while saving the temporary MHT file.
455                                     // Display an error snackbar.
456                                     Snackbar.make(currentWebView, getString(R.string.error_saving_file), Snackbar.LENGTH_INDEFINITE).show();
457                                 }
458                             });
459                         } catch (IOException ioException) {
460                             // Display a snackbar with the IO exception.
461                             Snackbar.make(currentWebView, getString(R.string.error_saving_file) + "  " + ioException, Snackbar.LENGTH_INDEFINITE).show();
462                         }
463                     }
464                 }
465             });
466
467     // Define the save webpage image activity result launcher.  It must be defined before `onCreate()` is run or the app will crash.
468     private final ActivityResultLauncher<String> saveWebpageImageActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.CreateDocument(),
469             new ActivityResultCallback<Uri>() {
470                 @Override
471                 public void onActivityResult(Uri fileUri) {
472                     // Only save the webpage image if the file URI is not null, which happens if the user exited the file picker by pressing back.
473                     if (fileUri != null) {
474                         // Save the webpage image.
475                         new SaveWebpageImage(resultLauncherActivityHandle, fileUri, currentWebView).execute();
476                     }
477                 }
478             });
479
480     // Remove the warning about needing to override `performClick()` when using an `OnTouchListener` with WebView.
481     @SuppressLint("ClickableViewAccessibility")
482     @Override
483     protected void onCreate(Bundle savedInstanceState) {
484         // Run the default commands.
485         super.onCreate(savedInstanceState);
486
487         // Populate the result launcher activity.  This will no longer be needed once the activity has transitioned to Kotlin.
488         resultLauncherActivityHandle = this;
489
490         // Check to see if the activity has been restarted.
491         if (savedInstanceState != null) {
492             // Store the saved instance state variables.
493             savedStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_STATE_ARRAY_LIST);
494             savedNestedScrollWebViewStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST);
495             savedTabPosition = savedInstanceState.getInt(SAVED_TAB_POSITION);
496             savedProxyMode = savedInstanceState.getString(PROXY_MODE);
497         }
498
499         // Initialize the default preference values the first time the program is run.  `false` keeps this command from resetting any current preferences back to default.
500         PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
501
502         // Get a handle for the shared preferences.
503         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
504
505         // Get the preferences.
506         String appTheme = sharedPreferences.getString("app_theme", getString(R.string.app_theme_default_value));
507         boolean allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false);
508         bottomAppBar = sharedPreferences.getBoolean(getString(R.string.bottom_app_bar_key), false);
509
510         // Get the theme entry values string array.
511         String[] appThemeEntryValuesStringArray = getResources().getStringArray(R.array.app_theme_entry_values);
512
513         // 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.
514         if (appTheme.equals(appThemeEntryValuesStringArray[1])) {  // The light theme is selected.
515             // Apply the light theme.
516             AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
517         } else if (appTheme.equals(appThemeEntryValuesStringArray[2])) {  // The dark theme is selected.
518             // Apply the dark theme.
519             AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
520         } else {  // The system default theme is selected.
521             if (Build.VERSION.SDK_INT >= 28) {  // The system default theme is supported.
522                 // Follow the system default theme.
523                 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
524             } else {  // The system default theme is not supported.
525                 // Follow the battery saver mode.
526                 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
527             }
528         }
529
530         // Disable screenshots if not allowed.
531         if (!allowScreenshots) {
532             getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
533         }
534
535         // 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.
536         WebView.enableSlowWholeDocumentDraw();
537
538         // Set the content view according to the position of the app bar.
539         if (bottomAppBar) setContentView(R.layout.main_framelayout_bottom_appbar);
540         else setContentView(R.layout.main_framelayout_top_appbar);
541
542         // Get handles for the views.
543         rootFrameLayout = findViewById(R.id.root_framelayout);
544         drawerLayout = findViewById(R.id.drawerlayout);
545         coordinatorLayout = findViewById(R.id.coordinatorlayout);
546         appBarLayout = findViewById(R.id.appbar_layout);
547         toolbar = findViewById(R.id.toolbar);
548         findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
549         tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
550         tabLayout = findViewById(R.id.tablayout);
551         swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
552         webViewPager = findViewById(R.id.webviewpager);
553         NavigationView navigationView = findViewById(R.id.navigationview);
554         fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
555
556         // Get a handle for the navigation menu.
557         Menu navigationMenu = navigationView.getMenu();
558
559         // Get handles for the navigation menu items.
560         navigationBackMenuItem = navigationMenu.findItem(R.id.back);
561         navigationForwardMenuItem = navigationMenu.findItem(R.id.forward);
562         navigationHistoryMenuItem = navigationMenu.findItem(R.id.history);
563         navigationRequestsMenuItem = navigationMenu.findItem(R.id.requests);
564
565         // Listen for touches on the navigation menu.
566         navigationView.setNavigationItemSelectedListener(this);
567
568         // Get a handle for the app compat delegate.
569         AppCompatDelegate appCompatDelegate = getDelegate();
570
571         // Set the support action bar.
572         appCompatDelegate.setSupportActionBar(toolbar);
573
574         // Get a handle for the action bar.
575         actionBar = appCompatDelegate.getSupportActionBar();
576
577         // Remove the incorrect lint warning below that the action bar might be null.
578         assert actionBar != null;
579
580         // Add the custom layout, which shows the URL text bar.
581         actionBar.setCustomView(R.layout.url_app_bar);
582         actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
583
584         // Get handles for the views in the URL app bar.
585         urlRelativeLayout = findViewById(R.id.url_relativelayout);
586         urlEditText = findViewById(R.id.url_edittext);
587
588         // Create the hamburger icon at the start of the AppBar.
589         actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
590
591         // Initially disable the sliding drawers.  They will be enabled once the blocklists are loaded.
592         drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
593
594         // Initialize the web view pager adapter.
595         webViewPagerAdapter = new WebViewPagerAdapter(getSupportFragmentManager());
596
597         // Set the pager adapter on the web view pager.
598         webViewPager.setAdapter(webViewPagerAdapter);
599
600         // Store up to 100 tabs in memory.
601         webViewPager.setOffscreenPageLimit(100);
602
603         // Instantiate the helpers.
604         bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this);
605         domainsDatabaseHelper = new DomainsDatabaseHelper(this);
606         proxyHelper = new ProxyHelper();
607         sanitizeUrlHelper = new SanitizeUrlHelper();
608
609         // Initialize the app.
610         initializeApp();
611
612         // Apply the app settings from the shared preferences.
613         applyAppSettings();
614
615         // Populate the blocklists.
616         populateBlocklists = new PopulateBlocklists(this, this).execute();
617     }
618
619     @Override
620     protected void onNewIntent(Intent intent) {
621         // Run the default commands.
622         super.onNewIntent(intent);
623
624         // Check to see if the app is being restarted from a saved state.
625         if (savedStateArrayList == null || savedStateArrayList.size() == 0) {  // The activity is not being restarted from a saved state.
626             // Get the information from the intent.
627             String intentAction = intent.getAction();
628             Uri intentUriData = intent.getData();
629             String intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT);
630
631             // Determine if this is a web search.
632             boolean isWebSearch = ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH));
633
634             // 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.
635             if (intentUriData != null || intentStringExtra != null || isWebSearch) {
636                 // Exit the full screen video if it is displayed.
637                 if (displayingFullScreenVideo) {
638                     // Exit full screen video mode.
639                     exitFullScreenVideo();
640
641                     // Reload the current WebView.  Otherwise, it can display entirely black.
642                     currentWebView.reload();
643                 }
644
645                 // Get the shared preferences.
646                 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
647
648                 // Create a URL string.
649                 String url;
650
651                 // If the intent action is a web search, perform the search.
652                 if (isWebSearch) {  // The intent is a web search.
653                     // Create an encoded URL string.
654                     String encodedUrlString;
655
656                     // Sanitize the search input and convert it to a search.
657                     try {
658                         encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
659                     } catch (UnsupportedEncodingException exception) {
660                         encodedUrlString = "";
661                     }
662
663                     // Add the base search URL.
664                     url = searchURL + encodedUrlString;
665                 } else if (intentUriData != null) {  // The intent contains a URL formatted as a URI.
666                     // Set the intent data as the URL.
667                     url = intentUriData.toString();
668                 } else {  // The intent contains a string, which might be a URL.
669                     // Set the intent string as the URL.
670                     url = intentStringExtra;
671                 }
672
673                 // Add a new tab if specified in the preferences.
674                 if (sharedPreferences.getBoolean("open_intents_in_new_tab", true)) {  // Load the URL in a new tab.
675                     // Set the loading new intent flag.
676                     loadingNewIntent = true;
677
678                     // Add a new tab.
679                     addNewTab(url, true);
680                 } else {  // Load the URL in the current tab.
681                     // Make it so.
682                     loadUrl(currentWebView, url);
683                 }
684
685                 // Close the navigation drawer if it is open.
686                 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
687                     drawerLayout.closeDrawer(GravityCompat.START);
688                 }
689
690                 // Close the bookmarks drawer if it is open.
691                 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
692                     drawerLayout.closeDrawer(GravityCompat.END);
693                 }
694             }
695         } else {  // The app has been restarted.
696             // Replace the intent that started the app with this one.  This will load the tab after the others have been restored.
697             setIntent(intent);
698         }
699     }
700
701     @Override
702     public void onRestart() {
703         // Run the default commands.
704         super.onRestart();
705
706         // Apply the app settings if returning from the Settings activity.
707         if (reapplyAppSettingsOnRestart) {
708             // Reset the reapply app settings on restart tracker.
709             reapplyAppSettingsOnRestart = false;
710
711             // Apply the app settings.
712             applyAppSettings();
713         }
714
715         // Apply the domain settings if returning from the settings or domains activity.
716         if (reapplyDomainSettingsOnRestart) {
717             // Reset the reapply domain settings on restart tracker.
718             reapplyDomainSettingsOnRestart = false;
719
720             // Reapply the domain settings for each tab.
721             for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
722                 // Get the WebView tab fragment.
723                 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
724
725                 // Get the fragment view.
726                 View fragmentView = webViewTabFragment.getView();
727
728                 // Only reload the WebViews if they exist.
729                 if (fragmentView != null) {
730                     // Get the nested scroll WebView from the tab fragment.
731                     NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
732
733                     // Reset the current domain name so the domain settings will be reapplied.
734                     nestedScrollWebView.setCurrentDomainName("");
735
736                     // Reapply the domain settings if the URL is not null, which can happen if an empty tab is active when returning from settings.
737                     if (nestedScrollWebView.getUrl() != null) {
738                         applyDomainSettings(nestedScrollWebView, nestedScrollWebView.getUrl(), false, true, false);
739                     }
740                 }
741             }
742         }
743
744         // Update the bookmarks drawer if returning from the Bookmarks activity.
745         if (restartFromBookmarksActivity) {
746             // Close the bookmarks drawer.
747             drawerLayout.closeDrawer(GravityCompat.END);
748
749             // Reload the bookmarks drawer.
750             loadBookmarksFolder();
751
752             // Reset `restartFromBookmarksActivity`.
753             restartFromBookmarksActivity = false;
754         }
755
756         // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.  This can be important if the screen was rotated.
757         updatePrivacyIcons(true);
758     }
759
760     // `onStart()` runs after `onCreate()` or `onRestart()`.  This is used instead of `onResume()` so the commands aren't called every time the screen is partially hidden.
761     @Override
762     public void onStart() {
763         // Run the default commands.
764         super.onStart();
765
766         // Resume any WebViews.
767         for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
768             // Get the WebView tab fragment.
769             WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
770
771             // Get the fragment view.
772             View fragmentView = webViewTabFragment.getView();
773
774             // Only resume the WebViews if they exist (they won't when the app is first created).
775             if (fragmentView != null) {
776                 // Get the nested scroll WebView from the tab fragment.
777                 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
778
779                 // Resume the nested scroll WebView.
780                 nestedScrollWebView.onResume();
781             }
782         }
783
784         // Resume the nested scroll WebView JavaScript timers.  This is a global command that resumes JavaScript timers on all WebViews.
785         if (currentWebView != null) {
786             currentWebView.resumeTimers();
787         }
788
789         // Reapply the proxy settings if the system is using a proxy.  This redisplays the appropriate alert dialog.
790         if (!proxyMode.equals(ProxyHelper.NONE)) {
791             applyProxy(false);
792         }
793
794         // Reapply any system UI flags.
795         if (displayingFullScreenVideo || inFullScreenBrowsingMode) {  // The system is displaying a website or a video in full screen mode.
796             /* Hide the system bars.
797              * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
798              * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
799              * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
800              * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
801              */
802             rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
803                     View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
804         }
805
806         // Show any pending dialogs.
807         for (int i = 0; i < pendingDialogsArrayList.size(); i++) {
808             // Get the pending dialog from the array list.
809             PendingDialog pendingDialog = pendingDialogsArrayList.get(i);
810
811             // Show the pending dialog.
812             pendingDialog.dialogFragment.show(getSupportFragmentManager(), pendingDialog.tag);
813         }
814
815         // Clear the pending dialogs array list.
816         pendingDialogsArrayList.clear();
817     }
818
819     // `onStop()` runs after `onPause()`.  It is used instead of `onPause()` so the commands are not called every time the screen is partially hidden.
820     @Override
821     public void onStop() {
822         // Run the default commands.
823         super.onStop();
824
825         for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
826             // Get the WebView tab fragment.
827             WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
828
829             // Get the fragment view.
830             View fragmentView = webViewTabFragment.getView();
831
832             // Only pause the WebViews if they exist (they won't when the app is first created).
833             if (fragmentView != null) {
834                 // Get the nested scroll WebView from the tab fragment.
835                 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
836
837                 // Pause the nested scroll WebView.
838                 nestedScrollWebView.onPause();
839             }
840         }
841
842         // Pause the WebView JavaScript timers.  This is a global command that pauses JavaScript on all WebViews.
843         if (currentWebView != null) {
844             currentWebView.pauseTimers();
845         }
846     }
847
848     @Override
849     public void onSaveInstanceState(@NonNull Bundle savedInstanceState) {
850         // Run the default commands.
851         super.onSaveInstanceState(savedInstanceState);
852
853         // Create the saved state array lists.
854         ArrayList<Bundle> savedStateArrayList = new ArrayList<>();
855         ArrayList<Bundle> savedNestedScrollWebViewStateArrayList = new ArrayList<>();
856
857         // Get the URLs from each tab.
858         for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
859             // Get the WebView tab fragment.
860             WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
861
862             // Get the fragment view.
863             View fragmentView = webViewTabFragment.getView();
864
865             if (fragmentView != null) {
866                 // Get the nested scroll WebView from the tab fragment.
867                 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
868
869                 // Create saved state bundle.
870                 Bundle savedStateBundle = new Bundle();
871
872                 // Get the current states.
873                 nestedScrollWebView.saveState(savedStateBundle);
874                 Bundle savedNestedScrollWebViewStateBundle = nestedScrollWebView.saveNestedScrollWebViewState();
875
876                 // Store the saved states in the array lists.
877                 savedStateArrayList.add(savedStateBundle);
878                 savedNestedScrollWebViewStateArrayList.add(savedNestedScrollWebViewStateBundle);
879             }
880         }
881
882         // Get the current tab position.
883         int currentTabPosition = tabLayout.getSelectedTabPosition();
884
885         // Store the saved states in the bundle.
886         savedInstanceState.putParcelableArrayList(SAVED_STATE_ARRAY_LIST, savedStateArrayList);
887         savedInstanceState.putParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST, savedNestedScrollWebViewStateArrayList);
888         savedInstanceState.putInt(SAVED_TAB_POSITION, currentTabPosition);
889         savedInstanceState.putString(PROXY_MODE, proxyMode);
890     }
891
892     @Override
893     public void onDestroy() {
894         // Unregister the orbot status broadcast receiver if it exists.
895         if (orbotStatusBroadcastReceiver != null) {
896             this.unregisterReceiver(orbotStatusBroadcastReceiver);
897         }
898
899         // Close the bookmarks cursor if it exists.
900         if (bookmarksCursor != null) {
901             bookmarksCursor.close();
902         }
903
904         // Close the bookmarks database if it exists.
905         if (bookmarksDatabaseHelper != null) {
906             bookmarksDatabaseHelper.close();
907         }
908
909         // Stop populating the blocklists if the AsyncTask is running in the background.
910         if (populateBlocklists != null) {
911             populateBlocklists.cancel(true);
912         }
913
914         // Run the default commands.
915         super.onDestroy();
916     }
917
918     @Override
919     public boolean onCreateOptionsMenu(Menu menu) {
920         // Inflate the menu.  This adds items to the action bar if it is present.
921         getMenuInflater().inflate(R.menu.webview_options_menu, menu);
922
923         // Store a handle for the options menu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons()`.
924         optionsMenu = menu;
925
926         // Get handles for the menu items.
927         optionsPrivacyMenuItem = menu.findItem(R.id.javascript);
928         optionsRefreshMenuItem = menu.findItem(R.id.refresh);
929         MenuItem bookmarksMenuItem = menu.findItem(R.id.bookmarks);
930         optionsCookiesMenuItem = menu.findItem(R.id.cookies);
931         optionsDomStorageMenuItem = menu.findItem(R.id.dom_storage);
932         optionsSaveFormDataMenuItem = menu.findItem(R.id.save_form_data);  // Form data can be removed once the minimum API >= 26.
933         optionsClearDataMenuItem = menu.findItem(R.id.clear_data);
934         optionsClearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
935         optionsClearDomStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
936         optionsClearFormDataMenuItem = menu.findItem(R.id.clear_form_data);  // Form data can be removed once the minimum API >= 26.
937         optionsBlocklistsMenuItem = menu.findItem(R.id.blocklists);
938         optionsEasyListMenuItem = menu.findItem(R.id.easylist);
939         optionsEasyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
940         optionsFanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
941         optionsFanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
942         optionsUltraListMenuItem = menu.findItem(R.id.ultralist);
943         optionsUltraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
944         optionsBlockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
945         optionsProxyMenuItem = menu.findItem(R.id.proxy);
946         optionsProxyNoneMenuItem = menu.findItem(R.id.proxy_none);
947         optionsProxyTorMenuItem = menu.findItem(R.id.proxy_tor);
948         optionsProxyI2pMenuItem = menu.findItem(R.id.proxy_i2p);
949         optionsProxyCustomMenuItem = menu.findItem(R.id.proxy_custom);
950         optionsUserAgentMenuItem = menu.findItem(R.id.user_agent);
951         optionsUserAgentPrivacyBrowserMenuItem = menu.findItem(R.id.user_agent_privacy_browser);
952         optionsUserAgentWebViewDefaultMenuItem = menu.findItem(R.id.user_agent_webview_default);
953         optionsUserAgentFirefoxOnAndroidMenuItem = menu.findItem(R.id.user_agent_firefox_on_android);
954         optionsUserAgentChromeOnAndroidMenuItem = menu.findItem(R.id.user_agent_chrome_on_android);
955         optionsUserAgentSafariOnIosMenuItem = menu.findItem(R.id.user_agent_safari_on_ios);
956         optionsUserAgentFirefoxOnLinuxMenuItem = menu.findItem(R.id.user_agent_firefox_on_linux);
957         optionsUserAgentChromiumOnLinuxMenuItem = menu.findItem(R.id.user_agent_chromium_on_linux);
958         optionsUserAgentFirefoxOnWindowsMenuItem = menu.findItem(R.id.user_agent_firefox_on_windows);
959         optionsUserAgentChromeOnWindowsMenuItem = menu.findItem(R.id.user_agent_chrome_on_windows);
960         optionsUserAgentEdgeOnWindowsMenuItem = menu.findItem(R.id.user_agent_edge_on_windows);
961         optionsUserAgentInternetExplorerOnWindowsMenuItem = menu.findItem(R.id.user_agent_internet_explorer_on_windows);
962         optionsUserAgentSafariOnMacosMenuItem = menu.findItem(R.id.user_agent_safari_on_macos);
963         optionsUserAgentCustomMenuItem = menu.findItem(R.id.user_agent_custom);
964         optionsSwipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
965         optionsWideViewportMenuItem = menu.findItem(R.id.wide_viewport);
966         optionsDisplayImagesMenuItem = menu.findItem(R.id.display_images);
967         optionsDarkWebViewMenuItem = menu.findItem(R.id.dark_webview);
968         optionsFontSizeMenuItem = menu.findItem(R.id.font_size);
969         optionsAddOrEditDomainMenuItem = menu.findItem(R.id.add_or_edit_domain);
970
971         // Set the initial status of the privacy icons.  `false` does not call `invalidateOptionsMenu` as the last step.
972         updatePrivacyIcons(false);
973
974         // Only display the form data menu items if the API < 26.
975         optionsSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
976         optionsClearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
977
978         // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
979         optionsClearFormDataMenuItem.setEnabled(Build.VERSION.SDK_INT < 26);
980
981         // Get the shared preferences.
982         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
983
984         // Get the dark theme and app bar preferences.
985         boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false);
986
987         // 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.
988         if (displayAdditionalAppBarIcons) {
989             optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
990             bookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
991             optionsCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
992         } else { //Do not display the additional icons.
993             optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
994             bookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
995             optionsCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
996         }
997
998         // Replace Refresh with Stop if a URL is already loading.
999         if (currentWebView != null && currentWebView.getProgress() != 100) {
1000             // Set the title.
1001             optionsRefreshMenuItem.setTitle(R.string.stop);
1002
1003             // Set the icon if it is displayed in the app bar.  Once the minimum API is >= 26, the blue and black icons can be combined with a tint list.
1004             if (displayAdditionalAppBarIcons) {
1005                 optionsRefreshMenuItem.setIcon(R.drawable.close_blue);
1006             }
1007         }
1008
1009         // Done.
1010         return true;
1011     }
1012
1013     @Override
1014     public boolean onPrepareOptionsMenu(Menu menu) {
1015         // Get a handle for the cookie manager.
1016         CookieManager cookieManager = CookieManager.getInstance();
1017
1018         // Initialize the current user agent string and the font size.
1019         String currentUserAgent = getString(R.string.user_agent_privacy_browser);
1020         int fontSize = 100;
1021
1022         // 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.
1023         if (currentWebView != null) {
1024             // Set the add or edit domain text.
1025             if (currentWebView.getDomainSettingsApplied()) {
1026                 optionsAddOrEditDomainMenuItem.setTitle(R.string.edit_domain_settings);
1027             } else {
1028                 optionsAddOrEditDomainMenuItem.setTitle(R.string.add_domain_settings);
1029             }
1030
1031             // Get the current user agent from the WebView.
1032             currentUserAgent = currentWebView.getSettings().getUserAgentString();
1033
1034             // Get the current font size from the
1035             fontSize = currentWebView.getSettings().getTextZoom();
1036
1037             // Set the status of the menu item checkboxes.
1038             optionsDomStorageMenuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1039             optionsSaveFormDataMenuItem.setChecked(currentWebView.getSettings().getSaveFormData());  // Form data can be removed once the minimum API >= 26.
1040             optionsEasyListMenuItem.setChecked(currentWebView.getEasyListEnabled());
1041             optionsEasyPrivacyMenuItem.setChecked(currentWebView.getEasyPrivacyEnabled());
1042             optionsFanboysAnnoyanceListMenuItem.setChecked(currentWebView.getFanboysAnnoyanceListEnabled());
1043             optionsFanboysSocialBlockingListMenuItem.setChecked(currentWebView.getFanboysSocialBlockingListEnabled());
1044             optionsUltraListMenuItem.setChecked(currentWebView.getUltraListEnabled());
1045             optionsUltraPrivacyMenuItem.setChecked(currentWebView.getUltraPrivacyEnabled());
1046             optionsBlockAllThirdPartyRequestsMenuItem.setChecked(currentWebView.getBlockAllThirdPartyRequests());
1047             optionsSwipeToRefreshMenuItem.setChecked(currentWebView.getSwipeToRefresh());
1048             optionsWideViewportMenuItem.setChecked(currentWebView.getSettings().getUseWideViewPort());
1049             optionsDisplayImagesMenuItem.setChecked(currentWebView.getSettings().getLoadsImagesAutomatically());
1050
1051             // Initialize the display names for the blocklists with the number of blocked requests.
1052             optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
1053             optionsEasyListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYLIST) + " - " + getString(R.string.easylist));
1054             optionsEasyPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYPRIVACY) + " - " + getString(R.string.easyprivacy));
1055             optionsFanboysAnnoyanceListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " + getString(R.string.fanboys_annoyance_list));
1056             optionsFanboysSocialBlockingListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " + getString(R.string.fanboys_social_blocking_list));
1057             optionsUltraListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRALIST) + " - " + getString(R.string.ultralist));
1058             optionsUltraPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRAPRIVACY) + " - " + getString(R.string.ultraprivacy));
1059             optionsBlockAllThirdPartyRequestsMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " + getString(R.string.block_all_third_party_requests));
1060
1061             // Enable DOM Storage if JavaScript is enabled.
1062             optionsDomStorageMenuItem.setEnabled(currentWebView.getSettings().getJavaScriptEnabled());
1063
1064             // Set the checkbox status for dark WebView if the WebView supports it.
1065             if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
1066                 optionsDarkWebViewMenuItem.setChecked(WebSettingsCompat.getForceDark(currentWebView.getSettings()) == WebSettingsCompat.FORCE_DARK_ON);
1067             }
1068         }
1069
1070         // Set the cookies menu item checked status.
1071         optionsCookiesMenuItem.setChecked(cookieManager.acceptCookie());
1072
1073         // Enable Clear Cookies if there are any.
1074         optionsClearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1075
1076         // 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`.
1077         String privateDataDirectoryString = getApplicationInfo().dataDir;
1078
1079         // Get a count of the number of files in the Local Storage directory.
1080         File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1081         int localStorageDirectoryNumberOfFiles = 0;
1082         if (localStorageDirectory.exists()) {
1083             // `Objects.requireNonNull` removes a lint warning that `localStorageDirectory.list` might produce a null pointed exception if it is dereferenced.
1084             localStorageDirectoryNumberOfFiles = Objects.requireNonNull(localStorageDirectory.list()).length;
1085         }
1086
1087         // Get a count of the number of files in the IndexedDB directory.
1088         File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1089         int indexedDBDirectoryNumberOfFiles = 0;
1090         if (indexedDBDirectory.exists()) {
1091             // `Objects.requireNonNull` removes a lint warning that `indexedDBDirectory.list` might produce a null pointed exception if it is dereferenced.
1092             indexedDBDirectoryNumberOfFiles = Objects.requireNonNull(indexedDBDirectory.list()).length;
1093         }
1094
1095         // Enable Clear DOM Storage if there is any.
1096         optionsClearDomStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1097
1098         // Enable Clear Form Data is there is any.  This can be removed once the minimum API >= 26.
1099         if (Build.VERSION.SDK_INT < 26) {
1100             // Get the WebView database.
1101             WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1102
1103             // Enable the clear form data menu item if there is anything to clear.
1104             optionsClearFormDataMenuItem.setEnabled(webViewDatabase.hasFormData());
1105         }
1106
1107         // Enable Clear Data if any of the submenu items are enabled.
1108         optionsClearDataMenuItem.setEnabled(optionsClearCookiesMenuItem.isEnabled() || optionsClearDomStorageMenuItem.isEnabled() || optionsClearFormDataMenuItem.isEnabled());
1109
1110         // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
1111         optionsFanboysSocialBlockingListMenuItem.setEnabled(!optionsFanboysAnnoyanceListMenuItem.isChecked());
1112
1113         // Set the proxy title and check the applied proxy.
1114         switch (proxyMode) {
1115             case ProxyHelper.NONE:
1116                 // Set the proxy title.
1117                 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_none));
1118
1119                 // Check the proxy None radio button.
1120                 optionsProxyNoneMenuItem.setChecked(true);
1121                 break;
1122
1123             case ProxyHelper.TOR:
1124                 // Set the proxy title.
1125                 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_tor));
1126
1127                 // Check the proxy Tor radio button.
1128                 optionsProxyTorMenuItem.setChecked(true);
1129                 break;
1130
1131             case ProxyHelper.I2P:
1132                 // Set the proxy title.
1133                 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_i2p));
1134
1135                 // Check the proxy I2P radio button.
1136                 optionsProxyI2pMenuItem.setChecked(true);
1137                 break;
1138
1139             case ProxyHelper.CUSTOM:
1140                 // Set the proxy title.
1141                 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_custom));
1142
1143                 // Check the proxy Custom radio button.
1144                 optionsProxyCustomMenuItem.setChecked(true);
1145                 break;
1146         }
1147
1148         // Select the current user agent menu item.  A switch statement cannot be used because the user agents are not compile time constants.
1149         if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) {  // Privacy Browser.
1150             // Update the user agent menu item title.
1151             optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_privacy_browser));
1152
1153             // Select the Privacy Browser radio box.
1154             optionsUserAgentPrivacyBrowserMenuItem.setChecked(true);
1155         } else if (currentUserAgent.equals(webViewDefaultUserAgent)) {  // WebView Default.
1156             // Update the user agent menu item title.
1157             optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_webview_default));
1158
1159             // Select the WebView Default radio box.
1160             optionsUserAgentWebViewDefaultMenuItem.setChecked(true);
1161         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) {  // Firefox on Android.
1162             // Update the user agent menu item title.
1163             optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_android));
1164
1165             // Select the Firefox on Android radio box.
1166             optionsUserAgentFirefoxOnAndroidMenuItem.setChecked(true);
1167         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) {  // Chrome on Android.
1168             // Update the user agent menu item title.
1169             optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_android));
1170
1171             // Select the Chrome on Android radio box.
1172             optionsUserAgentChromeOnAndroidMenuItem.setChecked(true);
1173         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) {  // Safari on iOS.
1174             // Update the user agent menu item title.
1175             optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_ios));
1176
1177             // Select the Safari on iOS radio box.
1178             optionsUserAgentSafariOnIosMenuItem.setChecked(true);
1179         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) {  // Firefox on Linux.
1180             // Update the user agent menu item title.
1181             optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_linux));
1182
1183             // Select the Firefox on Linux radio box.
1184             optionsUserAgentFirefoxOnLinuxMenuItem.setChecked(true);
1185         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) {  // Chromium on Linux.
1186             // Update the user agent menu item title.
1187             optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chromium_on_linux));
1188
1189             // Select the Chromium on Linux radio box.
1190             optionsUserAgentChromiumOnLinuxMenuItem.setChecked(true);
1191         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) {  // Firefox on Windows.
1192             // Update the user agent menu item title.
1193             optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_windows));
1194
1195             // Select the Firefox on Windows radio box.
1196             optionsUserAgentFirefoxOnWindowsMenuItem.setChecked(true);
1197         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) {  // Chrome on Windows.
1198             // Update the user agent menu item title.
1199             optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_windows));
1200
1201             // Select the Chrome on Windows radio box.
1202             optionsUserAgentChromeOnWindowsMenuItem.setChecked(true);
1203         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) {  // Edge on Windows.
1204             // Update the user agent menu item title.
1205             optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_edge_on_windows));
1206
1207             // Select the Edge on Windows radio box.
1208             optionsUserAgentEdgeOnWindowsMenuItem.setChecked(true);
1209         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) {  // Internet Explorer on Windows.
1210             // Update the user agent menu item title.
1211             optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_internet_explorer_on_windows));
1212
1213             // Select the Internet on Windows radio box.
1214             optionsUserAgentInternetExplorerOnWindowsMenuItem.setChecked(true);
1215         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) {  // Safari on macOS.
1216             // Update the user agent menu item title.
1217             optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_macos));
1218
1219             // Select the Safari on macOS radio box.
1220             optionsUserAgentSafariOnMacosMenuItem.setChecked(true);
1221         } else {  // Custom user agent.
1222             // Update the user agent menu item title.
1223             optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_custom));
1224
1225             // Select the Custom radio box.
1226             optionsUserAgentCustomMenuItem.setChecked(true);
1227         }
1228
1229         // Set the font size title.
1230         optionsFontSizeMenuItem.setTitle(getString(R.string.font_size) + " - " + fontSize + "%");
1231
1232         // Run all the other default commands.
1233         super.onPrepareOptionsMenu(menu);
1234
1235         // Display the menu.
1236         return true;
1237     }
1238
1239     @Override
1240     public boolean onOptionsItemSelected(MenuItem menuItem) {
1241         // Get a handle for the shared preferences.
1242         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1243
1244         // Get a handle for the cookie manager.
1245         CookieManager cookieManager = CookieManager.getInstance();
1246
1247         // Get the selected menu item ID.
1248         int menuItemId = menuItem.getItemId();
1249
1250         // Run the commands that correlate to the selected menu item.
1251         if (menuItemId == R.id.javascript) {  // JavaScript.
1252             // Toggle the JavaScript status.
1253             currentWebView.getSettings().setJavaScriptEnabled(!currentWebView.getSettings().getJavaScriptEnabled());
1254
1255             // Update the privacy icon.
1256             updatePrivacyIcons(true);
1257
1258             // Display a `Snackbar`.
1259             if (currentWebView.getSettings().getJavaScriptEnabled()) {  // JavaScrip is enabled.
1260                 Snackbar.make(webViewPager, R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1261             } else if (cookieManager.acceptCookie()) {  // JavaScript is disabled, but first-party cookies are enabled.
1262                 Snackbar.make(webViewPager, R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1263             } else {  // Privacy mode.
1264                 Snackbar.make(webViewPager, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1265             }
1266
1267             // Reload the current WebView.
1268             currentWebView.reload();
1269
1270             // Consume the event.
1271             return true;
1272         } else if (menuItemId == R.id.refresh) {  // Refresh.
1273             // Run the command that correlates to the current status of the menu item.
1274             if (menuItem.getTitle().equals(getString(R.string.refresh))) {  // The refresh button was pushed.
1275                 // Reload the current WebView.
1276                 currentWebView.reload();
1277             } else {  // The stop button was pushed.
1278                 // Stop the loading of the WebView.
1279                 currentWebView.stopLoading();
1280             }
1281
1282             // Consume the event.
1283             return true;
1284         } else if (menuItemId == R.id.bookmarks) {  // Bookmarks.
1285             // Open the bookmarks drawer.
1286             drawerLayout.openDrawer(GravityCompat.END);
1287
1288             // Consume the event.
1289             return true;
1290         } else if (menuItemId == R.id.cookies) {  // Cookies.
1291             // Switch the first-party cookie status.
1292             cookieManager.setAcceptCookie(!cookieManager.acceptCookie());
1293
1294             // Store the cookie status.
1295             currentWebView.setAcceptCookies(cookieManager.acceptCookie());
1296
1297             // Update the menu checkbox.
1298             menuItem.setChecked(cookieManager.acceptCookie());
1299
1300             // Update the privacy icon.
1301             updatePrivacyIcons(true);
1302
1303             // Display a snackbar.
1304             if (cookieManager.acceptCookie()) {  // Cookies are enabled.
1305                 Snackbar.make(webViewPager, R.string.cookies_enabled, Snackbar.LENGTH_SHORT).show();
1306             } else if (currentWebView.getSettings().getJavaScriptEnabled()) {  // JavaScript is still enabled.
1307                 Snackbar.make(webViewPager, R.string.cookies_disabled, Snackbar.LENGTH_SHORT).show();
1308             } else {  // Privacy mode.
1309                 Snackbar.make(webViewPager, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1310             }
1311
1312             // Reload the current WebView.
1313             currentWebView.reload();
1314
1315             // Consume the event.
1316             return true;
1317         } else if (menuItemId == R.id.dom_storage) {  // DOM storage.
1318             // Toggle the status of domStorageEnabled.
1319             currentWebView.getSettings().setDomStorageEnabled(!currentWebView.getSettings().getDomStorageEnabled());
1320
1321             // Update the menu checkbox.
1322             menuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1323
1324             // Update the privacy icon.
1325             updatePrivacyIcons(true);
1326
1327             // Display a snackbar.
1328             if (currentWebView.getSettings().getDomStorageEnabled()) {
1329                 Snackbar.make(webViewPager, R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1330             } else {
1331                 Snackbar.make(webViewPager, R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1332             }
1333
1334             // Reload the current WebView.
1335             currentWebView.reload();
1336
1337             // Consume the event.
1338             return true;
1339         } else if (menuItemId == R.id.save_form_data) {  // Form data.  This can be removed once the minimum API >= 26.
1340             // Switch the status of saveFormDataEnabled.
1341             currentWebView.getSettings().setSaveFormData(!currentWebView.getSettings().getSaveFormData());
1342
1343             // Update the menu checkbox.
1344             menuItem.setChecked(currentWebView.getSettings().getSaveFormData());
1345
1346             // Display a snackbar.
1347             if (currentWebView.getSettings().getSaveFormData()) {
1348                 Snackbar.make(webViewPager, R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1349             } else {
1350                 Snackbar.make(webViewPager, R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1351             }
1352
1353             // Update the privacy icon.
1354             updatePrivacyIcons(true);
1355
1356             // Reload the current WebView.
1357             currentWebView.reload();
1358
1359             // Consume the event.
1360             return true;
1361         } else if (menuItemId == R.id.clear_cookies) {  // Clear cookies.
1362             // Create a snackbar.
1363             Snackbar.make(webViewPager, R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1364                     .setAction(R.string.undo, v -> {
1365                         // Do nothing because everything will be handled by `onDismissed()` below.
1366                     })
1367                     .addCallback(new Snackbar.Callback() {
1368                         @Override
1369                         public void onDismissed(Snackbar snackbar, int event) {
1370                             if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) {  // The snackbar was dismissed without the undo button being pushed.
1371                                 // Delete the cookies.
1372                                 cookieManager.removeAllCookies(null);
1373                             }
1374                         }
1375                     })
1376                     .show();
1377
1378             // Consume the event.
1379             return true;
1380         } else if (menuItemId == R.id.clear_dom_storage) {  // Clear DOM storage.
1381             // Create a snackbar.
1382             Snackbar.make(webViewPager, R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1383                     .setAction(R.string.undo, v -> {
1384                         // Do nothing because everything will be handled by `onDismissed()` below.
1385                     })
1386                     .addCallback(new Snackbar.Callback() {
1387                         @Override
1388                         public void onDismissed(Snackbar snackbar, int event) {
1389                             if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) {  // The snackbar was dismissed without the undo button being pushed.
1390                                 // Delete the DOM Storage.
1391                                 WebStorage webStorage = WebStorage.getInstance();
1392                                 webStorage.deleteAllData();
1393
1394                                 // Initialize a handler to manually delete the DOM storage files and directories.
1395                                 Handler deleteDomStorageHandler = new Handler();
1396
1397                                 // Setup a runnable to manually delete the DOM storage files and directories.
1398                                 Runnable deleteDomStorageRunnable = () -> {
1399                                     try {
1400                                         // Get a handle for the runtime.
1401                                         Runtime runtime = Runtime.getRuntime();
1402
1403                                         // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1404                                         // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1405                                         String privateDataDirectoryString = getApplicationInfo().dataDir;
1406
1407                                         // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1408                                         Process deleteLocalStorageProcess = runtime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1409
1410                                         // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1411                                         Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1412                                         Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1413                                         Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1414                                         Process deleteDatabasesProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1415
1416                                         // Wait for the processes to finish.
1417                                         deleteLocalStorageProcess.waitFor();
1418                                         deleteIndexProcess.waitFor();
1419                                         deleteQuotaManagerProcess.waitFor();
1420                                         deleteQuotaManagerJournalProcess.waitFor();
1421                                         deleteDatabasesProcess.waitFor();
1422                                     } catch (Exception exception) {
1423                                         // Do nothing if an error is thrown.
1424                                     }
1425                                 };
1426
1427                                 // Manually delete the DOM storage files after 200 milliseconds.
1428                                 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
1429                             }
1430                         }
1431                     })
1432                     .show();
1433
1434             // Consume the event.
1435             return true;
1436         } else if (menuItemId == R.id.clear_form_data) {  // Clear form data.  This can be remove once the minimum API >= 26.
1437             // Create a snackbar.
1438             Snackbar.make(webViewPager, R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1439                     .setAction(R.string.undo, v -> {
1440                         // Do nothing because everything will be handled by `onDismissed()` below.
1441                     })
1442                     .addCallback(new Snackbar.Callback() {
1443                         @Override
1444                         public void onDismissed(Snackbar snackbar, int event) {
1445                             if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) {  // The snackbar was dismissed without the undo button being pushed.
1446                                 // Get a handle for the webView database.
1447                                 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1448
1449                                 // Delete the form data.
1450                                 webViewDatabase.clearFormData();
1451                             }
1452                         }
1453                     })
1454                     .show();
1455
1456             // Consume the event.
1457             return true;
1458         } else if (menuItemId == R.id.easylist) {  // EasyList.
1459             // Toggle the EasyList status.
1460             currentWebView.setEasyListEnabled(!currentWebView.getEasyListEnabled());
1461
1462             // Update the menu checkbox.
1463             menuItem.setChecked(currentWebView.getEasyListEnabled());
1464
1465             // Reload the current WebView.
1466             currentWebView.reload();
1467
1468             // Consume the event.
1469             return true;
1470         } else if (menuItemId == R.id.easyprivacy) {  // EasyPrivacy.
1471             // Toggle the EasyPrivacy status.
1472             currentWebView.setEasyPrivacyEnabled(!currentWebView.getEasyPrivacyEnabled());
1473
1474             // Update the menu checkbox.
1475             menuItem.setChecked(currentWebView.getEasyPrivacyEnabled());
1476
1477             // Reload the current WebView.
1478             currentWebView.reload();
1479
1480             // Consume the event.
1481             return true;
1482         } else if (menuItemId == R.id.fanboys_annoyance_list) {  // Fanboy's Annoyance List.
1483             // Toggle Fanboy's Annoyance List status.
1484             currentWebView.setFanboysAnnoyanceListEnabled(!currentWebView.getFanboysAnnoyanceListEnabled());
1485
1486             // Update the menu checkbox.
1487             menuItem.setChecked(currentWebView.getFanboysAnnoyanceListEnabled());
1488
1489             // Update the status of Fanboy's Social Blocking List.
1490             optionsFanboysSocialBlockingListMenuItem.setEnabled(!currentWebView.getFanboysAnnoyanceListEnabled());
1491
1492             // Reload the current WebView.
1493             currentWebView.reload();
1494
1495             // Consume the event.
1496             return true;
1497         } else if (menuItemId == R.id.fanboys_social_blocking_list) {  // Fanboy's Social Blocking List.
1498             // Toggle Fanboy's Social Blocking List status.
1499             currentWebView.setFanboysSocialBlockingListEnabled(!currentWebView.getFanboysSocialBlockingListEnabled());
1500
1501             // Update the menu checkbox.
1502             menuItem.setChecked(currentWebView.getFanboysSocialBlockingListEnabled());
1503
1504             // Reload the current WebView.
1505             currentWebView.reload();
1506
1507             // Consume the event.
1508             return true;
1509         } else if (menuItemId == R.id.ultralist) {  // UltraList.
1510             // Toggle the UltraList status.
1511             currentWebView.setUltraListEnabled(!currentWebView.getUltraListEnabled());
1512
1513             // Update the menu checkbox.
1514             menuItem.setChecked(currentWebView.getUltraListEnabled());
1515
1516             // Reload the current WebView.
1517             currentWebView.reload();
1518
1519             // Consume the event.
1520             return true;
1521         } else if (menuItemId == R.id.ultraprivacy) {  // UltraPrivacy.
1522             // Toggle the UltraPrivacy status.
1523             currentWebView.setUltraPrivacyEnabled(!currentWebView.getUltraPrivacyEnabled());
1524
1525             // Update the menu checkbox.
1526             menuItem.setChecked(currentWebView.getUltraPrivacyEnabled());
1527
1528             // Reload the current WebView.
1529             currentWebView.reload();
1530
1531             // Consume the event.
1532             return true;
1533         } else if (menuItemId == R.id.block_all_third_party_requests) {  // Block all third-party requests.
1534             //Toggle the third-party requests blocker status.
1535             currentWebView.setBlockAllThirdPartyRequests(!currentWebView.getBlockAllThirdPartyRequests());
1536
1537             // Update the menu checkbox.
1538             menuItem.setChecked(currentWebView.getBlockAllThirdPartyRequests());
1539
1540             // Reload the current WebView.
1541             currentWebView.reload();
1542
1543             // Consume the event.
1544             return true;
1545         } else if (menuItemId == R.id.proxy_none) {  // Proxy - None.
1546             // Update the proxy mode.
1547             proxyMode = ProxyHelper.NONE;
1548
1549             // Apply the proxy mode.
1550             applyProxy(true);
1551
1552             // Consume the event.
1553             return true;
1554         } else if (menuItemId == R.id.proxy_tor) {  // Proxy - Tor.
1555             // Update the proxy mode.
1556             proxyMode = ProxyHelper.TOR;
1557
1558             // Apply the proxy mode.
1559             applyProxy(true);
1560
1561             // Consume the event.
1562             return true;
1563         } else if (menuItemId == R.id.proxy_i2p) {  // Proxy - I2P.
1564             // Update the proxy mode.
1565             proxyMode = ProxyHelper.I2P;
1566
1567             // Apply the proxy mode.
1568             applyProxy(true);
1569
1570             // Consume the event.
1571             return true;
1572         } else if (menuItemId == R.id.proxy_custom) {  // Proxy - Custom.
1573             // Update the proxy mode.
1574             proxyMode = ProxyHelper.CUSTOM;
1575
1576             // Apply the proxy mode.
1577             applyProxy(true);
1578
1579             // Consume the event.
1580             return true;
1581         } else if (menuItemId == R.id.user_agent_privacy_browser) {  // User Agent - Privacy Browser.
1582             // Update the user agent.
1583             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
1584
1585             // Reload the current WebView.
1586             currentWebView.reload();
1587
1588             // Consume the event.
1589             return true;
1590         } else if (menuItemId == R.id.user_agent_webview_default) {  // User Agent - WebView Default.
1591             // Update the user agent.
1592             currentWebView.getSettings().setUserAgentString("");
1593
1594             // Reload the current WebView.
1595             currentWebView.reload();
1596
1597             // Consume the event.
1598             return true;
1599         } else if (menuItemId == R.id.user_agent_firefox_on_android) {  // User Agent - Firefox on Android.
1600             // Update the user agent.
1601             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
1602
1603             // Reload the current WebView.
1604             currentWebView.reload();
1605
1606             // Consume the event.
1607             return true;
1608         } else if (menuItemId == R.id.user_agent_chrome_on_android) {  // User Agent - Chrome on Android.
1609             // Update the user agent.
1610             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
1611
1612             // Reload the current WebView.
1613             currentWebView.reload();
1614
1615             // Consume the event.
1616             return true;
1617         } else if (menuItemId == R.id.user_agent_safari_on_ios) {  // User Agent - Safari on iOS.
1618             // Update the user agent.
1619             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
1620
1621             // Reload the current WebView.
1622             currentWebView.reload();
1623
1624             // Consume the event.
1625             return true;
1626         } else if (menuItemId == R.id.user_agent_firefox_on_linux) {  // User Agent - Firefox on Linux.
1627             // Update the user agent.
1628             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
1629
1630             // Reload the current WebView.
1631             currentWebView.reload();
1632
1633             // Consume the event.
1634             return true;
1635         } else if (menuItemId == R.id.user_agent_chromium_on_linux) {  // User Agent - Chromium on Linux.
1636             // Update the user agent.
1637             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
1638
1639             // Reload the current WebView.
1640             currentWebView.reload();
1641
1642             // Consume the event.
1643             return true;
1644         } else if (menuItemId == R.id.user_agent_firefox_on_windows) {  // User Agent - Firefox on Windows.
1645             // Update the user agent.
1646             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
1647
1648             // Reload the current WebView.
1649             currentWebView.reload();
1650
1651             // Consume the event.
1652             return true;
1653         } else if (menuItemId == R.id.user_agent_chrome_on_windows) {  // User Agent - Chrome on Windows.
1654             // Update the user agent.
1655             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
1656
1657             // Reload the current WebView.
1658             currentWebView.reload();
1659
1660             // Consume the event.
1661             return true;
1662         } else if (menuItemId == R.id.user_agent_edge_on_windows) {  // User Agent - Edge on Windows.
1663             // Update the user agent.
1664             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
1665
1666             // Reload the current WebView.
1667             currentWebView.reload();
1668
1669             // Consume the event.
1670             return true;
1671         } else if (menuItemId == R.id.user_agent_internet_explorer_on_windows) {  // User Agent - Internet Explorer on Windows.
1672             // Update the user agent.
1673             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
1674
1675             // Reload the current WebView.
1676             currentWebView.reload();
1677
1678             // Consume the event.
1679             return true;
1680         } else if (menuItemId == R.id.user_agent_safari_on_macos) {  // User Agent - Safari on macOS.
1681             // Update the user agent.
1682             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
1683
1684             // Reload the current WebView.
1685             currentWebView.reload();
1686
1687             // Consume the event.
1688             return true;
1689         } else if (menuItemId == R.id.user_agent_custom) {  // User Agent - Custom.
1690             // Update the user agent.
1691             currentWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
1692
1693             // Reload the current WebView.
1694             currentWebView.reload();
1695
1696             // Consume the event.
1697             return true;
1698         } else if (menuItemId == R.id.font_size) {  // Font size.
1699             // Instantiate the font size dialog.
1700             DialogFragment fontSizeDialogFragment = FontSizeDialog.displayDialog(currentWebView.getSettings().getTextZoom());
1701
1702             // Show the font size dialog.
1703             fontSizeDialogFragment.show(getSupportFragmentManager(), getString(R.string.font_size));
1704
1705             // Consume the event.
1706             return true;
1707         } else if (menuItemId == R.id.swipe_to_refresh) {  // Swipe to refresh.
1708             // Toggle the stored status of swipe to refresh.
1709             currentWebView.setSwipeToRefresh(!currentWebView.getSwipeToRefresh());
1710
1711             // Update the swipe refresh layout.
1712             if (currentWebView.getSwipeToRefresh()) {  // Swipe to refresh is enabled.
1713                 // Only enable the swipe refresh layout if the WebView is scrolled to the top.  It is updated every time the scroll changes.
1714                 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
1715             } else {  // Swipe to refresh is disabled.
1716                 // Disable the swipe refresh layout.
1717                 swipeRefreshLayout.setEnabled(false);
1718             }
1719
1720             // Consume the event.
1721             return true;
1722         } else if (menuItemId == R.id.wide_viewport) {  // Wide viewport.
1723             // Toggle the viewport.
1724             currentWebView.getSettings().setUseWideViewPort(!currentWebView.getSettings().getUseWideViewPort());
1725
1726             // Consume the event.
1727             return true;
1728         } else if (menuItemId == R.id.display_images) {  // Display images.
1729             // Toggle the displaying of images.
1730             if (currentWebView.getSettings().getLoadsImagesAutomatically()) {  // Images are currently loaded automatically.
1731                 // Disable loading of images.
1732                 currentWebView.getSettings().setLoadsImagesAutomatically(false);
1733
1734                 // Reload the website to remove existing images.
1735                 currentWebView.reload();
1736             } else {  // Images are not currently loaded automatically.
1737                 // Enable loading of images.  Missing images will be loaded without the need for a reload.
1738                 currentWebView.getSettings().setLoadsImagesAutomatically(true);
1739             }
1740
1741             // Consume the event.
1742             return true;
1743         } else if (menuItemId == R.id.dark_webview) {  // Dark WebView.
1744             // Check to see if dark WebView is supported by this WebView.
1745             if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
1746                 // Toggle the dark WebView setting.
1747                 if (WebSettingsCompat.getForceDark(currentWebView.getSettings()) == WebSettingsCompat.FORCE_DARK_ON) {  // Dark WebView is currently enabled.
1748                     // Turn off dark WebView.
1749                     WebSettingsCompat.setForceDark(currentWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
1750                 } else {  // Dark WebView is currently disabled.
1751                     // Turn on dark WebView.
1752                     WebSettingsCompat.setForceDark(currentWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
1753                 }
1754             }
1755
1756             // Consume the event.
1757             return true;
1758         } else if (menuItemId == R.id.find_on_page) {  // Find on page.
1759             // Get a handle for the views.
1760             Toolbar toolbar = findViewById(R.id.toolbar);
1761             LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
1762             EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
1763
1764             // Set the minimum height of the find on page linear layout to match the toolbar.
1765             findOnPageLinearLayout.setMinimumHeight(toolbar.getHeight());
1766
1767             // Hide the toolbar.
1768             toolbar.setVisibility(View.GONE);
1769
1770             // Show the find on page linear layout.
1771             findOnPageLinearLayout.setVisibility(View.VISIBLE);
1772
1773             // Display the keyboard.  The app must wait 200 ms before running the command to work around a bug in Android.
1774             // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1775             findOnPageEditText.postDelayed(() -> {
1776                 // Set the focus on the find on page edit text.
1777                 findOnPageEditText.requestFocus();
1778
1779                 // Get a handle for the input method manager.
1780                 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1781
1782                 // Remove the lint warning below that the input method manager might be null.
1783                 assert inputMethodManager != null;
1784
1785                 // Display the keyboard.  `0` sets no input flags.
1786                 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1787             }, 200);
1788
1789             // Consume the event.
1790             return true;
1791         } else if (menuItemId == R.id.print) {  // Print.
1792             // Get a print manager instance.
1793             PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1794
1795             // Remove the lint error below that print manager might be null.
1796             assert printManager != null;
1797
1798             // Create a print document adapter from the current WebView.
1799             PrintDocumentAdapter printDocumentAdapter = currentWebView.createPrintDocumentAdapter(getString(R.string.print));
1800
1801             // Print the document.
1802             printManager.print(getString(R.string.privacy_browser_webpage), printDocumentAdapter, null);
1803
1804             // Consume the event.
1805             return true;
1806         } else if (menuItemId == R.id.save_url) {  // Save URL.
1807             // Check the download preference.
1808             if (downloadWithExternalApp) {  // Download with an external app.
1809                 downloadUrlWithExternalApp(currentWebView.getCurrentUrl());
1810             } else {  // Handle the download inside of Privacy Browser.
1811                 // Prepare the save dialog.  The dialog will be displayed once the file size and the content disposition have been acquired.
1812                 new PrepareSaveDialog(this, this, getSupportFragmentManager(), currentWebView.getSettings().getUserAgentString(),
1813                         currentWebView.getAcceptCookies()).execute(currentWebView.getCurrentUrl());
1814             }
1815
1816             // Consume the event.
1817             return true;
1818         } else if (menuItemId == R.id.save_archive) {
1819             // Open the file picker with a default file name built from the current domain name.
1820             saveWebpageArchiveActivityResultLauncher.launch(currentWebView.getCurrentDomainName() + ".mht");
1821
1822             // Consume the event.
1823             return true;
1824         } else if (menuItemId == R.id.save_image) {  // Save image.
1825             // Open the file picker with a default file name built from the current domain name.
1826             saveWebpageImageActivityResultLauncher.launch(currentWebView.getCurrentDomainName() + ".png");
1827
1828             // Consume the event.
1829             return true;
1830         } else if (menuItemId == R.id.add_to_homescreen) {  // Add to homescreen.
1831             // Instantiate the create home screen shortcut dialog.
1832             DialogFragment createHomeScreenShortcutDialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView.getTitle(), currentWebView.getUrl(),
1833                     currentWebView.getFavoriteOrDefaultIcon());
1834
1835             // Show the create home screen shortcut dialog.
1836             createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
1837
1838             // Consume the event.
1839             return true;
1840         } else if (menuItemId == R.id.view_source) {  // View source.
1841             // Create an intent to launch the view source activity.
1842             Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
1843
1844             // Add the variables to the intent.
1845             viewSourceIntent.putExtra(ViewSourceActivityKt.CURRENT_URL, currentWebView.getUrl());
1846             viewSourceIntent.putExtra(ViewSourceActivityKt.USER_AGENT, currentWebView.getSettings().getUserAgentString());
1847
1848             // Make it so.
1849             startActivity(viewSourceIntent);
1850
1851             // Consume the event.
1852             return true;
1853         } else if (menuItemId == R.id.share_message) {  // Share a message.
1854             // Prepare the share string.
1855             String shareString = currentWebView.getTitle() + " – " + currentWebView.getUrl();
1856
1857             // Create the share intent.
1858             Intent shareMessageIntent = new Intent(Intent.ACTION_SEND);
1859
1860             // Add the share string to the intent.
1861             shareMessageIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1862
1863             // Set the MIME type.
1864             shareMessageIntent.setType("text/plain");
1865
1866             // Set the intent to open in a new task.
1867             shareMessageIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1868
1869             // Make it so.
1870             startActivity(Intent.createChooser(shareMessageIntent, getString(R.string.share_message)));
1871
1872             // Consume the event.
1873             return true;
1874         } else if (menuItemId == R.id.share_url) {  // Share URL.
1875             // Create the share intent.
1876             Intent shareUrlIntent = new Intent(Intent.ACTION_SEND);
1877
1878             // Add the URL to the intent.
1879             shareUrlIntent.putExtra(Intent.EXTRA_TEXT, currentWebView.getUrl());
1880
1881             // Add the title to the intent.
1882             shareUrlIntent.putExtra(Intent.EXTRA_SUBJECT, currentWebView.getTitle());
1883
1884             // Set the MIME type.
1885             shareUrlIntent.setType("text/plain");
1886
1887             // Set the intent to open in a new task.
1888             shareUrlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1889
1890             //Make it so.
1891             startActivity(Intent.createChooser(shareUrlIntent, getString(R.string.share_url)));
1892
1893             // Consume the event.
1894             return true;
1895         } else if (menuItemId == R.id.open_with_app) {  // Open with app.
1896             // Open the URL with an outside app.
1897             openWithApp(currentWebView.getUrl());
1898
1899             // Consume the event.
1900             return true;
1901         } else if (menuItemId == R.id.open_with_browser) {  // Open with browser.
1902             // Open the URL with an outside browser.
1903             openWithBrowser(currentWebView.getUrl());
1904
1905             // Consume the event.
1906             return true;
1907         } else if (menuItemId == R.id.add_or_edit_domain) {  // Add or edit domain.
1908             // Check if domain settings currently exist.
1909             if (currentWebView.getDomainSettingsApplied()) {  // Edit the current domain settings.
1910                 // Reapply the domain settings on returning to `MainWebViewActivity`.
1911                 reapplyDomainSettingsOnRestart = true;
1912
1913                 // Create an intent to launch the domains activity.
1914                 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1915
1916                 // Add the extra information to the intent.
1917                 domainsIntent.putExtra("load_domain", currentWebView.getDomainSettingsDatabaseId());
1918                 domainsIntent.putExtra("close_on_back", true);
1919                 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1920                 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1921
1922                 // Get the current certificate.
1923                 SslCertificate sslCertificate = currentWebView.getCertificate();
1924
1925                 // Check to see if the SSL certificate is populated.
1926                 if (sslCertificate != null) {
1927                     // Extract the certificate to strings.
1928                     String issuedToCName = sslCertificate.getIssuedTo().getCName();
1929                     String issuedToOName = sslCertificate.getIssuedTo().getOName();
1930                     String issuedToUName = sslCertificate.getIssuedTo().getUName();
1931                     String issuedByCName = sslCertificate.getIssuedBy().getCName();
1932                     String issuedByOName = sslCertificate.getIssuedBy().getOName();
1933                     String issuedByUName = sslCertificate.getIssuedBy().getUName();
1934                     long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1935                     long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1936
1937                     // Add the certificate to the intent.
1938                     domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1939                     domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1940                     domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1941                     domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1942                     domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1943                     domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1944                     domainsIntent.putExtra("ssl_start_date", startDateLong);
1945                     domainsIntent.putExtra("ssl_end_date", endDateLong);
1946                 }
1947
1948                 // Make it so.
1949                 startActivity(domainsIntent);
1950             } else {  // Add a new domain.
1951                 // Apply the new domain settings on returning to `MainWebViewActivity`.
1952                 reapplyDomainSettingsOnRestart = true;
1953
1954                 // Get the current domain
1955                 Uri currentUri = Uri.parse(currentWebView.getUrl());
1956                 String currentDomain = currentUri.getHost();
1957
1958                 // Create the domain and store the database ID.
1959                 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1960
1961                 // Create an intent to launch the domains activity.
1962                 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1963
1964                 // Add the extra information to the intent.
1965                 domainsIntent.putExtra("load_domain", newDomainDatabaseId);
1966                 domainsIntent.putExtra("close_on_back", true);
1967                 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1968                 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1969
1970                 // Get the current certificate.
1971                 SslCertificate sslCertificate = currentWebView.getCertificate();
1972
1973                 // Check to see if the SSL certificate is populated.
1974                 if (sslCertificate != null) {
1975                     // Extract the certificate to strings.
1976                     String issuedToCName = sslCertificate.getIssuedTo().getCName();
1977                     String issuedToOName = sslCertificate.getIssuedTo().getOName();
1978                     String issuedToUName = sslCertificate.getIssuedTo().getUName();
1979                     String issuedByCName = sslCertificate.getIssuedBy().getCName();
1980                     String issuedByOName = sslCertificate.getIssuedBy().getOName();
1981                     String issuedByUName = sslCertificate.getIssuedBy().getUName();
1982                     long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1983                     long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1984
1985                     // Add the certificate to the intent.
1986                     domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1987                     domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1988                     domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1989                     domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1990                     domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1991                     domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1992                     domainsIntent.putExtra("ssl_start_date", startDateLong);
1993                     domainsIntent.putExtra("ssl_end_date", endDateLong);
1994                 }
1995
1996                 // Make it so.
1997                 startActivity(domainsIntent);
1998             }
1999
2000             // Consume the event.
2001             return true;
2002         } else {  // There is no match with the options menu.  Pass the event up to the parent method.
2003             // Don't consume the event.
2004             return super.onOptionsItemSelected(menuItem);
2005         }
2006     }
2007
2008     // removeAllCookies is deprecated, but it is required for API < 21.
2009     @Override
2010     public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2011         // Get a handle for the shared preferences.
2012         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2013
2014         // Get the menu item ID.
2015         int menuItemId = menuItem.getItemId();
2016
2017         // Run the commands that correspond to the selected menu item.
2018         if (menuItemId == R.id.clear_and_exit) {  // Clear and exit.
2019             // Clear and exit Privacy Browser.
2020             clearAndExit();
2021         } else if (menuItemId == R.id.home) {  // Home.
2022             // Load the homepage.
2023             loadUrl(currentWebView, sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
2024         } else if (menuItemId == R.id.back) {  // Back.
2025             // Check if the WebView can go back.
2026             if (currentWebView.canGoBack()) {
2027                 // Get the current web back forward list.
2028                 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
2029
2030                 // Get the previous entry URL.
2031                 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
2032
2033                 // Apply the domain settings.
2034                 applyDomainSettings(currentWebView, previousUrl, false, false, false);
2035
2036                 // Load the previous website in the history.
2037                 currentWebView.goBack();
2038             }
2039         } else if (menuItemId == R.id.forward) {  // Forward.
2040             // Check if the WebView can go forward.
2041             if (currentWebView.canGoForward()) {
2042                 // Get the current web back forward list.
2043                 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
2044
2045                 // Get the next entry URL.
2046                 String nextUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() + 1).getUrl();
2047
2048                 // Apply the domain settings.
2049                 applyDomainSettings(currentWebView, nextUrl, false, false, false);
2050
2051                 // Load the next website in the history.
2052                 currentWebView.goForward();
2053             }
2054         } else if (menuItemId == R.id.history) {  // History.
2055             // Instantiate the URL history dialog.
2056             DialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView.getWebViewFragmentId());
2057
2058             // Show the URL history dialog.
2059             urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2060         } else if (menuItemId == R.id.open) {  // Open.
2061             // Instantiate the open file dialog.
2062             DialogFragment openDialogFragment = new OpenDialog();
2063
2064             // Show the open file dialog.
2065             openDialogFragment.show(getSupportFragmentManager(), getString(R.string.open));
2066         } else if (menuItemId == R.id.requests) {  // Requests.
2067             // Populate the resource requests.
2068             RequestsActivity.resourceRequests = currentWebView.getResourceRequests();
2069
2070             // Create an intent to launch the Requests activity.
2071             Intent requestsIntent = new Intent(this, RequestsActivity.class);
2072
2073             // Add the block third-party requests status to the intent.
2074             requestsIntent.putExtra("block_all_third_party_requests", currentWebView.getBlockAllThirdPartyRequests());
2075
2076             // Make it so.
2077             startActivity(requestsIntent);
2078         } else if (menuItemId == R.id.downloads) {  // Downloads.
2079             // Try the default system download manager.
2080             try {
2081                 // Launch the default system Download Manager.
2082                 Intent defaultDownloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2083
2084                 // Launch as a new task so that the download manager and Privacy Browser show as separate windows in the recent tasks list.
2085                 defaultDownloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2086
2087                 // Make it so.
2088                 startActivity(defaultDownloadManagerIntent);
2089             } catch (Exception defaultDownloadManagerException) {
2090                 // Try a generic file manager.
2091                 try {
2092                     // Create a generic file manager intent.
2093                     Intent genericFileManagerIntent = new Intent(Intent.ACTION_VIEW);
2094
2095                     // Open the download directory.
2096                     genericFileManagerIntent.setDataAndType(Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()), DocumentsContract.Document.MIME_TYPE_DIR);
2097
2098                     // Launch as a new task so that the file manager and Privacy Browser show as separate windows in the recent tasks list.
2099                     genericFileManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2100
2101                     // Make it so.
2102                     startActivity(genericFileManagerIntent);
2103                 } catch (Exception genericFileManagerException) {
2104                     // Try an alternate file manager.
2105                     try {
2106                         // Create an alternate file manager intent.
2107                         Intent alternateFileManagerIntent = new Intent(Intent.ACTION_VIEW);
2108
2109                         // Open the download directory.
2110                         alternateFileManagerIntent.setDataAndType(Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()), "resource/folder");
2111
2112                         // Launch as a new task so that the file manager and Privacy Browser show as separate windows in the recent tasks list.
2113                         alternateFileManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2114
2115                         // Open the alternate file manager.
2116                         startActivity(alternateFileManagerIntent);
2117                     } catch (Exception alternateFileManagerException) {
2118                         // Display a snackbar.
2119                         Snackbar.make(currentWebView, R.string.no_file_manager_detected, Snackbar.LENGTH_INDEFINITE).show();
2120                     }
2121                 }
2122             }
2123         } else if (menuItemId == R.id.domains) {  // Domains.
2124             // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2125             reapplyDomainSettingsOnRestart = true;
2126
2127             // Launch the domains activity.
2128             Intent domainsIntent = new Intent(this, DomainsActivity.class);
2129
2130             // Add the extra information to the intent.
2131             domainsIntent.putExtra("current_url", currentWebView.getUrl());
2132             domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
2133
2134             // Get the current certificate.
2135             SslCertificate sslCertificate = currentWebView.getCertificate();
2136
2137             // Check to see if the SSL certificate is populated.
2138             if (sslCertificate != null) {
2139                 // Extract the certificate to strings.
2140                 String issuedToCName = sslCertificate.getIssuedTo().getCName();
2141                 String issuedToOName = sslCertificate.getIssuedTo().getOName();
2142                 String issuedToUName = sslCertificate.getIssuedTo().getUName();
2143                 String issuedByCName = sslCertificate.getIssuedBy().getCName();
2144                 String issuedByOName = sslCertificate.getIssuedBy().getOName();
2145                 String issuedByUName = sslCertificate.getIssuedBy().getUName();
2146                 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
2147                 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
2148
2149                 // Add the certificate to the intent.
2150                 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
2151                 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
2152                 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
2153                 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
2154                 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
2155                 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
2156                 domainsIntent.putExtra("ssl_start_date", startDateLong);
2157                 domainsIntent.putExtra("ssl_end_date", endDateLong);
2158             }
2159
2160             // Make it so.
2161             startActivity(domainsIntent);
2162         } else if (menuItemId == R.id.settings) {  // Settings.
2163             // Set the flag to reapply app settings on restart when returning from Settings.
2164             reapplyAppSettingsOnRestart = true;
2165
2166             // Set the flag to reapply the domain settings on restart when returning from Settings.
2167             reapplyDomainSettingsOnRestart = true;
2168
2169             // Launch the settings activity.
2170             Intent settingsIntent = new Intent(this, SettingsActivity.class);
2171             startActivity(settingsIntent);
2172         } else if (menuItemId == R.id.import_export) { // Import/Export.
2173             // Create an intent to launch the import/export activity.
2174             Intent importExportIntent = new Intent(this, ImportExportActivity.class);
2175
2176             // Make it so.
2177             startActivity(importExportIntent);
2178         } else if (menuItemId == R.id.logcat) {  // Logcat.
2179             // Create an intent to launch the logcat activity.
2180             Intent logcatIntent = new Intent(this, LogcatActivity.class);
2181
2182             // Make it so.
2183             startActivity(logcatIntent);
2184         } else if (menuItemId == R.id.guide) {  // Guide.
2185             // Create an intent to launch the guide activity.
2186             Intent guideIntent = new Intent(this, GuideActivity.class);
2187
2188             // Make it so.
2189             startActivity(guideIntent);
2190         } else if (menuItemId == R.id.about) {  // About
2191             // Create an intent to launch the about activity.
2192             Intent aboutIntent = new Intent(this, AboutActivity.class);
2193
2194             // Create a string array for the blocklist versions.
2195             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],
2196                     ultraList.get(0).get(0)[0], ultraPrivacy.get(0).get(0)[0]};
2197
2198             // Add the blocklist versions to the intent.
2199             aboutIntent.putExtra(AboutActivity.BLOCKLIST_VERSIONS, blocklistVersions);
2200
2201             // Make it so.
2202             startActivity(aboutIntent);
2203         }
2204
2205         // Close the navigation drawer.
2206         drawerLayout.closeDrawer(GravityCompat.START);
2207         return true;
2208     }
2209
2210     @Override
2211     public void onPostCreate(Bundle savedInstanceState) {
2212         // Run the default commands.
2213         super.onPostCreate(savedInstanceState);
2214
2215         // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished.  This creates the navigation drawer icon.
2216         actionBarDrawerToggle.syncState();
2217     }
2218
2219     @Override
2220     public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2221         // Get the hit test result.
2222         final WebView.HitTestResult hitTestResult = currentWebView.getHitTestResult();
2223
2224         // Define the URL strings.
2225         final String imageUrl;
2226         final String linkUrl;
2227
2228         // Get handles for the system managers.
2229         final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2230
2231         // Remove the lint errors below that the clipboard manager might be null.
2232         assert clipboardManager != null;
2233
2234         // Process the link according to the type.
2235         switch (hitTestResult.getType()) {
2236             // `SRC_ANCHOR_TYPE` is a link.
2237             case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2238                 // Get the target URL.
2239                 linkUrl = hitTestResult.getExtra();
2240
2241                 // Set the target URL as the title of the `ContextMenu`.
2242                 menu.setHeaderTitle(linkUrl);
2243
2244                 // Add an Open in New Tab entry.
2245                 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2246                     // Load the link URL in a new tab and move to it.
2247                     addNewTab(linkUrl, true);
2248
2249                     // Consume the event.
2250                     return true;
2251                 });
2252
2253                 // Add an Open in Background entry.
2254                 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2255                     // Load the link URL in a new tab but do not move to it.
2256                     addNewTab(linkUrl, false);
2257
2258                     // Consume the event.
2259                     return true;
2260                 });
2261
2262                 // Add an Open with App entry.
2263                 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2264                     openWithApp(linkUrl);
2265
2266                     // Consume the event.
2267                     return true;
2268                 });
2269
2270                 // Add an Open with Browser entry.
2271                 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2272                     openWithBrowser(linkUrl);
2273
2274                     // Consume the event.
2275                     return true;
2276                 });
2277
2278                 // Add a Copy URL entry.
2279                 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2280                     // Save the link URL in a `ClipData`.
2281                     ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2282
2283                     // Set the `ClipData` as the clipboard's primary clip.
2284                     clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2285
2286                     // Consume the event.
2287                     return true;
2288                 });
2289
2290                 // Add a Save URL entry.
2291                 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2292                     // Check the download preference.
2293                     if (downloadWithExternalApp) {  // Download with an external app.
2294                         downloadUrlWithExternalApp(linkUrl);
2295                     } else {  // Handle the download inside of Privacy Browser.
2296                         // Prepare the save dialog.  The dialog will be displayed once the file size and the content disposition have been acquired.
2297                         new PrepareSaveDialog(this, this, getSupportFragmentManager(), currentWebView.getSettings().getUserAgentString(),
2298                                 currentWebView.getAcceptCookies()).execute(linkUrl);
2299                     }
2300
2301                     // Consume the event.
2302                     return true;
2303                 });
2304
2305                 // Add an empty Cancel entry, which by default closes the context menu.
2306                 menu.add(R.string.cancel);
2307                 break;
2308
2309             // `IMAGE_TYPE` is an image.
2310             case WebView.HitTestResult.IMAGE_TYPE:
2311                 // Get the image URL.
2312                 imageUrl = hitTestResult.getExtra();
2313
2314                 // Remove the incorrect lint warning below that the image URL might be null.
2315                 assert imageUrl != null;
2316
2317                 // Set the context menu title.
2318                 if (imageUrl.startsWith("data:")) {  // The image data is contained in within the URL, making it exceedingly long.
2319                     // Truncate the image URL before making it the title.
2320                     menu.setHeaderTitle(imageUrl.substring(0, 100));
2321                 } else {  // The image URL does not contain the full image data.
2322                     // Set the image URL as the title of the context menu.
2323                     menu.setHeaderTitle(imageUrl);
2324                 }
2325
2326                 // Add an Open in New Tab entry.
2327                 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2328                     // Load the image in a new tab.
2329                     addNewTab(imageUrl, true);
2330
2331                     // Consume the event.
2332                     return true;
2333                 });
2334
2335                 // Add an Open with App entry.
2336                 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2337                     // Open the image URL with an external app.
2338                     openWithApp(imageUrl);
2339
2340                     // Consume the event.
2341                     return true;
2342                 });
2343
2344                 // Add an Open with Browser entry.
2345                 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2346                     // Open the image URL with an external browser.
2347                     openWithBrowser(imageUrl);
2348
2349                     // Consume the event.
2350                     return true;
2351                 });
2352
2353                 // Add a View Image entry.
2354                 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2355                     // Load the image in the current tab.
2356                     loadUrl(currentWebView, imageUrl);
2357
2358                     // Consume the event.
2359                     return true;
2360                 });
2361
2362                 // Add a Save Image entry.
2363                 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2364                     // Check the download preference.
2365                     if (downloadWithExternalApp) {  // Download with an external app.
2366                         downloadUrlWithExternalApp(imageUrl);
2367                     } else {  // Handle the download inside of Privacy Browser.
2368                         // Prepare the save dialog.  The dialog will be displayed once the file size and the content disposition have been acquired.
2369                         new PrepareSaveDialog(this, this, getSupportFragmentManager(), currentWebView.getSettings().getUserAgentString(),
2370                                 currentWebView.getAcceptCookies()).execute(imageUrl);
2371                     }
2372
2373                     // Consume the event.
2374                     return true;
2375                 });
2376
2377                 // Add a Copy URL entry.
2378                 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2379                     // Save the image URL in a clip data.
2380                     ClipData imageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2381
2382                     // Set the clip data as the clipboard's primary clip.
2383                     clipboardManager.setPrimaryClip(imageTypeClipData);
2384
2385                     // Consume the event.
2386                     return true;
2387                 });
2388
2389                 // Add an empty Cancel entry, which by default closes the context menu.
2390                 menu.add(R.string.cancel);
2391                 break;
2392
2393             // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2394             case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2395                 // Get the image URL.
2396                 imageUrl = hitTestResult.getExtra();
2397
2398                 // Instantiate a handler.
2399                 Handler handler = new Handler();
2400
2401                 // Get a message from the handler.
2402                 Message message = handler.obtainMessage();
2403
2404                 // Request the image details from the last touched node be returned in the message.
2405                 currentWebView.requestFocusNodeHref(message);
2406
2407                 // Get the link URL from the message data.
2408                 linkUrl = message.getData().getString("url");
2409
2410                 // Set the link URL as the title of the context menu.
2411                 menu.setHeaderTitle(linkUrl);
2412
2413                 // Add an Open in New Tab entry.
2414                 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2415                     // Load the link URL in a new tab and move to it.
2416                     addNewTab(linkUrl, true);
2417
2418                     // Consume the event.
2419                     return true;
2420                 });
2421
2422                 // Add an Open in Background entry.
2423                 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2424                     // Lod the link URL in a new tab but do not move to it.
2425                     addNewTab(linkUrl, false);
2426
2427                     // Consume the event.
2428                     return true;
2429                 });
2430
2431                 // Add an Open Image in New Tab entry.
2432                 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2433                     // Load the image in a new tab and move to it.
2434                     addNewTab(imageUrl, true);
2435
2436                     // Consume the event.
2437                     return true;
2438                 });
2439
2440                 // Add an Open with App entry.
2441                 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2442                     // Open the link URL with an external app.
2443                     openWithApp(linkUrl);
2444
2445                     // Consume the event.
2446                     return true;
2447                 });
2448
2449                 // Add an Open with Browser entry.
2450                 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2451                     // Open the link URL with an external browser.
2452                     openWithBrowser(linkUrl);
2453
2454                     // Consume the event.
2455                     return true;
2456                 });
2457
2458                 // Add a View Image entry.
2459                 menu.add(R.string.view_image).setOnMenuItemClickListener((MenuItem item) -> {
2460                    // View the image in the current tab.
2461                    loadUrl(currentWebView, imageUrl);
2462
2463                    // Consume the event.
2464                    return true;
2465                 });
2466
2467                 // Add a Save Image entry.
2468                 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2469                     // Check the download preference.
2470                     if (downloadWithExternalApp) {  // Download with an external app.
2471                         downloadUrlWithExternalApp(imageUrl);
2472                     } else {  // Handle the download inside of Privacy Browser.
2473                         // Prepare the save dialog.  The dialog will be displayed once the file size and the content disposition have been acquired.
2474                         new PrepareSaveDialog(this, this, getSupportFragmentManager(), currentWebView.getSettings().getUserAgentString(),
2475                                 currentWebView.getAcceptCookies()).execute(imageUrl);
2476                     }
2477
2478                     // Consume the event.
2479                     return true;
2480                 });
2481
2482                 // Add a Copy URL entry.
2483                 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2484                     // Save the link URL in a clip data.
2485                     ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2486
2487                     // Set the clip data as the clipboard's primary clip.
2488                     clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2489
2490                     // Consume the event.
2491                     return true;
2492                 });
2493
2494                 // Add a Save URL entry.
2495                 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2496                     // Check the download preference.
2497                     if (downloadWithExternalApp) {  // Download with an external app.
2498                         downloadUrlWithExternalApp(linkUrl);
2499                     } else {  // Handle the download inside of Privacy Browser.
2500                         // Prepare the save dialog.  The dialog will be displayed once the file size and the content disposition have been acquired.
2501                         new PrepareSaveDialog(this, this, getSupportFragmentManager(), currentWebView.getSettings().getUserAgentString(),
2502                                 currentWebView.getAcceptCookies()).execute(linkUrl);
2503                     }
2504
2505                     // Consume the event.
2506                     return true;
2507                 });
2508
2509                 // Add an empty Cancel entry, which by default closes the context menu.
2510                 menu.add(R.string.cancel);
2511                 break;
2512
2513             case WebView.HitTestResult.EMAIL_TYPE:
2514                 // Get the target URL.
2515                 linkUrl = hitTestResult.getExtra();
2516
2517                 // Set the target URL as the title of the `ContextMenu`.
2518                 menu.setHeaderTitle(linkUrl);
2519
2520                 // Add a Write Email entry.
2521                 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2522                     // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2523                     Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2524
2525                     // Parse the url and set it as the data for the `Intent`.
2526                     emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2527
2528                     // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2529                     emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2530
2531                     try {
2532                         // Make it so.
2533                         startActivity(emailIntent);
2534                     } catch (ActivityNotFoundException exception) {
2535                         // Display a snackbar.
2536                         Snackbar.make(currentWebView, getString(R.string.error) + "  " + exception, Snackbar.LENGTH_INDEFINITE).show();
2537                     }
2538
2539                     // Consume the event.
2540                     return true;
2541                 });
2542
2543                 // Add a Copy Email Address entry.
2544                 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2545                     // Save the email address in a `ClipData`.
2546                     ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2547
2548                     // Set the `ClipData` as the clipboard's primary clip.
2549                     clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2550
2551                     // Consume the event.
2552                     return true;
2553                 });
2554
2555                 // Add an empty Cancel entry, which by default closes the context menu.
2556                 menu.add(R.string.cancel);
2557                 break;
2558         }
2559     }
2560
2561     @Override
2562     public void onCreateBookmark(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2563         // Get a handle for the bookmarks list view.
2564         ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2565
2566         // Get the dialog.
2567         Dialog dialog = dialogFragment.getDialog();
2568
2569         // Remove the incorrect lint warning below that the dialog might be null.
2570         assert dialog != null;
2571
2572         // Get the views from the dialog fragment.
2573         EditText createBookmarkNameEditText = dialog.findViewById(R.id.create_bookmark_name_edittext);
2574         EditText createBookmarkUrlEditText = dialog.findViewById(R.id.create_bookmark_url_edittext);
2575
2576         // Extract the strings from the edit texts.
2577         String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2578         String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2579
2580         // Create a favorite icon byte array output stream.
2581         ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2582
2583         // Convert the favorite icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
2584         favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2585
2586         // Convert the favorite icon byte array stream to a byte array.
2587         byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2588
2589         // Display the new bookmark below the current items in the (0 indexed) list.
2590         int newBookmarkDisplayOrder = bookmarksListView.getCount();
2591
2592         // Create the bookmark.
2593         bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2594
2595         // Update the bookmarks cursor with the current contents of this folder.
2596         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2597
2598         // Update the list view.
2599         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2600
2601         // Scroll to the new bookmark.
2602         bookmarksListView.setSelection(newBookmarkDisplayOrder);
2603     }
2604
2605     @Override
2606     public void onCreateBookmarkFolder(DialogFragment dialogFragment, @NonNull Bitmap favoriteIconBitmap) {
2607         // Get a handle for the bookmarks list view.
2608         ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2609
2610         // Get the dialog.
2611         Dialog dialog = dialogFragment.getDialog();
2612
2613         // Remove the incorrect lint warning below that the dialog might be null.
2614         assert dialog != null;
2615
2616         // Get handles for the views in the dialog fragment.
2617         EditText folderNameEditText = dialog.findViewById(R.id.folder_name_edittext);
2618         RadioButton defaultIconRadioButton = dialog.findViewById(R.id.default_icon_radiobutton);
2619         ImageView defaultIconImageView = dialog.findViewById(R.id.default_icon_imageview);
2620
2621         // Get new folder name string.
2622         String folderNameString = folderNameEditText.getText().toString();
2623
2624         // Create a folder icon bitmap.
2625         Bitmap folderIconBitmap;
2626
2627         // Set the folder icon bitmap according to the dialog.
2628         if (defaultIconRadioButton.isChecked()) {  // Use the default folder icon.
2629             // Get the default folder icon drawable.
2630             Drawable folderIconDrawable = defaultIconImageView.getDrawable();
2631
2632             // Convert the folder icon drawable to a bitmap drawable.
2633             BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2634
2635             // Convert the folder icon bitmap drawable to a bitmap.
2636             folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2637         } else {  // Use the WebView favorite icon.
2638             // Copy the favorite icon bitmap to the folder icon bitmap.
2639             folderIconBitmap = favoriteIconBitmap;
2640         }
2641
2642         // Create a folder icon byte array output stream.
2643         ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2644
2645         // Convert the folder icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
2646         folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2647
2648         // Convert the folder icon byte array stream to a byte array.
2649         byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2650
2651         // Move all the bookmarks down one in the display order.
2652         for (int i = 0; i < bookmarksListView.getCount(); i++) {
2653             int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2654             bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2655         }
2656
2657         // Create the folder, which will be placed at the top of the `ListView`.
2658         bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2659
2660         // Update the bookmarks cursor with the current contents of this folder.
2661         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2662
2663         // Update the `ListView`.
2664         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2665
2666         // Scroll to the new folder.
2667         bookmarksListView.setSelection(0);
2668     }
2669
2670     @Override
2671     public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, @NonNull Bitmap favoriteIconBitmap) {
2672         // Remove the incorrect lint warning below that the dialog fragment might be null.
2673         assert dialogFragment != null;
2674
2675         // Get the dialog.
2676         Dialog dialog = dialogFragment.getDialog();
2677
2678         // Remove the incorrect lint warning below that the dialog might be null.
2679         assert dialog != null;
2680
2681         // Get handles for the views from the dialog.
2682         RadioButton currentFolderIconRadioButton = dialog.findViewById(R.id.current_icon_radiobutton);
2683         RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.default_icon_radiobutton);
2684         ImageView defaultFolderIconImageView = dialog.findViewById(R.id.default_icon_imageview);
2685         EditText editFolderNameEditText = dialog.findViewById(R.id.folder_name_edittext);
2686
2687         // Get the new folder name.
2688         String newFolderNameString = editFolderNameEditText.getText().toString();
2689
2690         // Check if the favorite icon has changed.
2691         if (currentFolderIconRadioButton.isChecked()) {  // Only the name has changed.
2692             // Update the name in the database.
2693             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2694         } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) {  // Only the icon has changed.
2695             // Create the new folder icon Bitmap.
2696             Bitmap folderIconBitmap;
2697
2698             // Populate the new folder icon bitmap.
2699             if (defaultFolderIconRadioButton.isChecked()) {
2700                 // Get the default folder icon drawable.
2701                 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2702
2703                 // Convert the folder icon drawable to a bitmap drawable.
2704                 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2705
2706                 // Convert the folder icon bitmap drawable to a bitmap.
2707                 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2708             } else {  // Use the `WebView` favorite icon.
2709                 // Copy the favorite icon bitmap to the folder icon bitmap.
2710                 folderIconBitmap = favoriteIconBitmap;
2711             }
2712
2713             // Create a folder icon byte array output stream.
2714             ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2715
2716             // Convert the folder icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
2717             folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2718
2719             // Convert the folder icon byte array stream to a byte array.
2720             byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2721
2722             // Update the folder icon in the database.
2723             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, newFolderIconByteArray);
2724         } else {  // The folder icon and the name have changed.
2725             // Get the new folder icon bitmap.
2726             Bitmap folderIconBitmap;
2727             if (defaultFolderIconRadioButton.isChecked()) {
2728                 // Get the default folder icon drawable.
2729                 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2730
2731                 // Convert the folder icon drawable to a bitmap drawable.
2732                 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2733
2734                 // Convert the folder icon bitmap drawable to a bitmap.
2735                 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2736             } else {  // Use the `WebView` favorite icon.
2737                 // Copy the favorite icon bitmap to the folder icon bitmap.
2738                 folderIconBitmap = favoriteIconBitmap;
2739             }
2740
2741             // Create a folder icon byte array output stream.
2742             ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2743
2744             // Convert the folder icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
2745             folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2746
2747             // Convert the folder icon byte array stream to a byte array.
2748             byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2749
2750             // Update the folder name and icon in the database.
2751             bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, newFolderIconByteArray);
2752         }
2753
2754         // Update the bookmarks cursor with the current contents of this folder.
2755         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2756
2757         // Update the `ListView`.
2758         bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2759     }
2760
2761     // Override `onBackPressed()` to handle the navigation drawer and and the WebViews.
2762     @Override
2763     public void onBackPressed() {
2764         // Check the different options for processing `back`.
2765         if (drawerLayout.isDrawerVisible(GravityCompat.START)) {  // The navigation drawer is open.
2766             // Close the navigation drawer.
2767             drawerLayout.closeDrawer(GravityCompat.START);
2768         } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){  // The bookmarks drawer is open.
2769             // close the bookmarks drawer.
2770             drawerLayout.closeDrawer(GravityCompat.END);
2771         } else if (displayingFullScreenVideo) {  // A full screen video is shown.
2772             // Exit the full screen video.
2773             exitFullScreenVideo();
2774         } else if (currentWebView.canGoBack()) {  // There is at least one item in the current WebView history.
2775             // Get the current web back forward list.
2776             WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
2777
2778             // Get the previous entry URL.
2779             String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
2780
2781             // Apply the domain settings.
2782             applyDomainSettings(currentWebView, previousUrl, false, false, false);
2783
2784             // Go back.
2785             currentWebView.goBack();
2786         } else if (tabLayout.getTabCount() > 1) {  // There are at least two tabs.
2787             // Close the current tab.
2788             closeCurrentTab();
2789         } else {  // There isn't anything to do in Privacy Browser.
2790             // Close Privacy Browser.  `finishAndRemoveTask()` also removes Privacy Browser from the recent app list.
2791             finishAndRemoveTask();
2792
2793             // Manually kill Privacy Browser.  Otherwise, it is glitchy when restarted.
2794             System.exit(0);
2795         }
2796     }
2797
2798     // Process the results of a file browse.
2799     @Override
2800     public void onActivityResult(int requestCode, int resultCode, Intent returnedIntent) {
2801         // Run the default commands.
2802         super.onActivityResult(requestCode, resultCode, returnedIntent);
2803
2804         // Run the commands that correlate to the specified request code.
2805         switch (requestCode) {
2806             case BROWSE_FILE_UPLOAD_REQUEST_CODE:
2807                 // Pass the file to the WebView.
2808                 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, returnedIntent));
2809                 break;
2810
2811             case BROWSE_OPEN_REQUEST_CODE:
2812                 // Don't do anything if the user pressed back from the file picker.
2813                 if (resultCode == Activity.RESULT_OK) {
2814                     // Get a handle for the open dialog fragment.
2815                     DialogFragment openDialogFragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.open));
2816
2817                     // Only update the file name if the dialog still exists.
2818                     if (openDialogFragment != null) {
2819                         // Get a handle for the open dialog.
2820                         Dialog openDialog = openDialogFragment.getDialog();
2821
2822                         // Remove the incorrect lint warning below that the dialog might be null.
2823                         assert openDialog != null;
2824
2825                         // Get a handle for the file name edit text.
2826                         EditText fileNameEditText = openDialog.findViewById(R.id.file_name_edittext);
2827
2828                         // Get the file name URI from the intent.
2829                         Uri fileNameUri = returnedIntent.getData();
2830
2831                         // Get the file name string from the URI.
2832                         String fileNameString = fileNameUri.toString();
2833
2834                         // Set the file name text.
2835                         fileNameEditText.setText(fileNameString);
2836
2837                         // Move the cursor to the end of the file name edit text.
2838                         fileNameEditText.setSelection(fileNameString.length());
2839                     }
2840                 }
2841                 break;
2842         }
2843     }
2844
2845     private void loadUrlFromTextBox() {
2846         // Get the text from urlTextBox and convert it to a string.  trim() removes white spaces from the beginning and end of the string.
2847         String unformattedUrlString = urlEditText.getText().toString().trim();
2848
2849         // Initialize the formatted URL string.
2850         String url = "";
2851
2852         // Check to see if the unformatted URL string is a valid URL.  Otherwise, convert it into a search.
2853         if (unformattedUrlString.startsWith("content://")) {  // This is a Content URL.
2854             // Load the entire content URL.
2855             url = unformattedUrlString;
2856         } else if (Patterns.WEB_URL.matcher(unformattedUrlString).matches() || unformattedUrlString.startsWith("http://") || unformattedUrlString.startsWith("https://") ||
2857                 unformattedUrlString.startsWith("file://")) {  // This is a standard URL.
2858             // Add `https://` at the beginning if there is no protocol.  Otherwise the app will segfault.
2859             if (!unformattedUrlString.startsWith("http") && !unformattedUrlString.startsWith("file://")) {
2860                 unformattedUrlString = "https://" + unformattedUrlString;
2861             }
2862
2863             // Initialize the unformatted URL.
2864             URL unformattedUrl = null;
2865
2866             // Convert the unformatted URL string to a URL, then to a URI, and then back to a string, which sanitizes the input and adds in any missing components.
2867             try {
2868                 unformattedUrl = new URL(unformattedUrlString);
2869             } catch (MalformedURLException e) {
2870                 e.printStackTrace();
2871             }
2872
2873             // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2874             String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2875             String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2876             String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2877             String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2878             String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2879
2880             // Build the URI.
2881             Uri.Builder uri = new Uri.Builder();
2882             uri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2883
2884             // Decode the URI as a UTF-8 string in.
2885             try {
2886                 url = URLDecoder.decode(uri.build().toString(), "UTF-8");
2887             } catch (UnsupportedEncodingException exception) {
2888                 // Do nothing.  The formatted URL string will remain blank.
2889             }
2890         } else if (!unformattedUrlString.isEmpty()){  // This is not a URL, but rather a search string.
2891             // Create an encoded URL String.
2892             String encodedUrlString;
2893
2894             // Sanitize the search input.
2895             try {
2896                 encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2897             } catch (UnsupportedEncodingException exception) {
2898                 encodedUrlString = "";
2899             }
2900
2901             // Add the base search URL.
2902             url = searchURL + encodedUrlString;
2903         }
2904
2905         // Clear the focus from the URL edit text.  Otherwise, proximate typing in the box will retain the colorized formatting instead of being reset during refocus.
2906         urlEditText.clearFocus();
2907
2908         // Make it so.
2909         loadUrl(currentWebView, url);
2910     }
2911
2912     private void loadUrl(NestedScrollWebView nestedScrollWebView, String url) {
2913         // Sanitize the URL.
2914         url = sanitizeUrl(url);
2915
2916         // Apply the domain settings and load the URL.
2917         applyDomainSettings(nestedScrollWebView, url, true, false, true);
2918     }
2919
2920     public void findPreviousOnPage(View view) {
2921         // Go to the previous highlighted phrase on the page.  `false` goes backwards instead of forwards.
2922         currentWebView.findNext(false);
2923     }
2924
2925     public void findNextOnPage(View view) {
2926         // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2927         currentWebView.findNext(true);
2928     }
2929
2930     public void closeFindOnPage(View view) {
2931         // Get a handle for the views.
2932         Toolbar toolbar = findViewById(R.id.toolbar);
2933         LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
2934         EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
2935
2936         // Delete the contents of `find_on_page_edittext`.
2937         findOnPageEditText.setText(null);
2938
2939         // Clear the highlighted phrases if the WebView is not null.
2940         if (currentWebView != null) {
2941             currentWebView.clearMatches();
2942         }
2943
2944         // Hide the find on page linear layout.
2945         findOnPageLinearLayout.setVisibility(View.GONE);
2946
2947         // Show the toolbar.
2948         toolbar.setVisibility(View.VISIBLE);
2949
2950         // Get a handle for the input method manager.
2951         InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
2952
2953         // Remove the lint warning below that the input method manager might be null.
2954         assert inputMethodManager != null;
2955
2956         // Hide the keyboard.
2957         inputMethodManager.hideSoftInputFromWindow(toolbar.getWindowToken(), 0);
2958     }
2959
2960     @Override
2961     public void onApplyNewFontSize(DialogFragment dialogFragment) {
2962         // Remove the incorrect lint warning below that the dialog fragment might be null.
2963         assert dialogFragment != null;
2964
2965         // Get the dialog.
2966         Dialog dialog = dialogFragment.getDialog();
2967
2968         // Remove the incorrect lint warning below tha the dialog might be null.
2969         assert dialog != null;
2970
2971         // Get a handle for the font size edit text.
2972         EditText fontSizeEditText = dialog.findViewById(R.id.font_size_edittext);
2973
2974         // Initialize the new font size variable with the current font size.
2975         int newFontSize = currentWebView.getSettings().getTextZoom();
2976
2977         // Get the font size from the edit text.
2978         try {
2979             newFontSize = Integer.parseInt(fontSizeEditText.getText().toString());
2980         } catch (Exception exception) {
2981             // If the edit text does not contain a valid font size do nothing.
2982         }
2983
2984         // Apply the new font size.
2985         currentWebView.getSettings().setTextZoom(newFontSize);
2986     }
2987
2988     @Override
2989     public void onOpen(DialogFragment dialogFragment) {
2990         // Get the dialog.
2991         Dialog dialog = dialogFragment.getDialog();
2992
2993         // Remove the incorrect lint warning below that the dialog might be null.
2994         assert dialog != null;
2995
2996         // Get handles for the views.
2997         EditText fileNameEditText = dialog.findViewById(R.id.file_name_edittext);
2998         CheckBox mhtCheckBox = dialog.findViewById(R.id.mht_checkbox);
2999
3000         // Get the file path string.
3001         String openFilePath = fileNameEditText.getText().toString();
3002
3003         // Apply the domain settings.  This resets the favorite icon and removes any domain settings.
3004         applyDomainSettings(currentWebView, openFilePath, true, false, false);
3005
3006         // Open the file according to the type.
3007         if (mhtCheckBox.isChecked()) {  // Force opening of an MHT file.
3008             try {
3009                 // Get the MHT file input stream.
3010                 InputStream mhtFileInputStream = getContentResolver().openInputStream(Uri.parse(openFilePath));
3011
3012                 // Create a temporary MHT file.
3013                 File temporaryMhtFile = File.createTempFile("temporary_mht_file", ".mht", getCacheDir());
3014
3015                 // Get a file output stream for the temporary MHT file.
3016                 FileOutputStream temporaryMhtFileOutputStream = new FileOutputStream(temporaryMhtFile);
3017
3018                 // Create a transfer byte array.
3019                 byte[] transferByteArray = new byte[1024];
3020
3021                 // Create an integer to track the number of bytes read.
3022                 int bytesRead;
3023
3024                 // Copy the temporary MHT file input stream to the MHT output stream.
3025                 while ((bytesRead = mhtFileInputStream.read(transferByteArray)) > 0) {
3026                     temporaryMhtFileOutputStream.write(transferByteArray, 0, bytesRead);
3027                 }
3028
3029                 // Flush the temporary MHT file output stream.
3030                 temporaryMhtFileOutputStream.flush();
3031
3032                 // Close the streams.
3033                 temporaryMhtFileOutputStream.close();
3034                 mhtFileInputStream.close();
3035
3036                 // Load the temporary MHT file.
3037                 currentWebView.loadUrl(temporaryMhtFile.toString());
3038             } catch (Exception exception) {
3039                 // Display a snackbar.
3040                 Snackbar.make(currentWebView, getString(R.string.error) + "  " + exception, Snackbar.LENGTH_INDEFINITE).show();
3041             }
3042         } else {  // Let the WebView handle opening of the file.
3043             // Open the file.
3044             currentWebView.loadUrl(openFilePath);
3045         }
3046     }
3047
3048     private void downloadUrlWithExternalApp(String url) {
3049         // Create a download intent.  Not specifying the action type will display the maximum number of options.
3050         Intent downloadIntent = new Intent();
3051
3052         // Set the URI and the mime type.
3053         downloadIntent.setDataAndType(Uri.parse(url), "text/html");
3054
3055         // Flag the intent to open in a new task.
3056         downloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3057
3058         // Show the chooser.
3059         startActivity(Intent.createChooser(downloadIntent, getString(R.string.download_with_external_app)));
3060     }
3061
3062     public void onSaveUrl(@NonNull String originalUrlString, @NonNull String fileNameString, @NonNull DialogFragment dialogFragment) {
3063         // Store the URL.  This will be used in the save URL activity result launcher.
3064         if (originalUrlString.startsWith("data:")) {
3065             // Save the original URL.
3066             saveUrlString = originalUrlString;
3067         } else {
3068             // Get the dialog.
3069             Dialog dialog = dialogFragment.getDialog();
3070
3071             // Remove the incorrect lint warning below that the dialog might be null.
3072             assert dialog != null;
3073
3074             // Get a handle for the dialog URL edit text.
3075             EditText dialogUrlEditText = dialog.findViewById(R.id.url_edittext);
3076
3077             // Get the URL from the edit text, which may have been modified.
3078             saveUrlString = dialogUrlEditText.getText().toString();
3079         }
3080
3081         // Open the file picker.
3082         saveUrlActivityResultLauncher.launch(fileNameString);
3083     }
3084     
3085     // Remove the warning that `OnTouchListener()` needs to override `performClick()`, as the only purpose of setting the `OnTouchListener()` is to make it do nothing.
3086     @SuppressLint("ClickableViewAccessibility")
3087     private void initializeApp() {
3088         // Get a handle for the input method.
3089         InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
3090
3091         // Remove the lint warning below that the input method manager might be null.
3092         assert inputMethodManager != null;
3093
3094         // Initialize the gray foreground color spans for highlighting the URLs.
3095         initialGrayColorSpan = new ForegroundColorSpan(getColor(R.color.gray_500));
3096         finalGrayColorSpan = new ForegroundColorSpan(getColor(R.color.gray_500));
3097
3098         // Get the current theme status.
3099         int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
3100
3101         // Set the red color span according to the theme.
3102         if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
3103             redColorSpan = new ForegroundColorSpan(getColor(R.color.red_a700));
3104         } else {
3105             redColorSpan = new ForegroundColorSpan(getColor(R.color.red_900));
3106         }
3107
3108         // Remove the formatting from the URL edit text when the user is editing the text.
3109         urlEditText.setOnFocusChangeListener((View v, boolean hasFocus) -> {
3110             if (hasFocus) {  // The user is editing the URL text box.
3111                 // Remove the highlighting.
3112                 urlEditText.getText().removeSpan(redColorSpan);
3113                 urlEditText.getText().removeSpan(initialGrayColorSpan);
3114                 urlEditText.getText().removeSpan(finalGrayColorSpan);
3115             } else {  // The user has stopped editing the URL text box.
3116                 // Move to the beginning of the string.
3117                 urlEditText.setSelection(0);
3118
3119                 // Reapply the highlighting.
3120                 highlightUrlText();
3121             }
3122         });
3123
3124         // Set the go button on the keyboard to load the URL in `urlTextBox`.
3125         urlEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
3126             // If the event is a key-down event on the `enter` button, load the URL.
3127             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
3128                 // Load the URL into the mainWebView and consume the event.
3129                 loadUrlFromTextBox();
3130
3131                 // If the enter key was pressed, consume the event.
3132                 return true;
3133             } else {
3134                 // If any other key was pressed, do not consume the event.
3135                 return false;
3136             }
3137         });
3138
3139         // Create an Orbot status broadcast receiver.
3140         orbotStatusBroadcastReceiver = new BroadcastReceiver() {
3141             @Override
3142             public void onReceive(Context context, Intent intent) {
3143                 // Store the content of the status message in `orbotStatus`.
3144                 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
3145
3146                 // If Privacy Browser is waiting on the proxy, load the website now that Orbot is connected.
3147                 if ((orbotStatus != null) && orbotStatus.equals(ProxyHelper.ORBOT_STATUS_ON) && waitingForProxy) {
3148                     // Reset the waiting for proxy status.
3149                     waitingForProxy = false;
3150
3151                     // Get a list of the current fragments.
3152                     List<Fragment> fragmentList = getSupportFragmentManager().getFragments();
3153
3154                     // Check each fragment to see if it is a waiting for proxy dialog.  Sometimes more than one is displayed.
3155                     for (int i = 0; i < fragmentList.size(); i++) {
3156                         // Get the fragment tag.
3157                         String fragmentTag = fragmentList.get(i).getTag();
3158
3159                         // Check to see if it is the waiting for proxy dialog.
3160                         if ((fragmentTag!= null) && fragmentTag.equals(getString(R.string.waiting_for_proxy_dialog))) {
3161                             // Dismiss the waiting for proxy dialog.
3162                             ((DialogFragment) fragmentList.get(i)).dismiss();
3163                         }
3164                     }
3165
3166                     // Reload existing URLs and load any URLs that are waiting for the proxy.
3167                     for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3168                         // Get the WebView tab fragment.
3169                         WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3170
3171                         // Get the fragment view.
3172                         View fragmentView = webViewTabFragment.getView();
3173
3174                         // Only process the WebViews if they exist.
3175                         if (fragmentView != null) {
3176                             // Get the nested scroll WebView from the tab fragment.
3177                             NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3178
3179                             // Get the waiting for proxy URL string.
3180                             String waitingForProxyUrlString = nestedScrollWebView.getWaitingForProxyUrlString();
3181
3182                             // Load the pending URL if it exists.
3183                             if (!waitingForProxyUrlString.isEmpty()) {  // A URL is waiting to be loaded.
3184                                 // Load the URL.
3185                                 loadUrl(nestedScrollWebView, waitingForProxyUrlString);
3186
3187                                 // Reset the waiting for proxy URL string.
3188                                 nestedScrollWebView.setWaitingForProxyUrlString("");
3189                             } else {  // No URL is waiting to be loaded.
3190                                 // Reload the existing URL.
3191                                 nestedScrollWebView.reload();
3192                             }
3193                         }
3194                     }
3195                 }
3196             }
3197         };
3198
3199         // Register the Orbot status broadcast receiver on `this` context.
3200         this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
3201
3202         // Get handles for views that need to be modified.
3203         LinearLayout bookmarksHeaderLinearLayout = findViewById(R.id.bookmarks_header_linearlayout);
3204         ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
3205         FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
3206         FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
3207         FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
3208         EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
3209
3210         // Update the web view pager every time a tab is modified.
3211         webViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
3212             @Override
3213             public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
3214                 // Do nothing.
3215             }
3216
3217             @Override
3218             public void onPageSelected(int position) {
3219                 // Close the find on page bar if it is open.
3220                 closeFindOnPage(null);
3221
3222                 // Set the current WebView.
3223                 setCurrentWebView(position);
3224
3225                 // Select the corresponding tab if it does not match the currently selected page.  This will happen if the page was scrolled by creating a new tab.
3226                 if (tabLayout.getSelectedTabPosition() != position) {
3227                     // Wait until the new tab has been created.
3228                     tabLayout.post(() -> {
3229                         // Get a handle for the tab.
3230                         TabLayout.Tab tab = tabLayout.getTabAt(position);
3231
3232                         // Assert that the tab is not null.
3233                         assert tab != null;
3234
3235                         // Select the tab.
3236                         tab.select();
3237                     });
3238                 }
3239             }
3240
3241             @Override
3242             public void onPageScrollStateChanged(int state) {
3243                 // Do nothing.
3244             }
3245         });
3246
3247         // Display the View SSL Certificate dialog when the currently selected tab is reselected.
3248         tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
3249             @Override
3250             public void onTabSelected(TabLayout.Tab tab) {
3251                 // Select the same page in the view pager.
3252                 webViewPager.setCurrentItem(tab.getPosition());
3253             }
3254
3255             @Override
3256             public void onTabUnselected(TabLayout.Tab tab) {
3257                 // Do nothing.
3258             }
3259
3260             @Override
3261             public void onTabReselected(TabLayout.Tab tab) {
3262                 // Instantiate the View SSL Certificate dialog.
3263                 DialogFragment viewSslCertificateDialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView.getWebViewFragmentId(), currentWebView.getFavoriteOrDefaultIcon());
3264
3265                 // Display the View SSL Certificate dialog.
3266                 viewSslCertificateDialogFragment.show(getSupportFragmentManager(), getString(R.string.view_ssl_certificate));
3267             }
3268         });
3269
3270         // Set a touch listener on the bookmarks header linear layout so that touches don't pass through to the button underneath.
3271         bookmarksHeaderLinearLayout.setOnTouchListener((view, motionEvent) -> {
3272             // Consume the touch.
3273             return true;
3274         });
3275
3276         // Set the launch bookmarks activity FAB to launch the bookmarks activity.
3277         launchBookmarksActivityFab.setOnClickListener(v -> {
3278             // Get a copy of the favorite icon bitmap.
3279             Bitmap favoriteIconBitmap = currentWebView.getFavoriteOrDefaultIcon();
3280
3281             // Create a favorite icon byte array output stream.
3282             ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3283
3284             // Convert the favorite icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
3285             favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
3286
3287             // Convert the favorite icon byte array stream to a byte array.
3288             byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
3289
3290             // Create an intent to launch the bookmarks activity.
3291             Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
3292
3293             // Add the extra information to the intent.
3294             bookmarksIntent.putExtra("current_url", currentWebView.getUrl());
3295             bookmarksIntent.putExtra("current_title", currentWebView.getTitle());
3296             bookmarksIntent.putExtra("current_folder", currentBookmarksFolder);
3297             bookmarksIntent.putExtra("favorite_icon_byte_array", favoriteIconByteArray);
3298
3299             // Make it so.
3300             startActivity(bookmarksIntent);
3301         });
3302
3303         // Set the create new bookmark folder FAB to display an alert dialog.
3304         createBookmarkFolderFab.setOnClickListener(v -> {
3305             // Create a create bookmark folder dialog.
3306             DialogFragment createBookmarkFolderDialog = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView.getFavoriteOrDefaultIcon());
3307
3308             // Show the create bookmark folder dialog.
3309             createBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.create_folder));
3310         });
3311
3312         // Set the create new bookmark FAB to display an alert dialog.
3313         createBookmarkFab.setOnClickListener(view -> {
3314             // Instantiate the create bookmark dialog.
3315             DialogFragment createBookmarkDialog = CreateBookmarkDialog.createBookmark(currentWebView.getUrl(), currentWebView.getTitle(), currentWebView.getFavoriteOrDefaultIcon());
3316
3317             // Display the create bookmark dialog.
3318             createBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.create_bookmark));
3319         });
3320
3321         // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
3322         findOnPageEditText.addTextChangedListener(new TextWatcher() {
3323             @Override
3324             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
3325                 // Do nothing.
3326             }
3327
3328             @Override
3329             public void onTextChanged(CharSequence s, int start, int before, int count) {
3330                 // Do nothing.
3331             }
3332
3333             @Override
3334             public void afterTextChanged(Editable s) {
3335                 // Search for the text in the WebView if it is not null.  Sometimes on resume after a period of non-use the WebView will be null.
3336                 if (currentWebView != null) {
3337                     currentWebView.findAllAsync(findOnPageEditText.getText().toString());
3338                 }
3339             }
3340         });
3341
3342         // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
3343         findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
3344             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {  // The `enter` key was pressed.
3345                 // Hide the soft keyboard.
3346                 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3347
3348                 // Consume the event.
3349                 return true;
3350             } else {  // A different key was pressed.
3351                 // Do not consume the event.
3352                 return false;
3353             }
3354         });
3355
3356         // Implement swipe to refresh.
3357         swipeRefreshLayout.setOnRefreshListener(() -> {
3358             // Reload the website.
3359             currentWebView.reload();
3360         });
3361
3362         // Store the default progress view offsets for use later in `initializeWebView()`.
3363         defaultProgressViewStartOffset = swipeRefreshLayout.getProgressViewStartOffset();
3364         defaultProgressViewEndOffset = swipeRefreshLayout.getProgressViewEndOffset();
3365
3366         // Set the refresh color scheme according to the theme.
3367         swipeRefreshLayout.setColorSchemeResources(R.color.blue_text);
3368
3369         // Initialize a color background typed value.
3370         TypedValue colorBackgroundTypedValue = new TypedValue();
3371
3372         // Get the color background from the theme.
3373         getTheme().resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true);
3374
3375         // Get the color background int from the typed value.
3376         int colorBackgroundInt = colorBackgroundTypedValue.data;
3377
3378         // Set the swipe refresh background color.
3379         swipeRefreshLayout.setProgressBackgroundColorSchemeColor(colorBackgroundInt);
3380
3381         // The drawer titles identify the drawer layouts in accessibility mode.
3382         drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
3383         drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
3384
3385         // Load the bookmarks folder.
3386         loadBookmarksFolder();
3387
3388         // Handle clicks on bookmarks.
3389         bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
3390             // Convert the id from long to int to match the format of the bookmarks database.
3391             int databaseId = (int) id;
3392
3393             // Get the bookmark cursor for this ID.
3394             Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseId);
3395
3396             // Move the bookmark cursor to the first row.
3397             bookmarkCursor.moveToFirst();
3398
3399             // Act upon the bookmark according to the type.
3400             if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {  // The selected bookmark is a folder.
3401                 // Store the new folder name in `currentBookmarksFolder`.
3402                 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME));
3403
3404                 // Load the new folder.
3405                 loadBookmarksFolder();
3406             } else {  // The selected bookmark is not a folder.
3407                 // Load the bookmark URL.
3408                 loadUrl(currentWebView, bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_URL)));
3409
3410                 // Close the bookmarks drawer.
3411                 drawerLayout.closeDrawer(GravityCompat.END);
3412             }
3413
3414             // Close the `Cursor`.
3415             bookmarkCursor.close();
3416         });
3417
3418         bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
3419             // Convert the database ID from `long` to `int`.
3420             int databaseId = (int) id;
3421
3422             // Find out if the selected bookmark is a folder.
3423             boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
3424
3425             // Check to see if the bookmark is a folder.
3426             if (isFolder) {  // The bookmark is a folder.
3427                 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
3428                 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME));
3429
3430                 // Instantiate the edit folder bookmark dialog.
3431                 DialogFragment editBookmarkFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
3432
3433                 // Show the edit folder bookmark dialog.
3434                 editBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.edit_folder));
3435             } else {  // The bookmark is not a folder.
3436                 // Get the bookmark cursor for this ID.
3437                 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseId);
3438
3439                 // Move the bookmark cursor to the first row.
3440                 bookmarkCursor.moveToFirst();
3441
3442                 // Load the bookmark in a new tab but do not switch to the tab or close the drawer.
3443                 addNewTab(bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_URL)), false);
3444
3445                 // Display a snackbar.
3446                 Snackbar.make(drawerLayout, R.string.bookmark_opened_in_background, Snackbar.LENGTH_SHORT).show();
3447             }
3448
3449             // Consume the event.
3450             return true;
3451         });
3452
3453         // The drawer listener is used to update the navigation menu.
3454         drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
3455             @Override
3456             public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
3457             }
3458
3459             @Override
3460             public void onDrawerOpened(@NonNull View drawerView) {
3461             }
3462
3463             @Override
3464             public void onDrawerClosed(@NonNull View drawerView) {
3465                 // Reset the drawer icon when the drawer is closed.  Otherwise, it is an arrow if the drawer is open when the app is restarted.
3466                 actionBarDrawerToggle.syncState();
3467             }
3468
3469             @Override
3470             public void onDrawerStateChanged(int newState) {
3471                 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) {  // A drawer is opening or closing.
3472                     // Update the navigation menu items if the WebView is not null.
3473                     if (currentWebView != null) {
3474                         navigationBackMenuItem.setEnabled(currentWebView.canGoBack());
3475                         navigationForwardMenuItem.setEnabled(currentWebView.canGoForward());
3476                         navigationHistoryMenuItem.setEnabled((currentWebView.canGoBack() || currentWebView.canGoForward()));
3477                         navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
3478
3479                         // Hide the keyboard (if displayed).
3480                         inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3481                     }
3482
3483                     // Clear the focus from from the URL text box.  This removes any text selection markers and context menus, which otherwise draw above the open drawers.
3484                     urlEditText.clearFocus();
3485
3486                     // Clear the focus from from the WebView if it is not null, which can happen if a user opens a drawer while the browser is being resumed.
3487                     if (currentWebView != null) {
3488                         // Clearing the focus from the WebView removes any text selection markers and context menus, which otherwise draw above the open drawers.
3489                         currentWebView.clearFocus();
3490                     }
3491                 }
3492             }
3493         });
3494
3495         // Replace the header that `WebView` creates for `X-Requested-With` with a null value.  The default value is the application ID (com.stoutner.privacybrowser.standard).
3496         customHeaders.put("X-Requested-With", "");
3497
3498         // Inflate a bare WebView to get the default user agent.  It is not used to render content on the screen.
3499         @SuppressLint("InflateParams") View webViewLayout = getLayoutInflater().inflate(R.layout.bare_webview, null, false);
3500
3501         // Get a handle for the WebView.
3502         WebView bareWebView = webViewLayout.findViewById(R.id.bare_webview);
3503
3504         // Store the default user agent.
3505         webViewDefaultUserAgent = bareWebView.getSettings().getUserAgentString();
3506
3507         // Destroy the bare WebView.
3508         bareWebView.destroy();
3509     }
3510
3511     private void applyAppSettings() {
3512         // Get a handle for the shared preferences.
3513         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3514
3515         // Store the values from the shared preferences in variables.
3516         incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3517         sanitizeTrackingQueries = sharedPreferences.getBoolean(getString(R.string.tracking_queries_key), true);
3518         sanitizeAmpRedirects = sharedPreferences.getBoolean(getString(R.string.amp_redirects_key), true);
3519         proxyMode = sharedPreferences.getString("proxy", getString(R.string.proxy_default_value));
3520         fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3521         downloadWithExternalApp = sharedPreferences.getBoolean(getString(R.string.download_with_external_app_key), false);
3522         hideAppBar = sharedPreferences.getBoolean("hide_app_bar", true);
3523         scrollAppBar = sharedPreferences.getBoolean(getString(R.string.scroll_app_bar_key), true);
3524
3525         // Apply the saved proxy mode if the app has been restarted.
3526         if (savedProxyMode != null) {
3527             // Apply the saved proxy mode.
3528             proxyMode = savedProxyMode;
3529
3530             // Reset the saved proxy mode.
3531             savedProxyMode = null;
3532         }
3533
3534         // Get the search string.
3535         String searchString = sharedPreferences.getString("search", getString(R.string.search_default_value));
3536
3537         // Set the search string.
3538         if (searchString.equals("Custom URL")) {  // A custom search string is used.
3539             searchURL = sharedPreferences.getString("search_custom_url", getString(R.string.search_custom_url_default_value));
3540         } else {  // A custom search string is not used.
3541             searchURL = searchString;
3542         }
3543
3544         // Apply the proxy.
3545         applyProxy(false);
3546
3547         // Adjust the layout and scrolling parameters according to the position of the app bar.
3548         if (bottomAppBar) {  // The app bar is on the bottom.
3549             // Adjust the UI.
3550             if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) {  // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
3551                 // Reset the WebView padding to fill the available space.
3552                 swipeRefreshLayout.setPadding(0, 0, 0, 0);
3553             } else {  // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
3554                 // Move the WebView above the app bar layout.
3555                 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight);
3556
3557                 // Show the app bar if it is scrolled off the screen.
3558                 if (appBarLayout.getTranslationY() != 0) {
3559                     // Animate the bottom app bar onto the screen.
3560                     objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0);
3561
3562                     // Make it so.
3563                     objectAnimator.start();
3564                 }
3565             }
3566         } else {  // The app bar is on the top.
3567             // Get the current layout parameters.  Using coordinator layout parameters allows the `setBehavior()` command and using app bar layout parameters allows the `setScrollFlags()` command.
3568             CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
3569             AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) toolbar.getLayoutParams();
3570             AppBarLayout.LayoutParams findOnPageLayoutParams = (AppBarLayout.LayoutParams) findOnPageLinearLayout.getLayoutParams();
3571             AppBarLayout.LayoutParams tabsLayoutParams = (AppBarLayout.LayoutParams) tabsLinearLayout.getLayoutParams();
3572
3573             // Add the scrolling behavior to the layout parameters.
3574             if (scrollAppBar) {
3575                 // Enable scrolling of the app bar.
3576                 swipeRefreshLayoutParams.setBehavior(new AppBarLayout.ScrollingViewBehavior());
3577                 toolbarLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3578                 findOnPageLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3579                 tabsLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3580             } else {
3581                 // Disable scrolling of the app bar.
3582                 swipeRefreshLayoutParams.setBehavior(null);
3583                 toolbarLayoutParams.setScrollFlags(0);
3584                 findOnPageLayoutParams.setScrollFlags(0);
3585                 tabsLayoutParams.setScrollFlags(0);
3586
3587                 // Expand the app bar if it is currently collapsed.
3588                 appBarLayout.setExpanded(true);
3589             }
3590
3591             // Set the app bar scrolling for each WebView.
3592             for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3593                 // Get the WebView tab fragment.
3594                 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3595
3596                 // Get the fragment view.
3597                 View fragmentView = webViewTabFragment.getView();
3598
3599                 // Only modify the WebViews if they exist.
3600                 if (fragmentView != null) {
3601                     // Get the nested scroll WebView from the tab fragment.
3602                     NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3603
3604                     // Set the app bar scrolling.
3605                     nestedScrollWebView.setNestedScrollingEnabled(scrollAppBar);
3606                 }
3607             }
3608         }
3609
3610         // Update the full screen browsing mode settings.
3611         if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {  // Privacy Browser is currently in full screen browsing mode.
3612             // Update the visibility of the app bar, which might have changed in the settings.
3613             if (hideAppBar) {
3614                 // Hide the tab linear layout.
3615                 tabsLinearLayout.setVisibility(View.GONE);
3616
3617                 // Hide the action bar.
3618                 actionBar.hide();
3619             } else {
3620                 // Show the tab linear layout.
3621                 tabsLinearLayout.setVisibility(View.VISIBLE);
3622
3623                 // Show the action bar.
3624                 actionBar.show();
3625             }
3626
3627             /* Hide the system bars.
3628              * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3629              * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
3630              * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3631              * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3632              */
3633             rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
3634                     View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3635         } else {  // Privacy Browser is not in full screen browsing mode.
3636             // Reset the full screen tracker, which could be true if Privacy Browser was in full screen mode before entering settings and full screen browsing was disabled.
3637             inFullScreenBrowsingMode = false;
3638
3639             // Show the tab linear layout.
3640             tabsLinearLayout.setVisibility(View.VISIBLE);
3641
3642             // Show the action bar.
3643             actionBar.show();
3644
3645             // Remove the `SYSTEM_UI` flags from the root frame layout.
3646             rootFrameLayout.setSystemUiVisibility(0);
3647         }
3648     }
3649
3650     @Override
3651     public void navigateHistory(@NonNull String url, int steps) {
3652         // Apply the domain settings.
3653         applyDomainSettings(currentWebView, url, false, false, false);
3654
3655         // Load the history entry.
3656         currentWebView.goBackOrForward(steps);
3657     }
3658
3659     @Override
3660     public void pinnedErrorGoBack() {
3661         // Get the current web back forward list.
3662         WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
3663
3664         // Get the previous entry URL.
3665         String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
3666
3667         // Apply the domain settings.
3668         applyDomainSettings(currentWebView, previousUrl, false, false, false);
3669
3670         // Go back.
3671         currentWebView.goBack();
3672     }
3673
3674     // `reloadWebsite` is used if returning from the Domains activity.  Otherwise JavaScript might not function correctly if it is newly enabled.
3675     @SuppressLint("SetJavaScriptEnabled")
3676     private void applyDomainSettings(NestedScrollWebView nestedScrollWebView, String url, boolean resetTab, boolean reloadWebsite, boolean loadUrl) {
3677         // Store the current URL.
3678         nestedScrollWebView.setCurrentUrl(url);
3679
3680         // Parse the URL into a URI.
3681         Uri uri = Uri.parse(url);
3682
3683         // Extract the domain from `uri`.
3684         String newHostName = uri.getHost();
3685
3686         // Strings don't like to be null.
3687         if (newHostName == null) {
3688             newHostName = "";
3689         }
3690
3691         // Apply the domain settings if a new domain is being loaded or if the new domain is blank.  This allows the user to set temporary settings for JavaScript, cookies, DOM storage, etc.
3692         if (!nestedScrollWebView.getCurrentDomainName().equals(newHostName) || newHostName.equals("")) {
3693             // Set the new host name as the current domain name.
3694             nestedScrollWebView.setCurrentDomainName(newHostName);
3695
3696             // Reset the ignoring of pinned domain information.
3697             nestedScrollWebView.setIgnorePinnedDomainInformation(false);
3698
3699             // Clear any pinned SSL certificate or IP addresses.
3700             nestedScrollWebView.clearPinnedSslCertificate();
3701             nestedScrollWebView.setPinnedIpAddresses("");
3702
3703             // Reset the favorite icon if specified.
3704             if (resetTab) {
3705                 // Initialize the favorite icon.
3706                 nestedScrollWebView.initializeFavoriteIcon();
3707
3708                 // Get the current page position.
3709                 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
3710
3711                 // Get the corresponding tab.
3712                 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
3713
3714                 // Update the tab if it isn't null, which sometimes happens when restarting from the background.
3715                 if (tab != null) {
3716                     // Get the tab custom view.
3717                     View tabCustomView = tab.getCustomView();
3718
3719                     // Remove the warning below that the tab custom view might be null.
3720                     assert tabCustomView != null;
3721
3722                     // Get the tab views.
3723                     ImageView tabFavoriteIconImageView = tabCustomView.findViewById(R.id.favorite_icon_imageview);
3724                     TextView tabTitleTextView = tabCustomView.findViewById(R.id.title_textview);
3725
3726                     // Set the default favorite icon as the favorite icon for this tab.
3727                     tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nestedScrollWebView.getFavoriteOrDefaultIcon(), 64, 64, true));
3728
3729                     // Set the loading title text.
3730                     tabTitleTextView.setText(R.string.loading);
3731                 }
3732             }
3733
3734             // Get a full domain name cursor.
3735             Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3736
3737             // Initialize `domainSettingsSet`.
3738             Set<String> domainSettingsSet = new HashSet<>();
3739
3740             // Get the domain name column index.
3741             int domainNameColumnIndex = domainNameCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.DOMAIN_NAME);
3742
3743             // Populate the domain settings set.
3744             for (int i = 0; i < domainNameCursor.getCount(); i++) {
3745                 // Move the domains cursor to the current row.
3746                 domainNameCursor.moveToPosition(i);
3747
3748                 // Store the domain name in the domain settings set.
3749                 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3750             }
3751
3752             // Close the domain name cursor.
3753             domainNameCursor.close();
3754
3755             // Initialize the domain name in database variable.
3756             String domainNameInDatabase = null;
3757
3758             // Check the hostname against the domain settings set.
3759             if (domainSettingsSet.contains(newHostName)) {  // The hostname is contained in the domain settings set.
3760                 // Record the domain name in the database.
3761                 domainNameInDatabase = newHostName;
3762
3763                 // Set the domain settings applied tracker to true.
3764                 nestedScrollWebView.setDomainSettingsApplied(true);
3765             } else {  // The hostname is not contained in the domain settings set.
3766                 // Set the domain settings applied tracker to false.
3767                 nestedScrollWebView.setDomainSettingsApplied(false);
3768             }
3769
3770             // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3771             while (!nestedScrollWebView.getDomainSettingsApplied() && newHostName.contains(".")) {  // Stop checking if domain settings are already applied or there are no more `.` in the hostname.
3772                 if (domainSettingsSet.contains("*." + newHostName)) {  // Check the host name prepended by `*.`.
3773                     // Set the domain settings applied tracker to true.
3774                     nestedScrollWebView.setDomainSettingsApplied(true);
3775
3776                     // Store the applied domain names as it appears in the database.
3777                     domainNameInDatabase = "*." + newHostName;
3778                 }
3779
3780                 // Strip out the lowest subdomain of of the host name.
3781                 newHostName = newHostName.substring(newHostName.indexOf(".") + 1);
3782             }
3783
3784
3785             // Get a handle for the shared preferences.
3786             SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3787
3788             // Store the general preference information.
3789             String defaultFontSizeString = sharedPreferences.getString("font_size", getString(R.string.font_size_default_value));
3790             String defaultUserAgentName = sharedPreferences.getString("user_agent", getString(R.string.user_agent_default_value));
3791             boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
3792             String webViewTheme = sharedPreferences.getString("webview_theme", getString(R.string.webview_theme_default_value));
3793             boolean wideViewport = sharedPreferences.getBoolean("wide_viewport", true);
3794             boolean displayWebpageImages = sharedPreferences.getBoolean("display_webpage_images", true);
3795
3796             // Get the WebView theme entry values string array.
3797             String[] webViewThemeEntryValuesStringArray = getResources().getStringArray(R.array.webview_theme_entry_values);
3798
3799             // Get a handle for the cookie manager.
3800             CookieManager cookieManager = CookieManager.getInstance();
3801
3802             // Initialize the user agent array adapter and string array.
3803             ArrayAdapter<CharSequence> userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item);
3804             String[] userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
3805
3806             if (nestedScrollWebView.getDomainSettingsApplied()) {  // The url has custom domain settings.
3807                 // Remove the incorrect lint warning below that the domain name in database might be null.
3808                 assert domainNameInDatabase != null;
3809
3810                 // Get a cursor for the current host.
3811                 Cursor currentDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3812
3813                 // Move to the first position.
3814                 currentDomainSettingsCursor.moveToFirst();
3815
3816                 // Get the settings from the cursor.
3817                 nestedScrollWebView.setDomainSettingsDatabaseId(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ID)));
3818                 nestedScrollWebView.getSettings().setJavaScriptEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3819                 nestedScrollWebView.setAcceptCookies(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.COOKIES)) == 1);
3820                 nestedScrollWebView.getSettings().setDomStorageEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3821                 // Form data can be removed once the minimum API >= 26.
3822                 boolean saveFormData = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3823                 nestedScrollWebView.setEasyListEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3824                 nestedScrollWebView.setEasyPrivacyEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3825                 nestedScrollWebView.setFanboysAnnoyanceListEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3826                 nestedScrollWebView.setFanboysSocialBlockingListEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(
3827                         DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3828                 nestedScrollWebView.setUltraListEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ULTRALIST)) == 1);
3829                 nestedScrollWebView.setUltraPrivacyEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1);
3830                 nestedScrollWebView.setBlockAllThirdPartyRequests(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
3831                 String userAgentName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.USER_AGENT));
3832                 int fontSize = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.FONT_SIZE));
3833                 int swipeToRefreshInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
3834                 int webViewThemeInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.WEBVIEW_THEME));
3835                 int wideViewportInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.WIDE_VIEWPORT));
3836                 int displayWebpageImagesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.DISPLAY_IMAGES));
3837                 boolean pinnedSslCertificate = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3838                 String pinnedSslIssuedToCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3839                 String pinnedSslIssuedToOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3840                 String pinnedSslIssuedToUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3841                 String pinnedSslIssuedByCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3842                 String pinnedSslIssuedByOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3843                 String pinnedSslIssuedByUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3844                 Date pinnedSslStartDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_START_DATE)));
3845                 Date pinnedSslEndDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_END_DATE)));
3846                 boolean pinnedIpAddresses = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.PINNED_IP_ADDRESSES)) == 1);
3847                 String pinnedHostIpAddresses = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.IP_ADDRESSES));
3848
3849                 // Close the current host domain settings cursor.
3850                 currentDomainSettingsCursor.close();
3851
3852                 // If there is a pinned SSL certificate, store it in the WebView.
3853                 if (pinnedSslCertificate) {
3854                     nestedScrollWebView.setPinnedSslCertificate(pinnedSslIssuedToCName, pinnedSslIssuedToOName, pinnedSslIssuedToUName, pinnedSslIssuedByCName, pinnedSslIssuedByOName, pinnedSslIssuedByUName,
3855                             pinnedSslStartDate, pinnedSslEndDate);
3856                 }
3857
3858                 // If there is a pinned IP address, store it in the WebView.
3859                 if (pinnedIpAddresses) {
3860                     nestedScrollWebView.setPinnedIpAddresses(pinnedHostIpAddresses);
3861                 }
3862
3863                 // Apply the cookie domain settings.
3864                 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptCookies());
3865
3866                 // Apply the form data setting if the API < 26.
3867                 if (Build.VERSION.SDK_INT < 26) {
3868                     nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
3869                 }
3870
3871                 // Apply the font size.
3872                 try {  // Try the specified font size to see if it is valid.
3873                     if (fontSize == 0) {  // Apply the default font size.
3874                             // Try to set the font size from the value in the app settings.
3875                             nestedScrollWebView.getSettings().setTextZoom(Integer.parseInt(defaultFontSizeString));
3876                     } else {  // Apply the font size from domain settings.
3877                         nestedScrollWebView.getSettings().setTextZoom(fontSize);
3878                     }
3879                 } catch (Exception exception) {  // The specified font size is invalid
3880                     // Set the font size to be 100%
3881                     nestedScrollWebView.getSettings().setTextZoom(100);
3882                 }
3883
3884                 // Set the user agent.
3885                 if (userAgentName.equals(getString(R.string.system_default_user_agent))) {  // Use the system default user agent.
3886                     // Get the array position of the default user agent name.
3887                     int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3888
3889                     // Set the user agent according to the system default.
3890                     switch (defaultUserAgentArrayPosition) {
3891                         case UNRECOGNIZED_USER_AGENT:  // The default user agent name is not on the canonical list.
3892                             // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3893                             nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
3894                             break;
3895
3896                         case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3897                             // Set the user agent to `""`, which uses the default value.
3898                             nestedScrollWebView.getSettings().setUserAgentString("");
3899                             break;
3900
3901                         case SETTINGS_CUSTOM_USER_AGENT:
3902                             // Set the default custom user agent.
3903                             nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
3904                             break;
3905
3906                         default:
3907                             // Get the user agent string from the user agent data array
3908                             nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
3909                     }
3910                 } else {  // Set the user agent according to the stored name.
3911                     // Get the array position of the user agent name.
3912                     int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
3913
3914                     switch (userAgentArrayPosition) {
3915                         case UNRECOGNIZED_USER_AGENT:  // The user agent name contains a custom user agent.
3916                             nestedScrollWebView.getSettings().setUserAgentString(userAgentName);
3917                             break;
3918
3919                         case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3920                             // Set the user agent to `""`, which uses the default value.
3921                             nestedScrollWebView.getSettings().setUserAgentString("");
3922                             break;
3923
3924                         default:
3925                             // Get the user agent string from the user agent data array.
3926                             nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3927                     }
3928                 }
3929
3930                 // Set swipe to refresh.
3931                 switch (swipeToRefreshInt) {
3932                     case DomainsDatabaseHelper.SYSTEM_DEFAULT:
3933                         // Store the swipe to refresh status in the nested scroll WebView.
3934                         nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
3935
3936                         // Update the swipe refresh layout.
3937                         if (defaultSwipeToRefresh) {  // Swipe to refresh is enabled.
3938                             // Only enable the swipe refresh layout if the WebView is scrolled to the top.  It is updated every time the scroll changes.
3939                             swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
3940                         } else {  // Swipe to refresh is disabled.
3941                             // Disable the swipe refresh layout.
3942                             swipeRefreshLayout.setEnabled(false);
3943                         }
3944                         break;
3945
3946                     case DomainsDatabaseHelper.ENABLED:
3947                         // Store the swipe to refresh status in the nested scroll WebView.
3948                         nestedScrollWebView.setSwipeToRefresh(true);
3949
3950                         // Only enable the swipe refresh layout if the WebView is scrolled to the top.  It is updated every time the scroll changes.
3951                         swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
3952                         break;
3953
3954                     case DomainsDatabaseHelper.DISABLED:
3955                         // Store the swipe to refresh status in the nested scroll WebView.
3956                         nestedScrollWebView.setSwipeToRefresh(false);
3957
3958                         // Disable swipe to refresh.
3959                         swipeRefreshLayout.setEnabled(false);
3960                 }
3961
3962                 // Check to see if WebView themes are supported.
3963                 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
3964                     // Set the WebView theme.
3965                     switch (webViewThemeInt) {
3966                         case DomainsDatabaseHelper.SYSTEM_DEFAULT:
3967                             // Set the WebView theme.  A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
3968                             if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) {  // The light theme is selected.
3969                                 // Turn off the WebView dark mode.
3970                                 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
3971                             } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) {  // The dark theme is selected.
3972                                 // Turn on the WebView dark mode.
3973                                 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
3974                             } else {  // The system default theme is selected.
3975                                 // Get the current system theme status.
3976                                 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
3977
3978                                 // Set the WebView theme according to the current system theme status.
3979                                 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {  // The system is in day mode.
3980                                     // Turn off the WebView dark mode.
3981                                     WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
3982                                 } else {  // The system is in night mode.
3983                                     // Turn on the WebView dark mode.
3984                                     WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
3985                                 }
3986                             }
3987                             break;
3988
3989                         case DomainsDatabaseHelper.LIGHT_THEME:
3990                             // Turn off the WebView dark mode.
3991                             WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
3992                             break;
3993
3994                         case DomainsDatabaseHelper.DARK_THEME:
3995                             // Turn on the WebView dark mode.
3996                             WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
3997                             break;
3998                     }
3999                 }
4000
4001                 // Set the viewport.
4002                 switch (wideViewportInt) {
4003                     case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4004                         nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
4005                         break;
4006
4007                     case DomainsDatabaseHelper.ENABLED:
4008                         nestedScrollWebView.getSettings().setUseWideViewPort(true);
4009                         break;
4010
4011                     case DomainsDatabaseHelper.DISABLED:
4012                         nestedScrollWebView.getSettings().setUseWideViewPort(false);
4013                         break;
4014                 }
4015
4016                 // Set the loading of webpage images.
4017                 switch (displayWebpageImagesInt) {
4018                     case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4019                         nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4020                         break;
4021
4022                     case DomainsDatabaseHelper.ENABLED:
4023                         nestedScrollWebView.getSettings().setLoadsImagesAutomatically(true);
4024                         break;
4025
4026                     case DomainsDatabaseHelper.DISABLED:
4027                         nestedScrollWebView.getSettings().setLoadsImagesAutomatically(false);
4028                         break;
4029                 }
4030
4031                 // Set a background on the URL relative layout to indicate that custom domain settings are being used.
4032                 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.domain_settings_url_background, null));
4033             } else {  // The new URL does not have custom domain settings.  Load the defaults.
4034                 // Store the values from the shared preferences.
4035                 nestedScrollWebView.getSettings().setJavaScriptEnabled(sharedPreferences.getBoolean("javascript", false));
4036                 nestedScrollWebView.setAcceptCookies(sharedPreferences.getBoolean(getString(R.string.cookies_key), false));
4037                 nestedScrollWebView.getSettings().setDomStorageEnabled(sharedPreferences.getBoolean("dom_storage", false));
4038                 boolean saveFormData = sharedPreferences.getBoolean("save_form_data", false);  // Form data can be removed once the minimum API >= 26.
4039                 nestedScrollWebView.setEasyListEnabled(sharedPreferences.getBoolean("easylist", true));
4040                 nestedScrollWebView.setEasyPrivacyEnabled(sharedPreferences.getBoolean("easyprivacy", true));
4041                 nestedScrollWebView.setFanboysAnnoyanceListEnabled(sharedPreferences.getBoolean("fanboys_annoyance_list", true));
4042                 nestedScrollWebView.setFanboysSocialBlockingListEnabled(sharedPreferences.getBoolean("fanboys_social_blocking_list", true));
4043                 nestedScrollWebView.setUltraListEnabled(sharedPreferences.getBoolean("ultralist", true));
4044                 nestedScrollWebView.setUltraPrivacyEnabled(sharedPreferences.getBoolean("ultraprivacy", true));
4045                 nestedScrollWebView.setBlockAllThirdPartyRequests(sharedPreferences.getBoolean("block_all_third_party_requests", false));
4046
4047                 // Apply the default cookie setting.
4048                 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptCookies());
4049
4050                 // Apply the default font size setting.
4051                 try {
4052                     // Try to set the font size from the value in the app settings.
4053                     nestedScrollWebView.getSettings().setTextZoom(Integer.parseInt(defaultFontSizeString));
4054                 } catch (Exception exception) {
4055                     // If the app settings value is invalid, set the font size to 100%.
4056                     nestedScrollWebView.getSettings().setTextZoom(100);
4057                 }
4058
4059                 // Apply the form data setting if the API < 26.
4060                 if (Build.VERSION.SDK_INT < 26) {
4061                     nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
4062                 }
4063
4064                 // Store the swipe to refresh status in the nested scroll WebView.
4065                 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
4066
4067                 // Update the swipe refresh layout.
4068                 if (defaultSwipeToRefresh) {  // Swipe to refresh is enabled.
4069                     // Only enable the swipe refresh layout if the WebView is scrolled to the top.  It is updated every time the scroll changes.
4070                     swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
4071                 } else {  // Swipe to refresh is disabled.
4072                     // Disable the swipe refresh layout.
4073                     swipeRefreshLayout.setEnabled(false);
4074                 }
4075
4076                 // Reset the pinned variables.
4077                 nestedScrollWebView.setDomainSettingsDatabaseId(-1);
4078
4079                 // Get the array position of the user agent name.
4080                 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4081
4082                 // Set the user agent.
4083                 switch (userAgentArrayPosition) {
4084                     case UNRECOGNIZED_USER_AGENT:  // The default user agent name is not on the canonical list.
4085                         // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4086                         nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
4087                         break;
4088
4089                     case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4090                         // Set the user agent to `""`, which uses the default value.
4091                         nestedScrollWebView.getSettings().setUserAgentString("");
4092                         break;
4093
4094                     case SETTINGS_CUSTOM_USER_AGENT:
4095                         // Set the default custom user agent.
4096                         nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
4097                         break;
4098
4099                     default:
4100                         // Get the user agent string from the user agent data array
4101                         nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4102                 }
4103
4104                 // Apply the WebView theme if supported by the installed WebView.
4105                 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
4106                     // Set the WebView theme.  A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
4107                     if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) {  // The light theme is selected.
4108                         // Turn off the WebView dark mode.
4109                         WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4110                     } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) {  // The dark theme is selected.
4111                         // Turn on the WebView dark mode.
4112                         WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4113                     } else {  // The system default theme is selected.
4114                         // Get the current system theme status.
4115                         int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4116
4117                         // Set the WebView theme according to the current system theme status.
4118                         if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {  // The system is in day mode.
4119                             // Turn off the WebView dark mode.
4120                             WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4121                         } else {  // The system is in night mode.
4122                             // Turn on the WebView dark mode.
4123                             WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4124                         }
4125                     }
4126                 }
4127
4128                 // Set the viewport.
4129                 nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
4130
4131                 // Set the loading of webpage images.
4132                 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4133
4134                 // Set a transparent background on the URL relative layout.
4135                 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.color.transparent, null));
4136             }
4137
4138             // Close the domains database helper.
4139             domainsDatabaseHelper.close();
4140
4141             // Update the privacy icons.
4142             updatePrivacyIcons(true);
4143         }
4144
4145         // Reload the website if returning from the Domains activity.
4146         if (reloadWebsite) {
4147             nestedScrollWebView.reload();
4148         }
4149
4150         // Load the URL if directed.  This makes sure that the domain settings are properly loaded before the URL.  By using `loadUrl()`, instead of `loadUrlFromBase()`, the Referer header will never be sent.
4151         if (loadUrl) {
4152             nestedScrollWebView.loadUrl(url, customHeaders);
4153         }
4154     }
4155
4156     private void applyProxy(boolean reloadWebViews) {
4157         // Set the proxy according to the mode.
4158         proxyHelper.setProxy(getApplicationContext(), appBarLayout, proxyMode);
4159
4160         // Reset the waiting for proxy tracker.
4161         waitingForProxy = false;
4162
4163         // Get the current theme status.
4164         int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4165
4166         // Update the user interface and reload the WebViews if requested.
4167         switch (proxyMode) {
4168             case ProxyHelper.NONE:
4169                 // Initialize a color background typed value.
4170                 TypedValue colorBackgroundTypedValue = new TypedValue();
4171
4172                 // Get the color background from the theme.
4173                 getTheme().resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true);
4174
4175                 // Get the color background int from the typed value.
4176                 int colorBackgroundInt = colorBackgroundTypedValue.data;
4177
4178                 // Set the default app bar layout background.
4179                 appBarLayout.setBackgroundColor(colorBackgroundInt);
4180                 break;
4181
4182             case ProxyHelper.TOR:
4183                 // Set the app bar background to indicate proxying through Orbot is enabled.
4184                 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4185                     appBarLayout.setBackgroundResource(R.color.blue_50);
4186                 } else {
4187                     appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4188                 }
4189
4190                 // Check to see if Orbot is installed.
4191                 try {
4192                     // Get the package manager.
4193                     PackageManager packageManager = getPackageManager();
4194
4195                     // Check to see if Orbot is in the list.  This will throw an error and drop to the catch section if it isn't installed.
4196                     packageManager.getPackageInfo("org.torproject.android", 0);
4197
4198                     // Check to see if the proxy is ready.
4199                     if (!orbotStatus.equals(ProxyHelper.ORBOT_STATUS_ON)) {  // Orbot is not ready.
4200                         // Set the waiting for proxy status.
4201                         waitingForProxy = true;
4202
4203                         // Show the waiting for proxy dialog if it isn't already displayed.
4204                         if (getSupportFragmentManager().findFragmentByTag(getString(R.string.waiting_for_proxy_dialog)) == null) {
4205                             // Get a handle for the waiting for proxy alert dialog.
4206                             DialogFragment waitingForProxyDialogFragment = new WaitingForProxyDialog();
4207
4208                             // Try to show the dialog.  Sometimes the window is not yet active if returning from Settings.
4209                             try {
4210                                 // Show the waiting for proxy alert dialog.
4211                                 waitingForProxyDialogFragment.show(getSupportFragmentManager(), getString(R.string.waiting_for_proxy_dialog));
4212                             } catch (Exception waitingForTorException) {
4213                                 // Add the dialog to the pending dialog array list.  It will be displayed in `onStart()`.
4214                                 pendingDialogsArrayList.add(new PendingDialog(waitingForProxyDialogFragment, getString(R.string.waiting_for_proxy_dialog)));
4215                             }
4216                         }
4217                     }
4218                 } catch (PackageManager.NameNotFoundException exception) {  // Orbot is not installed.
4219                     // Show the Orbot not installed dialog if it is not already displayed.
4220                     if (getSupportFragmentManager().findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
4221                         // Get a handle for the Orbot not installed alert dialog.
4222                         DialogFragment orbotNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode);
4223
4224                         // Try to show the dialog.  Sometimes the window is not yet active if returning from Settings.
4225                         try {
4226                             // Display the Orbot not installed alert dialog.
4227                             orbotNotInstalledDialogFragment.show(getSupportFragmentManager(), getString(R.string.proxy_not_installed_dialog));
4228                         } catch (Exception orbotNotInstalledException) {
4229                             // Add the dialog to the pending dialog array list.  It will be displayed in `onStart()`.
4230                             pendingDialogsArrayList.add(new PendingDialog(orbotNotInstalledDialogFragment, getString(R.string.proxy_not_installed_dialog)));
4231                         }
4232                     }
4233                 }
4234                 break;
4235
4236             case ProxyHelper.I2P:
4237                 // Set the app bar background to indicate proxying through Orbot is enabled.
4238                 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4239                     appBarLayout.setBackgroundResource(R.color.blue_50);
4240                 } else {
4241                     appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4242                 }
4243
4244                 // Check to see if I2P is installed.
4245                 try {
4246                     // Get the package manager.
4247                     PackageManager packageManager = getPackageManager();
4248
4249                     // Check to see if I2P is in the list.  This will throw an error and drop to the catch section if it isn't installed.
4250                     packageManager.getPackageInfo("net.i2p.android.router", 0);
4251                 } catch (PackageManager.NameNotFoundException exception) {  // I2P is not installed.
4252                     // Sow the I2P not installed dialog if it is not already displayed.
4253                     if (getSupportFragmentManager().findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
4254                         // Get a handle for the waiting for proxy alert dialog.
4255                         DialogFragment i2pNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode);
4256
4257                         // Try to show the dialog.  Sometimes the window is not yet active if returning from Settings.
4258                         try {
4259                             // Display the I2P not installed alert dialog.
4260                             i2pNotInstalledDialogFragment.show(getSupportFragmentManager(), getString(R.string.proxy_not_installed_dialog));
4261                         } catch (Exception i2pNotInstalledException) {
4262                             // Add the dialog to the pending dialog array list.  It will be displayed in `onStart()`.
4263                             pendingDialogsArrayList.add(new PendingDialog(i2pNotInstalledDialogFragment, getString(R.string.proxy_not_installed_dialog)));
4264                         }
4265                     }
4266                 }
4267                 break;
4268
4269             case ProxyHelper.CUSTOM:
4270                 // Set the app bar background to indicate proxying through Orbot is enabled.
4271                 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4272                     appBarLayout.setBackgroundResource(R.color.blue_50);
4273                 } else {
4274                     appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4275                 }
4276                 break;
4277         }
4278
4279         // Reload the WebViews if requested and not waiting for the proxy.
4280         if (reloadWebViews && !waitingForProxy) {
4281             // Reload the WebViews.
4282             for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4283                 // Get the WebView tab fragment.
4284                 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4285
4286                 // Get the fragment view.
4287                 View fragmentView = webViewTabFragment.getView();
4288
4289                 // Only reload the WebViews if they exist.
4290                 if (fragmentView != null) {
4291                     // Get the nested scroll WebView from the tab fragment.
4292                     NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4293
4294                     // Reload the WebView.
4295                     nestedScrollWebView.reload();
4296                 }
4297             }
4298         }
4299     }
4300
4301     private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
4302         // Only update the privacy icons if the options menu and the current WebView have already been populated.
4303         if ((optionsMenu != null) && (currentWebView != null)) {
4304             // Update the privacy icon.
4305             if (currentWebView.getSettings().getJavaScriptEnabled()) {  // JavaScript is enabled.
4306                 optionsPrivacyMenuItem.setIcon(R.drawable.javascript_enabled);
4307             } else if (currentWebView.getAcceptCookies()) {  // JavaScript is disabled but cookies are enabled.
4308                 optionsPrivacyMenuItem.setIcon(R.drawable.warning);
4309             } else {  // All the dangerous features are disabled.
4310                 optionsPrivacyMenuItem.setIcon(R.drawable.privacy_mode);
4311             }
4312
4313             // Update the cookies icon.
4314             if (currentWebView.getAcceptCookies()) {
4315                 optionsCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
4316             } else {
4317                 optionsCookiesMenuItem.setIcon(R.drawable.cookies_disabled);
4318             }
4319
4320             // Update the refresh icon.
4321             if (optionsRefreshMenuItem.getTitle() == getString(R.string.refresh)) {  // The refresh icon is displayed.
4322                 // Set the icon.  Once the minimum API is >= 26, the blue and black icons can be combined with a tint list.
4323                 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled);
4324             } else {  // The stop icon is displayed.
4325                 // Set the icon.  Once the minimum API is >= 26, the blue and black icons can be combined with a tint list.
4326                 optionsRefreshMenuItem.setIcon(R.drawable.close_blue);
4327             }
4328
4329             // `invalidateOptionsMenu()` calls `onPrepareOptionsMenu()` and redraws the icons in the app bar.
4330             if (runInvalidateOptionsMenu) {
4331                 invalidateOptionsMenu();
4332             }
4333         }
4334     }
4335
4336     private void highlightUrlText() {
4337         // Only highlight the URL text if the box is not currently selected.
4338         if (!urlEditText.hasFocus()) {
4339             // Get the URL string.
4340             String urlString = urlEditText.getText().toString();
4341
4342             // Highlight the URL according to the protocol.
4343             if (urlString.startsWith("file://") || urlString.startsWith("content://")) {  // This is a file or content URL.
4344                 // De-emphasize everything before the file name.
4345                 urlEditText.getText().setSpan(initialGrayColorSpan, 0, urlString.lastIndexOf("/") + 1,Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4346             } else {  // This is a web URL.
4347                 // Get the index of the `/` immediately after the domain name.
4348                 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
4349
4350                 // Create a base URL string.
4351                 String baseUrl;
4352
4353                 // Get the base URL.
4354                 if (endOfDomainName > 0) {  // There is at least one character after the base URL.
4355                     // Get the base URL.
4356                     baseUrl = urlString.substring(0, endOfDomainName);
4357                 } else {  // There are no characters after the base URL.
4358                     // Set the base URL to be the entire URL string.
4359                     baseUrl = urlString;
4360                 }
4361
4362                 // Get the index of the last `.` in the domain.
4363                 int lastDotIndex = baseUrl.lastIndexOf(".");
4364
4365                 // Get the index of the penultimate `.` in the domain.
4366                 int penultimateDotIndex = baseUrl.lastIndexOf(".", lastDotIndex - 1);
4367
4368                 // Markup the beginning of the URL.
4369                 if (urlString.startsWith("http://")) {  // Highlight the protocol of connections that are not encrypted.
4370                     urlEditText.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4371
4372                     // De-emphasize subdomains.
4373                     if (penultimateDotIndex > 0) {  // There is more than one subdomain in the domain name.
4374                         urlEditText.getText().setSpan(initialGrayColorSpan, 7, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4375                     }
4376                 } else if (urlString.startsWith("https://")) {  // De-emphasize the protocol of connections that are encrypted.
4377                     if (penultimateDotIndex > 0) {  // There is more than one subdomain in the domain name.
4378                         // De-emphasize the protocol and the additional subdomains.
4379                         urlEditText.getText().setSpan(initialGrayColorSpan, 0, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4380                     } else {  // There is only one subdomain in the domain name.
4381                         // De-emphasize only the protocol.
4382                         urlEditText.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4383                     }
4384                 }
4385
4386                 // De-emphasize the text after the domain name.
4387                 if (endOfDomainName > 0) {
4388                     urlEditText.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4389                 }
4390             }
4391         }
4392     }
4393
4394     private void loadBookmarksFolder() {
4395         // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
4396         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
4397
4398         // Populate the bookmarks cursor adapter.
4399         bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
4400             @Override
4401             public View newView(Context context, Cursor cursor, ViewGroup parent) {
4402                 // Inflate the individual item layout.
4403                 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
4404             }
4405
4406             @Override
4407             public void bindView(View view, Context context, Cursor cursor) {
4408                 // Get handles for the views.
4409                 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
4410                 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
4411
4412                 // Get the favorite icon byte array from the cursor.
4413                 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.FAVORITE_ICON));
4414
4415                 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
4416                 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
4417
4418                 // Display the bitmap in `bookmarkFavoriteIcon`.
4419                 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4420
4421                 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4422                 String bookmarkNameString = cursor.getString(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME));
4423                 bookmarkNameTextView.setText(bookmarkNameString);
4424
4425                 // Make the font bold for folders.
4426                 if (cursor.getInt(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4427                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4428                 } else {  // Reset the font to default for normal bookmarks.
4429                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4430                 }
4431             }
4432         };
4433
4434         // Get a handle for the bookmarks list view.
4435         ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
4436
4437         // Populate the list view with the adapter.
4438         bookmarksListView.setAdapter(bookmarksCursorAdapter);
4439
4440         // Get a handle for the bookmarks title text view.
4441         TextView bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
4442
4443         // Set the bookmarks drawer title.
4444         if (currentBookmarksFolder.isEmpty()) {
4445             bookmarksTitleTextView.setText(R.string.bookmarks);
4446         } else {
4447             bookmarksTitleTextView.setText(currentBookmarksFolder);
4448         }
4449     }
4450
4451     private void openWithApp(String url) {
4452         // Create an open with app intent with `ACTION_VIEW`.
4453         Intent openWithAppIntent = new Intent(Intent.ACTION_VIEW);
4454
4455         // Set the URI but not the MIME type.  This should open all available apps.
4456         openWithAppIntent.setData(Uri.parse(url));
4457
4458         // Flag the intent to open in a new task.
4459         openWithAppIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4460
4461         // Try the intent.
4462         try {
4463             // Show the chooser.
4464             startActivity(openWithAppIntent);
4465         } catch (ActivityNotFoundException exception) {  // There are no apps available to open the URL.
4466             // Show a snackbar with the error.
4467             Snackbar.make(currentWebView, getString(R.string.error) + "  " + exception, Snackbar.LENGTH_INDEFINITE).show();
4468         }
4469     }
4470
4471     private void openWithBrowser(String url) {
4472         // Create an open with browser intent with `ACTION_VIEW`.
4473         Intent openWithBrowserIntent = new Intent(Intent.ACTION_VIEW);
4474
4475         // Set the URI and the MIME type.  `"text/html"` should load browser options.
4476         openWithBrowserIntent.setDataAndType(Uri.parse(url), "text/html");
4477
4478         // Flag the intent to open in a new task.
4479         openWithBrowserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4480
4481         // Try the intent.
4482         try {
4483             // Show the chooser.
4484             startActivity(openWithBrowserIntent);
4485         } catch (ActivityNotFoundException exception) {  // There are no browsers available to open the URL.
4486             // Show a snackbar with the error.
4487             Snackbar.make(currentWebView, getString(R.string.error) + "  " + exception, Snackbar.LENGTH_INDEFINITE).show();
4488         }
4489     }
4490
4491     private String sanitizeUrl(String url) {
4492         // Sanitize tracking queries.
4493         if (sanitizeTrackingQueries)
4494             url = sanitizeUrlHelper.sanitizeTrackingQueries(url);
4495
4496         // Sanitize AMP redirects.
4497         if (sanitizeAmpRedirects)
4498             url = sanitizeUrlHelper.sanitizeAmpRedirects(url);
4499
4500         // Return the sanitized URL.
4501         return url;
4502     }
4503
4504     public void finishedPopulatingBlocklists(ArrayList<ArrayList<List<String[]>>> combinedBlocklists) {
4505         // Store the blocklists.
4506         easyList = combinedBlocklists.get(0);
4507         easyPrivacy = combinedBlocklists.get(1);
4508         fanboysAnnoyanceList = combinedBlocklists.get(2);
4509         fanboysSocialList = combinedBlocklists.get(3);
4510         ultraList = combinedBlocklists.get(4);
4511         ultraPrivacy = combinedBlocklists.get(5);
4512
4513         // Check to see if the activity has been restarted with a saved state.
4514         if ((savedStateArrayList == null) || (savedStateArrayList.size() == 0)) {  // The activity has not been restarted or it was restarted on start to force the night theme.
4515             // Add the first tab.
4516             addNewTab("", true);
4517         } else {  // The activity has been restarted.
4518             // Restore each tab.  Once the minimum API >= 24, a `forEach()` command can be used.
4519             for (int i = 0; i < savedStateArrayList.size(); i++) {
4520                 // Add a new tab.
4521                 tabLayout.addTab(tabLayout.newTab());
4522
4523                 // Get the new tab.
4524                 TabLayout.Tab newTab = tabLayout.getTabAt(i);
4525
4526                 // Remove the lint warning below that the current tab might be null.
4527                 assert newTab != null;
4528
4529                 // Set a custom view on the new tab.
4530                 newTab.setCustomView(R.layout.tab_custom_view);
4531
4532                 // Add the new page.
4533                 webViewPagerAdapter.restorePage(savedStateArrayList.get(i), savedNestedScrollWebViewStateArrayList.get(i));
4534             }
4535
4536             // Reset the saved state variables.
4537             savedStateArrayList = null;
4538             savedNestedScrollWebViewStateArrayList = null;
4539
4540             // Restore the selected tab position.
4541             if (savedTabPosition == 0) {  // The first tab is selected.
4542                 // Set the first page as the current WebView.
4543                 setCurrentWebView(0);
4544             } else {  // the first tab is not selected.
4545                 // Move to the selected tab.
4546                 webViewPager.setCurrentItem(savedTabPosition);
4547             }
4548
4549             // Get the intent that started the app.
4550             Intent intent = getIntent();
4551
4552             // Reset the intent.  This prevents a duplicate tab from being created on restart.
4553             setIntent(new Intent());
4554
4555             // Get the information from the intent.
4556             String intentAction = intent.getAction();
4557             Uri intentUriData = intent.getData();
4558             String intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT);
4559
4560             // Determine if this is a web search.
4561             boolean isWebSearch = ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH));
4562
4563             // 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.
4564             if (intentUriData != null || intentStringExtra != null || isWebSearch) {
4565                 // Get the shared preferences.
4566                 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4567
4568                 // Create a URL string.
4569                 String url;
4570
4571                 // If the intent action is a web search, perform the search.
4572                 if (isWebSearch) {  // The intent is a web search.
4573                     // Create an encoded URL string.
4574                     String encodedUrlString;
4575
4576                     // Sanitize the search input and convert it to a search.
4577                     try {
4578                         encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
4579                     } catch (UnsupportedEncodingException exception) {
4580                         encodedUrlString = "";
4581                     }
4582
4583                     // Add the base search URL.
4584                     url = searchURL + encodedUrlString;
4585                 } else if (intentUriData != null) {  // The intent contains a URL formatted as a URI.
4586                     // Set the intent data as the URL.
4587                     url = intentUriData.toString();
4588                 } else {  // The intent contains a string, which might be a URL.
4589                     // Set the intent string as the URL.
4590                     url = intentStringExtra;
4591                 }
4592
4593                 // Add a new tab if specified in the preferences.
4594                 if (sharedPreferences.getBoolean("open_intents_in_new_tab", true)) {  // Load the URL in a new tab.
4595                     // Set the loading new intent flag.
4596                     loadingNewIntent = true;
4597
4598                     // Add a new tab.
4599                     addNewTab(url, true);
4600                 } else {  // Load the URL in the current tab.
4601                     // Make it so.
4602                     loadUrl(currentWebView, url);
4603                 }
4604             }
4605         }
4606     }
4607
4608     public void addTab(View view) {
4609         // Add a new tab with a blank URL.
4610         addNewTab("", true);
4611     }
4612
4613     private void addNewTab(String url, boolean moveToTab) {
4614         // Clear the focus from the URL edit text, so that it will be populated with the information from the new tab.
4615         urlEditText.clearFocus();
4616
4617         // Get the new page number.  The page numbers are 0 indexed, so the new page number will match the current count.
4618         int newTabNumber = tabLayout.getTabCount();
4619
4620         // Add a new tab.
4621         tabLayout.addTab(tabLayout.newTab());
4622
4623         // Get the new tab.
4624         TabLayout.Tab newTab = tabLayout.getTabAt(newTabNumber);
4625
4626         // Remove the lint warning below that the current tab might be null.
4627         assert newTab != null;
4628
4629         // Set a custom view on the new tab.
4630         newTab.setCustomView(R.layout.tab_custom_view);
4631
4632         // Add the new WebView page.
4633         webViewPagerAdapter.addPage(newTabNumber, webViewPager, url, moveToTab);
4634
4635         // Show the app bar if it is at the bottom of the screen and the new tab is taking focus.
4636         if (bottomAppBar && moveToTab && (appBarLayout.getTranslationY() != 0)) {
4637             // Animate the bottom app bar onto the screen.
4638             objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0);
4639
4640             // Make it so.
4641             objectAnimator.start();
4642         }
4643     }
4644
4645     public void closeTab(View view) {
4646         // Run the command according to the number of tabs.
4647         if (tabLayout.getTabCount() > 1) {  // There is more than one tab open.
4648             // Close the current tab.
4649             closeCurrentTab();
4650         } else {  // There is only one tab open.
4651             clearAndExit();
4652         }
4653     }
4654
4655     private void closeCurrentTab() {
4656         // Get the current tab number.
4657         int currentTabNumber = tabLayout.getSelectedTabPosition();
4658
4659         // Delete the current tab.
4660         tabLayout.removeTabAt(currentTabNumber);
4661
4662         // Delete the current page.  If the selected page number did not change during the delete (because the newly selected tab has has same number as the previously deleted tab), it will return true,
4663         // meaning that the current WebView must be reset.  Otherwise it will happen automatically as the selected tab number changes.
4664         if (webViewPagerAdapter.deletePage(currentTabNumber, webViewPager)) {
4665             setCurrentWebView(currentTabNumber);
4666         }
4667     }
4668
4669     private void exitFullScreenVideo() {
4670         // Re-enable the screen timeout.
4671         fullScreenVideoFrameLayout.setKeepScreenOn(false);
4672
4673         // Unset the full screen video flag.
4674         displayingFullScreenVideo = false;
4675
4676         // Remove all the views from the full screen video frame layout.
4677         fullScreenVideoFrameLayout.removeAllViews();
4678
4679         // Hide the full screen video frame layout.
4680         fullScreenVideoFrameLayout.setVisibility(View.GONE);
4681
4682         // Enable the sliding drawers.
4683         drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
4684
4685         // Show the coordinator layout.
4686         coordinatorLayout.setVisibility(View.VISIBLE);
4687
4688         // Apply the appropriate full screen mode flags.
4689         if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {  // Privacy Browser is currently in full screen browsing mode.
4690             // Hide the app bar if specified.
4691             if (hideAppBar) {
4692                 // Hide the tab linear layout.
4693                 tabsLinearLayout.setVisibility(View.GONE);
4694
4695                 // Hide the action bar.
4696                 actionBar.hide();
4697             }
4698
4699             /* Hide the system bars.
4700              * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4701              * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4702              * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4703              * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4704              */
4705             rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
4706                     View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
4707         } else {  // Switch to normal viewing mode.
4708             // Remove the `SYSTEM_UI` flags from the root frame layout.
4709             rootFrameLayout.setSystemUiVisibility(0);
4710         }
4711     }
4712
4713     private void clearAndExit() {
4714         // Get a handle for the shared preferences.
4715         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4716
4717         // Close the bookmarks cursor and database.
4718         bookmarksCursor.close();
4719         bookmarksDatabaseHelper.close();
4720
4721         // Get the status of the clear everything preference.
4722         boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
4723
4724         // Get a handle for the runtime.
4725         Runtime runtime = Runtime.getRuntime();
4726
4727         // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
4728         // which links to `/data/data/com.stoutner.privacybrowser.standard`.
4729         String privateDataDirectoryString = getApplicationInfo().dataDir;
4730
4731         // Clear cookies.
4732         if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
4733             // Request the cookies be deleted.
4734             CookieManager.getInstance().removeAllCookies(null);
4735
4736             // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4737             try {
4738                 // Two commands must be used because `Runtime.exec()` does not like `*`.
4739                 Process deleteCookiesProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
4740                 Process deleteCookiesJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
4741
4742                 // Wait until the processes have finished.
4743                 deleteCookiesProcess.waitFor();
4744                 deleteCookiesJournalProcess.waitFor();
4745             } catch (Exception exception) {
4746                 // Do nothing if an error is thrown.
4747             }
4748         }
4749
4750         // Clear DOM storage.
4751         if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
4752             // Ask `WebStorage` to clear the DOM storage.
4753             WebStorage webStorage = WebStorage.getInstance();
4754             webStorage.deleteAllData();
4755
4756             // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4757             try {
4758                 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4759                 Process deleteLocalStorageProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
4760
4761                 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
4762                 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
4763                 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
4764                 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
4765                 Process deleteDatabaseProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
4766
4767                 // Wait until the processes have finished.
4768                 deleteLocalStorageProcess.waitFor();
4769                 deleteIndexProcess.waitFor();
4770                 deleteQuotaManagerProcess.waitFor();
4771                 deleteQuotaManagerJournalProcess.waitFor();
4772                 deleteDatabaseProcess.waitFor();
4773             } catch (Exception exception) {
4774                 // Do nothing if an error is thrown.
4775             }
4776         }
4777
4778         // Clear form data if the API < 26.
4779         if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
4780             WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
4781             webViewDatabase.clearFormData();
4782
4783             // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4784             try {
4785                 // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
4786                 Process deleteWebDataProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
4787                 Process deleteWebDataJournalProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
4788
4789                 // Wait until the processes have finished.
4790                 deleteWebDataProcess.waitFor();
4791                 deleteWebDataJournalProcess.waitFor();
4792             } catch (Exception exception) {
4793                 // Do nothing if an error is thrown.
4794             }
4795         }
4796
4797         // Clear the logcat.
4798         if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_logcat_key), true)) {
4799             try {
4800                 // Clear the logcat.  `-c` clears the logcat.  `-b all` clears all the buffers (instead of just crash, main, and system).
4801                 Process process = Runtime.getRuntime().exec("logcat -b all -c");
4802
4803                 // Wait for the process to finish.
4804                 process.waitFor();
4805             } catch (IOException|InterruptedException exception) {
4806                 // Do nothing.
4807             }
4808         }
4809
4810         // Clear the cache.
4811         if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
4812             // Clear the cache from each WebView.
4813             for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4814                 // Get the WebView tab fragment.
4815                 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4816
4817                 // Get the WebView fragment view.
4818                 View webViewFragmentView = webViewTabFragment.getView();
4819
4820                 // Only clear the cache if the WebView exists.
4821                 if (webViewFragmentView != null) {
4822                     // Get the nested scroll WebView from the tab fragment.
4823                     NestedScrollWebView nestedScrollWebView = webViewFragmentView.findViewById(R.id.nestedscroll_webview);
4824
4825                     // Clear the cache for this WebView.
4826                     nestedScrollWebView.clearCache(true);
4827                 }
4828             }
4829
4830             // Manually delete the cache directories.
4831             try {
4832                 // Delete the main cache directory.
4833                 Process deleteCacheProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/cache");
4834
4835                 // Delete the secondary `Service Worker` cache directory.
4836                 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4837                 Process deleteServiceWorkerProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
4838
4839                 // Wait until the processes have finished.
4840                 deleteCacheProcess.waitFor();
4841                 deleteServiceWorkerProcess.waitFor();
4842             } catch (Exception exception) {
4843                 // Do nothing if an error is thrown.
4844             }
4845         }
4846
4847         // Wipe out each WebView.
4848         for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4849             // Get the WebView tab fragment.
4850             WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4851
4852             // Get the WebView frame layout.
4853             FrameLayout webViewFrameLayout = (FrameLayout) webViewTabFragment.getView();
4854
4855             // Only wipe out the WebView if it exists.
4856             if (webViewFrameLayout != null) {
4857                 // Get the nested scroll WebView from the tab fragment.
4858                 NestedScrollWebView nestedScrollWebView = webViewFrameLayout.findViewById(R.id.nestedscroll_webview);
4859
4860                 // Clear SSL certificate preferences for this WebView.
4861                 nestedScrollWebView.clearSslPreferences();
4862
4863                 // Clear the back/forward history for this WebView.
4864                 nestedScrollWebView.clearHistory();
4865
4866                 // Remove all the views from the frame layout.
4867                 webViewFrameLayout.removeAllViews();
4868
4869                 // Destroy the internal state of the WebView.
4870                 nestedScrollWebView.destroy();
4871             }
4872         }
4873
4874         // Clear the custom headers.
4875         customHeaders.clear();
4876
4877         // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
4878         // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
4879         if (clearEverything) {
4880             try {
4881                 // Delete the folder.
4882                 Process deleteAppWebviewProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
4883
4884                 // Wait until the process has finished.
4885                 deleteAppWebviewProcess.waitFor();
4886             } catch (Exception exception) {
4887                 // Do nothing if an error is thrown.
4888             }
4889         }
4890
4891         // Close Privacy Browser.  `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
4892         finishAndRemoveTask();
4893
4894         // Remove the terminated program from RAM.  The status code is `0`.
4895         System.exit(0);
4896     }
4897
4898     public void bookmarksBack(View view) {
4899         if (currentBookmarksFolder.isEmpty()) {  // The home folder is displayed.
4900             // close the bookmarks drawer.
4901             drawerLayout.closeDrawer(GravityCompat.END);
4902         } else {  // A subfolder is displayed.
4903             // Place the former parent folder in `currentFolder`.
4904             currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolderName(currentBookmarksFolder);
4905
4906             // Load the new folder.
4907             loadBookmarksFolder();
4908         }
4909     }
4910
4911     private void setCurrentWebView(int pageNumber) {
4912         // Stop the swipe to refresh indicator if it is running
4913         swipeRefreshLayout.setRefreshing(false);
4914
4915         // Get the WebView tab fragment.
4916         WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(pageNumber);
4917
4918         // Get the fragment view.
4919         View webViewFragmentView = webViewTabFragment.getView();
4920
4921         // Set the current WebView if the fragment view is not null.
4922         if (webViewFragmentView != null) {  // The fragment has been populated.
4923             // Store the current WebView.
4924             currentWebView = webViewFragmentView.findViewById(R.id.nestedscroll_webview);
4925
4926             // Update the status of swipe to refresh.
4927             if (currentWebView.getSwipeToRefresh()) {  // Swipe to refresh is enabled.
4928                 // Enable the swipe refresh layout if the WebView is scrolled all the way to the top.  It is updated every time the scroll changes.
4929                 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
4930             } else {  // Swipe to refresh is disabled.
4931                 // Disable the swipe refresh layout.
4932                 swipeRefreshLayout.setEnabled(false);
4933             }
4934
4935             // Get a handle for the cookie manager.
4936             CookieManager cookieManager = CookieManager.getInstance();
4937
4938             // Set the cookie status.
4939             cookieManager.setAcceptCookie(currentWebView.getAcceptCookies());
4940
4941             // Update the privacy icons.  `true` redraws the icons in the app bar.
4942             updatePrivacyIcons(true);
4943
4944             // Get a handle for the input method manager.
4945             InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
4946
4947             // Remove the lint warning below that the input method manager might be null.
4948             assert inputMethodManager != null;
4949
4950             // Get the current URL.
4951             String url = currentWebView.getUrl();
4952
4953             // Update the URL edit text if not loading a new intent.  Otherwise, this will be handled by `onPageStarted()` (if called) and `onPageFinished()`.
4954             if (!loadingNewIntent) {  // A new intent is not being loaded.
4955                 if ((url == null) || url.equals("about:blank")) {  // The WebView is blank.
4956                     // Display the hint in the URL edit text.
4957                     urlEditText.setText("");
4958
4959                     // Request focus for the URL text box.
4960                     urlEditText.requestFocus();
4961
4962                     // Display the keyboard.
4963                     inputMethodManager.showSoftInput(urlEditText, 0);
4964                 } else {  // The WebView has a loaded URL.
4965                     // Clear the focus from the URL text box.
4966                     urlEditText.clearFocus();
4967
4968                     // Hide the soft keyboard.
4969                     inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
4970
4971                     // Display the current URL in the URL text box.
4972                     urlEditText.setText(url);
4973
4974                     // Highlight the URL text.
4975                     highlightUrlText();
4976                 }
4977             } else {  // A new intent is being loaded.
4978                 // Reset the loading new intent tracker.
4979                 loadingNewIntent = false;
4980             }
4981
4982             // Set the background to indicate the domain settings status.
4983             if (currentWebView.getDomainSettingsApplied()) {
4984                 // Set a background on the URL relative layout to indicate that custom domain settings are being used.
4985                 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.domain_settings_url_background, null));
4986             } else {
4987                 // Remove any background on the URL relative layout.
4988                 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.color.transparent, null));
4989             }
4990         } else {  // The fragment has not been populated.  Try again in 100 milliseconds.
4991             // Create a handler to set the current WebView.
4992             Handler setCurrentWebViewHandler = new Handler();
4993
4994             // Create a runnable to set the current WebView.
4995             Runnable setCurrentWebWebRunnable = () -> {
4996                 // Set the current WebView.
4997                 setCurrentWebView(pageNumber);
4998             };
4999
5000             // Try setting the current WebView again after 100 milliseconds.
5001             setCurrentWebViewHandler.postDelayed(setCurrentWebWebRunnable, 100);
5002         }
5003     }
5004
5005     @SuppressLint("ClickableViewAccessibility")
5006     @Override
5007     public void initializeWebView(NestedScrollWebView nestedScrollWebView, int pageNumber, ProgressBar progressBar, String url, Boolean restoringState) {
5008         // Get a handle for the shared preferences.
5009         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
5010
5011         // Get the WebView theme.
5012         String webViewTheme = sharedPreferences.getString("webview_theme", getString(R.string.webview_theme_default_value));
5013
5014         // Get the WebView theme entry values string array.
5015         String[] webViewThemeEntryValuesStringArray = getResources().getStringArray(R.array.webview_theme_entry_values);
5016
5017         // Apply the WebView theme if supported by the installed WebView.
5018         if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
5019             // Set the WebView theme.  A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
5020             if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) {  // The light theme is selected.
5021                 // Turn off the WebView dark mode.
5022                 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
5023
5024                 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
5025                 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
5026                 nestedScrollWebView.setVisibility(View.VISIBLE);
5027             } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) {  // The dark theme is selected.
5028                 // Turn on the WebView dark mode.
5029                 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
5030             } else {  // The system default theme is selected.
5031                 // Get the current system theme status.
5032                 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
5033
5034                 // Set the WebView theme according to the current system theme status.
5035                 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {  // The system is in day mode.
5036                     // Turn off the WebView dark mode.
5037                     WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
5038
5039                     // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
5040                     // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
5041                     nestedScrollWebView.setVisibility(View.VISIBLE);
5042                 } else {  // The system is in night mode.
5043                     // Turn on the WebView dark mode.
5044                     WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
5045                 }
5046             }
5047         }
5048
5049         // Get a handle for the activity
5050         Activity activity = this;
5051
5052         // Get a handle for the input method manager.
5053         InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
5054
5055         // Instantiate the blocklist helper.
5056         BlocklistHelper blocklistHelper = new BlocklistHelper();
5057
5058         // Remove the lint warning below that the input method manager might be null.
5059         assert inputMethodManager != null;
5060
5061         // Set the app bar scrolling.
5062         nestedScrollWebView.setNestedScrollingEnabled(scrollAppBar);
5063
5064         // Allow pinch to zoom.
5065         nestedScrollWebView.getSettings().setBuiltInZoomControls(true);
5066
5067         // Hide zoom controls.
5068         nestedScrollWebView.getSettings().setDisplayZoomControls(false);
5069
5070         // Don't allow mixed content (HTTP and HTTPS) on the same website.
5071         nestedScrollWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);
5072
5073         // Set the WebView to load in overview mode (zoomed out to the maximum width).
5074         nestedScrollWebView.getSettings().setLoadWithOverviewMode(true);
5075
5076         // Explicitly disable geolocation.
5077         nestedScrollWebView.getSettings().setGeolocationEnabled(false);
5078
5079         // Allow loading of file:// URLs.  This is necessary for opening MHT web archives, which are copies into a temporary cache location.
5080         nestedScrollWebView.getSettings().setAllowFileAccess(true);
5081
5082         // Create a double-tap gesture detector to toggle full-screen mode.
5083         GestureDetector doubleTapGestureDetector = new GestureDetector(getApplicationContext(), new GestureDetector.SimpleOnGestureListener() {
5084             // Override `onDoubleTap()`.  All other events are handled using the default settings.
5085             @Override
5086             public boolean onDoubleTap(MotionEvent event) {
5087                 if (fullScreenBrowsingModeEnabled) {  // Only process the double-tap if full screen browsing mode is enabled.
5088                     // Toggle the full screen browsing mode tracker.
5089                     inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
5090
5091                     // Toggle the full screen browsing mode.
5092                     if (inFullScreenBrowsingMode) {  // Switch to full screen mode.
5093                         // Hide the app bar if specified.
5094                         if (hideAppBar) {  // The app bar is hidden.
5095                             // Close the find on page bar if it is visible.
5096                             closeFindOnPage(null);
5097
5098                             // Hide the tab linear layout.
5099                             tabsLinearLayout.setVisibility(View.GONE);
5100
5101                             // Hide the action bar.
5102                             actionBar.hide();
5103
5104                             // Set layout and scrolling parameters according to the position of the app bar.
5105                             if (bottomAppBar) {  // The app bar is at the bottom.
5106                                 // Reset the WebView padding to fill the available space.
5107                                 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5108                             } else {  // The app bar is at the top.
5109                                 // Check to see if the app bar is normally scrolled.
5110                                 if (scrollAppBar) {  // The app bar is scrolled when it is displayed.
5111                                     // Get the swipe refresh layout parameters.
5112                                     CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
5113
5114                                     // Remove the off-screen scrolling layout.
5115                                     swipeRefreshLayoutParams.setBehavior(null);
5116                                 } else {  // The app bar is not scrolled when it is displayed.
5117                                     // Remove the padding from the top of the swipe refresh layout.
5118                                     swipeRefreshLayout.setPadding(0, 0, 0, 0);
5119
5120                                     // The swipe refresh circle must be moved above the now removed status bar location.
5121                                     swipeRefreshLayout.setProgressViewOffset(false, -200, defaultProgressViewEndOffset);
5122                                 }
5123                             }
5124                         } else {  // The app bar is not hidden.
5125                             // Adjust the UI for the bottom app bar.
5126                             if (bottomAppBar) {
5127                                 // Adjust the UI according to the scrolling of the app bar.
5128                                 if (scrollAppBar) {
5129                                     // Reset the WebView padding to fill the available space.
5130                                     swipeRefreshLayout.setPadding(0, 0, 0, 0);
5131                                 } else {
5132                                     // Move the WebView above the app bar layout.
5133                                     swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight);
5134                                 }
5135                             }
5136                         }
5137
5138                         /* Hide the system bars.
5139                          * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5140                          * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5141                          * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5142                          * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5143                          */
5144                         rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5145                                 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5146                     } else {  // Switch to normal viewing mode.
5147                         // Show the app bar if it was hidden.
5148                         if (hideAppBar) {
5149                             // Show the tab linear layout.
5150                             tabsLinearLayout.setVisibility(View.VISIBLE);
5151
5152                             // Show the action bar.
5153                             actionBar.show();
5154                         }
5155
5156                         // Set layout and scrolling parameters according to the position of the app bar.
5157                         if (bottomAppBar) {  // The app bar is at the bottom.
5158                             // Adjust the UI.
5159                             if (scrollAppBar) {
5160                                 // Reset the WebView padding to fill the available space.
5161                                 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5162                             } else {
5163                                 // Move the WebView above the app bar layout.
5164                                 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight);
5165                             }
5166                         } else {  // The app bar is at the top.
5167                             // Check to see if the app bar is normally scrolled.
5168                             if (scrollAppBar) {  // The app bar is scrolled when it is displayed.
5169                                 // Get the swipe refresh layout parameters.
5170                                 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
5171
5172                                 // Add the off-screen scrolling layout.
5173                                 swipeRefreshLayoutParams.setBehavior(new AppBarLayout.ScrollingViewBehavior());
5174                             } else {  // The app bar is not scrolled when it is displayed.
5175                                 // The swipe refresh layout must be manually moved below the app bar layout.
5176                                 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0);
5177
5178                                 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5179                                 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight);
5180                             }
5181                         }
5182
5183                         // Remove the `SYSTEM_UI` flags from the root frame layout.
5184                         rootFrameLayout.setSystemUiVisibility(0);
5185                     }
5186
5187                     // Consume the double-tap.
5188                     return true;
5189                 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
5190                     return false;
5191                 }
5192             }
5193
5194             @Override
5195             public boolean onFling(MotionEvent motionEvent1, MotionEvent motionEvent2, float velocityX, float velocityY) {
5196                 // Scroll the bottom app bar if enabled.
5197                 if (bottomAppBar && scrollAppBar && !objectAnimator.isRunning()) {
5198                     // Calculate the Y change.
5199                     float motionY = motionEvent2.getY() - motionEvent1.getY();
5200
5201                     // Scroll the app bar if the change is greater than 100 pixels.
5202                     if (motionY > 50) {
5203                         // Animate the bottom app bar onto the screen.
5204                         objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0);
5205                     } else if (motionY < -50) {
5206                         // Animate the bottom app bar off the screen.
5207                         objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", appBarLayout.getHeight());
5208                     }
5209
5210                     // Make it so.
5211                     objectAnimator.start();
5212                 }
5213
5214                 // Do not consume the event.
5215                 return false;
5216             }
5217         });
5218
5219         // Pass all touch events on the WebView through the double-tap gesture detector.
5220         nestedScrollWebView.setOnTouchListener((View view, MotionEvent event) -> {
5221             // Call `performClick()` on the view, which is required for accessibility.
5222             view.performClick();
5223
5224             // Send the event to the gesture detector.
5225             return doubleTapGestureDetector.onTouchEvent(event);
5226         });
5227
5228         // Register the WebView for a context menu.  This is used to see link targets and download images.
5229         registerForContextMenu(nestedScrollWebView);
5230
5231         // Allow the downloading of files.
5232         nestedScrollWebView.setDownloadListener((String downloadUrl, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
5233             // Check the download preference.
5234             if (downloadWithExternalApp) {  // Download with an external app.
5235                 downloadUrlWithExternalApp(downloadUrl);
5236             } else {  // Handle the download inside of Privacy Browser.
5237                 // Define a formatted file size string.
5238                 String formattedFileSizeString;
5239
5240                 // Process the content length if it contains data.
5241                 if (contentLength > 0) {  // The content length is greater than 0.
5242                     // Format the content length as a string.
5243                     formattedFileSizeString = NumberFormat.getInstance().format(contentLength) + " " + getString(R.string.bytes);
5244                 } else {  // The content length is not greater than 0.
5245                     // Set the formatted file size string to be `unknown size`.
5246                     formattedFileSizeString = getString(R.string.unknown_size);
5247                 }
5248
5249                 // Get the file name from the content disposition.
5250                 String fileNameString = PrepareSaveDialog.getFileNameFromHeaders(this, contentDisposition, mimetype, downloadUrl);
5251
5252                 // Instantiate the save dialog.
5253                 DialogFragment saveDialogFragment = SaveDialog.saveUrl(downloadUrl, formattedFileSizeString, fileNameString, userAgent,
5254                         nestedScrollWebView.getAcceptCookies());
5255
5256                 // Try to show the dialog.  The download listener continues to function even when the WebView is paused.  Attempting to display a dialog in that state leads to a crash.
5257                 try {
5258                     // Show the save dialog.  It must be named `save_dialog` so that the file picker can update the file name.
5259                     saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
5260                 } catch (Exception exception) {  // The dialog could not be shown.
5261                     // Add the dialog to the pending dialog array list.  It will be displayed in `onStart()`.
5262                     pendingDialogsArrayList.add(new PendingDialog(saveDialogFragment, getString(R.string.save_dialog)));
5263                 }
5264             }
5265         });
5266
5267         // Update the find on page count.
5268         nestedScrollWebView.setFindListener(new WebView.FindListener() {
5269             // Get a handle for `findOnPageCountTextView`.
5270             final TextView findOnPageCountTextView = findViewById(R.id.find_on_page_count_textview);
5271
5272             @Override
5273             public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
5274                 if ((isDoneCounting) && (numberOfMatches == 0)) {  // There are no matches.
5275                     // Set `findOnPageCountTextView` to `0/0`.
5276                     findOnPageCountTextView.setText(R.string.zero_of_zero);
5277                 } else if (isDoneCounting) {  // There are matches.
5278                     // `activeMatchOrdinal` is zero-based.
5279                     int activeMatch = activeMatchOrdinal + 1;
5280
5281                     // Build the match string.
5282                     String matchString = activeMatch + "/" + numberOfMatches;
5283
5284                     // Set `findOnPageCountTextView`.
5285                     findOnPageCountTextView.setText(matchString);
5286                 }
5287             }
5288         });
5289
5290         // Process scroll changes.
5291         nestedScrollWebView.setOnScrollChangeListener((view, scrollX, scrollY, oldScrollX, oldScrollY) -> {
5292             // Set the swipe to refresh status.
5293             if (nestedScrollWebView.getSwipeToRefresh()) {
5294                 // Only enable swipe to refresh if the WebView is scrolled to the top.
5295                 swipeRefreshLayout.setEnabled(nestedScrollWebView.getScrollY() == 0);
5296             } else {
5297                 // Disable swipe to refresh.
5298                 swipeRefreshLayout.setEnabled(false);
5299             }
5300
5301             // Reinforce the system UI visibility flags if in full screen browsing mode.
5302             // This hides the status and navigation bars, which are displayed if other elements are shown, like dialog boxes, the options menu, or the keyboard.
5303             if (inFullScreenBrowsingMode) {
5304                 /* Hide the system bars.
5305                  * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5306                  * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5307                  * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5308                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5309                  */
5310                 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5311                         View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5312             }
5313         });
5314
5315         // Set the web chrome client.
5316         nestedScrollWebView.setWebChromeClient(new WebChromeClient() {
5317             // Update the progress bar when a page is loading.
5318             @Override
5319             public void onProgressChanged(WebView view, int progress) {
5320                 // Update the progress bar.
5321                 progressBar.setProgress(progress);
5322
5323                 // Set the visibility of the progress bar.
5324                 if (progress < 100) {
5325                     // Show the progress bar.
5326                     progressBar.setVisibility(View.VISIBLE);
5327                 } else {
5328                     // Hide the progress bar.
5329                     progressBar.setVisibility(View.GONE);
5330
5331                     //Stop the swipe to refresh indicator if it is running
5332                     swipeRefreshLayout.setRefreshing(false);
5333
5334                     // Make the current WebView visible.  If this is a new tab, the current WebView would have been created invisible in `webview_framelayout` to prevent a white background splash in night mode.
5335                     nestedScrollWebView.setVisibility(View.VISIBLE);
5336                 }
5337             }
5338
5339             // Set the favorite icon when it changes.
5340             @Override
5341             public void onReceivedIcon(WebView view, Bitmap icon) {
5342                 // Only update the favorite icon if the website has finished loading.
5343                 if (progressBar.getVisibility() == View.GONE) {
5344                     // Store the new favorite icon.
5345                     nestedScrollWebView.setFavoriteOrDefaultIcon(icon);
5346
5347                     // Get the current page position.
5348                     int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5349
5350                     // Get the current tab.
5351                     TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
5352
5353                     // Check to see if the tab has been populated.
5354                     if (tab != null) {
5355                         // Get the custom view from the tab.
5356                         View tabView = tab.getCustomView();
5357
5358                         // Check to see if the custom tab view has been populated.
5359                         if (tabView != null) {
5360                             // Get the favorite icon image view from the tab.
5361                             ImageView tabFavoriteIconImageView = tabView.findViewById(R.id.favorite_icon_imageview);
5362
5363                             // Display the favorite icon in the tab.
5364                             tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
5365                         }
5366                     }
5367                 }
5368             }
5369
5370             // Save a copy of the title when it changes.
5371             @Override
5372             public void onReceivedTitle(WebView view, String title) {
5373                 // Get the current page position.
5374                 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5375
5376                 // Get the current tab.
5377                 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
5378
5379                 // Only populate the title text view if the tab has been fully created.
5380                 if (tab != null) {
5381                     // Get the custom view from the tab.
5382                     View tabView = tab.getCustomView();
5383
5384                     // Only populate the title text view if the tab view has been fully populated.
5385                     if (tabView != null) {
5386                         // Get the title text view from the tab.
5387                         TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
5388
5389                         // Set the title according to the URL.
5390                         if (title.equals("about:blank")) {
5391                             // Set the title to indicate a new tab.
5392                             tabTitleTextView.setText(R.string.new_tab);
5393                         } else {
5394                             // Set the title as the tab text.
5395                             tabTitleTextView.setText(title);
5396                         }
5397                     }
5398                 }
5399             }
5400
5401             // Enter full screen video.
5402             @Override
5403             public void onShowCustomView(View video, CustomViewCallback callback) {
5404                 // Set the full screen video flag.
5405                 displayingFullScreenVideo = true;
5406
5407                 // Hide the keyboard.
5408                 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
5409
5410                 // Hide the coordinator layout.
5411                 coordinatorLayout.setVisibility(View.GONE);
5412
5413                 /* Hide the system bars.
5414                  * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5415                  * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5416                  * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5417                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5418                  */
5419                 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5420                         View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5421
5422                 // Disable the sliding drawers.
5423                 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
5424
5425                 // Add the video view to the full screen video frame layout.
5426                 fullScreenVideoFrameLayout.addView(video);
5427
5428                 // Show the full screen video frame layout.
5429                 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
5430
5431                 // Disable the screen timeout while the video is playing.  YouTube does this automatically, but not all other videos do.
5432                 fullScreenVideoFrameLayout.setKeepScreenOn(true);
5433             }
5434
5435             // Exit full screen video.
5436             @Override
5437             public void onHideCustomView() {
5438                 // Exit the full screen video.
5439                 exitFullScreenVideo();
5440             }
5441
5442             // Upload files.
5443             @Override
5444             public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
5445                 // Store the file path callback.
5446                 fileChooserCallback = filePathCallback;
5447
5448                 // Create an intent to open a chooser based on the file chooser parameters.
5449                 Intent fileChooserIntent = fileChooserParams.createIntent();
5450
5451                 // Get a handle for the package manager.
5452                 PackageManager packageManager = getPackageManager();
5453
5454                 // Check to see if the file chooser intent resolves to an installed package.
5455                 if (fileChooserIntent.resolveActivity(packageManager) != null) {  // The file chooser intent is fine.
5456                     // Start the file chooser intent.
5457                     startActivityForResult(fileChooserIntent, BROWSE_FILE_UPLOAD_REQUEST_CODE);
5458                 } else {  // The file chooser intent will cause a crash.
5459                     // Create a generic intent to open a chooser.
5460                     Intent genericFileChooserIntent = new Intent(Intent.ACTION_GET_CONTENT);
5461
5462                     // Request an openable file.
5463                     genericFileChooserIntent.addCategory(Intent.CATEGORY_OPENABLE);
5464
5465                     // Set the file type to everything.
5466                     genericFileChooserIntent.setType("*/*");
5467
5468                     // Start the generic file chooser intent.
5469                     startActivityForResult(genericFileChooserIntent, BROWSE_FILE_UPLOAD_REQUEST_CODE);
5470                 }
5471                 return true;
5472             }
5473         });
5474
5475         nestedScrollWebView.setWebViewClient(new WebViewClient() {
5476             // `shouldOverrideUrlLoading` makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
5477             // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
5478             @Override
5479             public boolean shouldOverrideUrlLoading(WebView view, String url) {
5480                 // Sanitize the url.
5481                 url = sanitizeUrl(url);
5482
5483                 // Handle the URL according to the type.
5484                 if (url.startsWith("http")) {  // Load the URL in Privacy Browser.
5485                     // Load the URL.  By using `loadUrl()`, instead of `loadUrlFromBase()`, the Referer header will never be sent.
5486                     loadUrl(nestedScrollWebView, url);
5487
5488                     // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
5489                     // Custom headers cannot be added if false is returned and the WebView handles the loading of the URL.
5490                     return true;
5491                 } else if (url.startsWith("mailto:")) {  // Load the email address in an external email program.
5492                     // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
5493                     Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
5494
5495                     // Parse the url and set it as the data for the intent.
5496                     emailIntent.setData(Uri.parse(url));
5497
5498                     // Open the email program in a new task instead of as part of Privacy Browser.
5499                     emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5500
5501                     try {
5502                         // Make it so.
5503                         startActivity(emailIntent);
5504                     } catch (ActivityNotFoundException exception) {
5505                         // Display a snackbar.
5506                         Snackbar.make(currentWebView, getString(R.string.error) + "  " + exception, Snackbar.LENGTH_INDEFINITE).show();
5507                     }
5508
5509
5510                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5511                     return true;
5512                 } else if (url.startsWith("tel:")) {  // Load the phone number in the dialer.
5513                     // Open the dialer and load the phone number, but wait for the user to place the call.
5514                     Intent dialIntent = new Intent(Intent.ACTION_DIAL);
5515
5516                     // Add the phone number to the intent.
5517                     dialIntent.setData(Uri.parse(url));
5518
5519                     // Open the dialer in a new task instead of as part of Privacy Browser.
5520                     dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5521
5522                     try {
5523                         // Make it so.
5524                         startActivity(dialIntent);
5525                     } catch (ActivityNotFoundException exception) {
5526                         // Display a snackbar.
5527                         Snackbar.make(currentWebView, getString(R.string.error) + "  " + exception, Snackbar.LENGTH_INDEFINITE).show();
5528                     }
5529
5530                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5531                     return true;
5532                 } else {  // Load a system chooser to select an app that can handle the URL.
5533                     // Open an app that can handle the URL.
5534                     Intent genericIntent = new Intent(Intent.ACTION_VIEW);
5535
5536                     // Add the URL to the intent.
5537                     genericIntent.setData(Uri.parse(url));
5538
5539                     // List all apps that can handle the URL instead of just opening the first one.
5540                     genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
5541
5542                     // Open the app in a new task instead of as part of Privacy Browser.
5543                     genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5544
5545                     // Start the app or display a snackbar if no app is available to handle the URL.
5546                     try {
5547                         startActivity(genericIntent);
5548                     } catch (ActivityNotFoundException exception) {
5549                         Snackbar.make(nestedScrollWebView, getString(R.string.unrecognized_url) + "  " + url, Snackbar.LENGTH_SHORT).show();
5550                     }
5551
5552                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5553                     return true;
5554                 }
5555             }
5556
5557             // Check requests against the block lists.  The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
5558             @Override
5559             public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest webResourceRequest) {
5560                 // Get the URL.
5561                 String url = webResourceRequest.getUrl().toString();
5562
5563                 // Check to see if the resource request is for the main URL.
5564                 if (url.equals(nestedScrollWebView.getCurrentUrl())) {
5565                     // `return null` loads the resource request, which should never be blocked if it is the main URL.
5566                     return null;
5567                 }
5568
5569                 // Wait until the blocklists have been populated.  When Privacy Browser is being resumed after having the process killed in the background it will try to load the URLs immediately.
5570                 while (ultraPrivacy == null) {
5571                     // The wait must be synchronized, which only lets one thread run on it at a time, or `java.lang.IllegalMonitorStateException` is thrown.
5572                     synchronized (this) {
5573                         try {
5574                             // Check to see if the blocklists have been populated after 100 ms.
5575                             wait(100);
5576                         } catch (InterruptedException exception) {
5577                             // Do nothing.
5578                         }
5579                     }
5580                 }
5581
5582                 // Create an empty web resource response to be used if the resource request is blocked.
5583                 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
5584
5585                 // Reset the whitelist results tracker.
5586                 String[] whitelistResultStringArray = null;
5587
5588                 // Initialize the third party request tracker.
5589                 boolean isThirdPartyRequest = false;
5590
5591                 // Get the current URL.  `.getUrl()` throws an error because operations on the WebView cannot be made from this thread.
5592                 String currentBaseDomain = nestedScrollWebView.getCurrentDomainName();
5593
5594                 // Store a copy of the current domain for use in later requests.
5595                 String currentDomain = currentBaseDomain;
5596
5597                 // Get the request host name.
5598                 String requestBaseDomain = webResourceRequest.getUrl().getHost();
5599
5600                 // Only check for third-party requests if the current base domain is not empty and the request domain is not null.
5601                 if (!currentBaseDomain.isEmpty() && (requestBaseDomain != null)) {
5602                     // Determine the current base domain.
5603                     while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) {  // There is at least one subdomain.
5604                         // Remove the first subdomain.
5605                         currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
5606                     }
5607
5608                     // Determine the request base domain.
5609                     while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) {  // There is at least one subdomain.
5610                         // Remove the first subdomain.
5611                         requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
5612                     }
5613
5614                     // Update the third party request tracker.
5615                     isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
5616                 }
5617
5618                 // Get the current WebView page position.
5619                 int webViewPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5620
5621                 // Determine if the WebView is currently displayed.
5622                 boolean webViewDisplayed = (webViewPagePosition == tabLayout.getSelectedTabPosition());
5623
5624                 // Block third-party requests if enabled.
5625                 if (isThirdPartyRequest && nestedScrollWebView.getBlockAllThirdPartyRequests()) {
5626                     // Add the result to the resource requests.
5627                     nestedScrollWebView.addResourceRequest(new String[]{BlocklistHelper.REQUEST_THIRD_PARTY, url});
5628
5629                     // Increment the blocked requests counters.
5630                     nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5631                     nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS);
5632
5633                     // Update the titles of the blocklist menu items if the WebView is currently displayed.
5634                     if (webViewDisplayed) {
5635                         // Updating the UI must be run from the UI thread.
5636                         activity.runOnUiThread(() -> {
5637                             // Update the menu item titles.
5638                             navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5639
5640                             // Update the options menu if it has been populated.
5641                             if (optionsMenu != null) {
5642                                 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5643                                 optionsBlockAllThirdPartyRequestsMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " +
5644                                         getString(R.string.block_all_third_party_requests));
5645                             }
5646                         });
5647                     }
5648
5649                     // Return an empty web resource response.
5650                     return emptyWebResourceResponse;
5651                 }
5652
5653                 // Check UltraList if it is enabled.
5654                 if (nestedScrollWebView.getUltraListEnabled()) {
5655                     // Check the URL against UltraList.
5656                     String[] ultraListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraList);
5657
5658                     // Process the UltraList results.
5659                     if (ultraListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) {  // The resource request matched UltraList's blacklist.
5660                         // Add the result to the resource requests.
5661                         nestedScrollWebView.addResourceRequest(new String[] {ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]});
5662
5663                         // Increment the blocked requests counters.
5664                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5665                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRALIST);
5666
5667                         // Update the titles of the blocklist menu items if the WebView is currently displayed.
5668                         if (webViewDisplayed) {
5669                             // Updating the UI must be run from the UI thread.
5670                             activity.runOnUiThread(() -> {
5671                                 // Update the menu item titles.
5672                                 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5673
5674                                 // Update the options menu if it has been populated.
5675                                 if (optionsMenu != null) {
5676                                     optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5677                                     optionsUltraListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRALIST) + " - " + getString(R.string.ultralist));
5678                                 }
5679                             });
5680                         }
5681
5682                         // The resource request was blocked.  Return an empty web resource response.
5683                         return emptyWebResourceResponse;
5684                     } else if (ultraListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) {  // The resource request matched UltraList's whitelist.
5685                         // Add a whitelist entry to the resource requests array.
5686                         nestedScrollWebView.addResourceRequest(new String[] {ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]});
5687
5688                         // The resource request has been allowed by UltraPrivacy.  `return null` loads the requested resource.
5689                         return null;
5690                     }
5691                 }
5692
5693                 // Check UltraPrivacy if it is enabled.
5694                 if (nestedScrollWebView.getUltraPrivacyEnabled()) {
5695                     // Check the URL against UltraPrivacy.
5696                     String[] ultraPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraPrivacy);
5697
5698                     // Process the UltraPrivacy results.
5699                     if (ultraPrivacyResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) {  // The resource request matched UltraPrivacy's blacklist.
5700                         // Add the result to the resource requests.
5701                         nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5702                                 ultraPrivacyResults[5]});
5703
5704                         // Increment the blocked requests counters.
5705                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5706                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRAPRIVACY);
5707
5708                         // Update the titles of the blocklist menu items if the WebView is currently displayed.
5709                         if (webViewDisplayed) {
5710                             // Updating the UI must be run from the UI thread.
5711                             activity.runOnUiThread(() -> {
5712                                 // Update the menu item titles.
5713                                 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5714
5715                                 // Update the options menu if it has been populated.
5716                                 if (optionsMenu != null) {
5717                                     optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5718                                     optionsUltraPrivacyMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRAPRIVACY) + " - " + getString(R.string.ultraprivacy));
5719                                 }
5720                             });
5721                         }
5722
5723                         // The resource request was blocked.  Return an empty web resource response.
5724                         return emptyWebResourceResponse;
5725                     } else if (ultraPrivacyResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) {  // The resource request matched UltraPrivacy's whitelist.
5726                         // Add a whitelist entry to the resource requests array.
5727                         nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5728                                 ultraPrivacyResults[5]});
5729
5730                         // The resource request has been allowed by UltraPrivacy.  `return null` loads the requested resource.
5731                         return null;
5732                     }
5733                 }
5734
5735                 // Check EasyList if it is enabled.
5736                 if (nestedScrollWebView.getEasyListEnabled()) {
5737                     // Check the URL against EasyList.
5738                     String[] easyListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyList);
5739
5740                     // Process the EasyList results.
5741                     if (easyListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) {  // The resource request matched EasyList's blacklist.
5742                         // Add the result to the resource requests.
5743                         nestedScrollWebView.addResourceRequest(new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]});
5744
5745                         // Increment the blocked requests counters.
5746                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5747                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASYLIST);
5748
5749                         // Update the titles of the blocklist menu items if the WebView is currently displayed.
5750                         if (webViewDisplayed) {
5751                             // Updating the UI must be run from the UI thread.
5752                             activity.runOnUiThread(() -> {
5753                                 // Update the menu item titles.
5754                                 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5755
5756                                 // Update the options menu if it has been populated.
5757                                 if (optionsMenu != null) {
5758                                     optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5759                                     optionsEasyListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASYLIST) + " - " + getString(R.string.easylist));
5760                                 }
5761                             });
5762                         }
5763
5764                         // The resource request was blocked.  Return an empty web resource response.
5765                         return emptyWebResourceResponse;
5766                     } else if (easyListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) {  // The resource request matched EasyList's whitelist.
5767                         // Update the whitelist result string array tracker.
5768                         whitelistResultStringArray = new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]};
5769                     }
5770                 }
5771
5772                 // Check EasyPrivacy if it is enabled.
5773                 if (nestedScrollWebView.getEasyPrivacyEnabled()) {
5774                     // Check the URL against EasyPrivacy.
5775                     String[] easyPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyPrivacy);
5776
5777                     // Process the EasyPrivacy results.
5778                     if (easyPrivacyResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) {  // The resource request matched EasyPrivacy's blacklist.
5779                         // Add the result to the resource requests.
5780                         nestedScrollWebView.addResourceRequest(new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4],
5781                                 easyPrivacyResults[5]});
5782
5783                         // Increment the blocked requests counters.
5784                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5785                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASYPRIVACY);
5786
5787                         // Update the titles of the blocklist menu items if the WebView is currently displayed.
5788                         if (webViewDisplayed) {
5789                             // Updating the UI must be run from the UI thread.
5790                             activity.runOnUiThread(() -> {
5791                                 // Update the menu item titles.
5792                                 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5793
5794                                 // Update the options menu if it has been populated.
5795                                 if (optionsMenu != null) {
5796                                     optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5797                                     optionsEasyPrivacyMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASYPRIVACY) + " - " + getString(R.string.easyprivacy));
5798                                 }
5799                             });
5800                         }
5801
5802                         // The resource request was blocked.  Return an empty web resource response.
5803                         return emptyWebResourceResponse;
5804                     } else if (easyPrivacyResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) {  // The resource request matched EasyPrivacy's whitelist.
5805                         // Update the whitelist result string array tracker.
5806                         whitelistResultStringArray = new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5]};
5807                     }
5808                 }
5809
5810                 // Check Fanboy’s Annoyance List if it is enabled.
5811                 if (nestedScrollWebView.getFanboysAnnoyanceListEnabled()) {
5812                     // Check the URL against Fanboy's Annoyance List.
5813                     String[] fanboysAnnoyanceListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList);
5814
5815                     // Process the Fanboy's Annoyance List results.
5816                     if (fanboysAnnoyanceListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) {  // The resource request matched Fanboy's Annoyance List's blacklist.
5817                         // Add the result to the resource requests.
5818                         nestedScrollWebView.addResourceRequest(new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5819                                 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]});
5820
5821                         // Increment the blocked requests counters.
5822                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5823                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST);
5824
5825                         // Update the titles of the blocklist menu items if the WebView is currently displayed.
5826                         if (webViewDisplayed) {
5827                             // Updating the UI must be run from the UI thread.
5828                             activity.runOnUiThread(() -> {
5829                                 // Update the menu item titles.
5830                                 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5831
5832                                 // Update the options menu if it has been populated.
5833                                 if (optionsMenu != null) {
5834                                     optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5835                                     optionsFanboysAnnoyanceListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " +
5836                                             getString(R.string.fanboys_annoyance_list));
5837                                 }
5838                             });
5839                         }
5840
5841                         // The resource request was blocked.  Return an empty web resource response.
5842                         return emptyWebResourceResponse;
5843                     } else if (fanboysAnnoyanceListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)){  // The resource request matched Fanboy's Annoyance List's whitelist.
5844                         // Update the whitelist result string array tracker.
5845                         whitelistResultStringArray = new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5846                                 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]};
5847                     }
5848                 } else if (nestedScrollWebView.getFanboysSocialBlockingListEnabled()) {  // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
5849                     // Check the URL against Fanboy's Annoyance List.
5850                     String[] fanboysSocialListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysSocialList);
5851
5852                     // Process the Fanboy's Social Blocking List results.
5853                     if (fanboysSocialListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) {  // The resource request matched Fanboy's Social Blocking List's blacklist.
5854                         // Add the result to the resource requests.
5855                         nestedScrollWebView.addResourceRequest(new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5856                                 fanboysSocialListResults[4], fanboysSocialListResults[5]});
5857
5858                         // Increment the blocked requests counters.
5859                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5860                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST);
5861
5862                         // Update the titles of the blocklist menu items if the WebView is currently displayed.
5863                         if (webViewDisplayed) {
5864                             // Updating the UI must be run from the UI thread.
5865                             activity.runOnUiThread(() -> {
5866                                 // Update the menu item titles.
5867                                 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5868
5869                                 // Update the options menu if it has been populated.
5870                                 if (optionsMenu != null) {
5871                                     optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5872                                     optionsFanboysSocialBlockingListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " +
5873                                             getString(R.string.fanboys_social_blocking_list));
5874                                 }
5875                             });
5876                         }
5877
5878                         // The resource request was blocked.  Return an empty web resource response.
5879                         return emptyWebResourceResponse;
5880                     } else if (fanboysSocialListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) {  // The resource request matched Fanboy's Social Blocking List's whitelist.
5881                         // Update the whitelist result string array tracker.
5882                         whitelistResultStringArray = new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5883                                 fanboysSocialListResults[4], fanboysSocialListResults[5]};
5884                     }
5885                 }
5886
5887                 // Add the request to the log because it hasn't been processed by any of the previous checks.
5888                 if (whitelistResultStringArray != null) {  // The request was processed by a whitelist.
5889                     nestedScrollWebView.addResourceRequest(whitelistResultStringArray);
5890                 } else {  // The request didn't match any blocklist entry.  Log it as a default request.
5891                     nestedScrollWebView.addResourceRequest(new String[]{BlocklistHelper.REQUEST_DEFAULT, url});
5892                 }
5893
5894                 // The resource request has not been blocked.  `return null` loads the requested resource.
5895                 return null;
5896             }
5897
5898             // Handle HTTP authentication requests.
5899             @Override
5900             public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
5901                 // Store the handler.
5902                 nestedScrollWebView.setHttpAuthHandler(handler);
5903
5904                 // Instantiate an HTTP authentication dialog.
5905                 DialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm, nestedScrollWebView.getWebViewFragmentId());
5906
5907                 // Show the HTTP authentication dialog.
5908                 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
5909             }
5910
5911             @Override
5912             public void onPageStarted(WebView view, String url, Bitmap favicon) {
5913                 // Get the app bar layout height.  This can't be done in `applyAppSettings()` because the app bar is not yet populated there.
5914                 // This should only be populated if it is greater than 0 because otherwise it will be reset to 0 if the app bar is hidden in full screen browsing mode.
5915                 if (appBarLayout.getHeight() > 0) appBarHeight = appBarLayout.getHeight();
5916
5917                 // Set the padding and layout settings according to the position of the app bar.
5918                 if (bottomAppBar) {  // The app bar is on the bottom.
5919                     // Adjust the UI.
5920                     if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) {  // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
5921                         // Reset the WebView padding to fill the available space.
5922                         swipeRefreshLayout.setPadding(0, 0, 0, 0);
5923                     } else {  // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
5924                         // Move the WebView above the app bar layout.
5925                         swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight);
5926                     }
5927                 } else {  // The app bar is on the top.
5928                     // Set the top padding of the swipe refresh layout according to the app bar scrolling preference.  This can't be done in `appAppSettings()` because the app bar is not yet populated there.
5929                     if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) {
5930                         // No padding is needed because it will automatically be placed below the app bar layout due to the scrolling layout behavior.
5931                         swipeRefreshLayout.setPadding(0, 0, 0, 0);
5932
5933                         // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5934                         swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10, defaultProgressViewEndOffset);
5935                     } else {
5936                         // The swipe refresh layout must be manually moved below the app bar layout.
5937                         swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0);
5938
5939                         // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5940                         swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight);
5941                     }
5942                 }
5943
5944                 // Reset the list of resource requests.
5945                 nestedScrollWebView.clearResourceRequests();
5946
5947                 // Reset the requests counters.
5948                 nestedScrollWebView.resetRequestsCounters();
5949
5950                 // Get the current page position.
5951                 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5952
5953                 // Update the URL text bar if the page is currently selected and the URL edit text is not currently being edited.
5954                 if ((tabLayout.getSelectedTabPosition() == currentPagePosition) && !urlEditText.hasFocus()) {
5955                     // Display the formatted URL text.
5956                     urlEditText.setText(url);
5957
5958                     // Apply text highlighting to the URL text box.
5959                     highlightUrlText();
5960
5961                     // Hide the keyboard.
5962                     inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
5963                 }
5964
5965                 // Reset the list of host IP addresses.
5966                 nestedScrollWebView.setCurrentIpAddresses("");
5967
5968                 // Get a URI for the current URL.
5969                 Uri currentUri = Uri.parse(url);
5970
5971                 // Get the IP addresses for the host.
5972                 new GetHostIpAddresses(activity, getSupportFragmentManager(), nestedScrollWebView).execute(currentUri.getHost());
5973
5974                 // Replace Refresh with Stop if the options menu has been created.  (The first WebView typically begins loading before the menu items are instantiated.)
5975                 if (optionsMenu != null) {
5976                     // Set the title.
5977                     optionsRefreshMenuItem.setTitle(R.string.stop);
5978
5979                     // Get the app bar and theme preferences.
5980                     boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false);
5981
5982                     // Set the icon if it is displayed in the AppBar.  Once the minimum API is >= 26, the blue and black icons can be combined with a tint list.
5983                     if (displayAdditionalAppBarIcons) {
5984                         optionsRefreshMenuItem.setIcon(R.drawable.close_blue);
5985                     }
5986                 }
5987             }
5988
5989             @Override
5990             public void onPageFinished(WebView view, String url) {
5991                 // Flush any cookies to persistent storage.  The cookie manager has become very lazy about flushing cookies in recent versions.
5992                 if (nestedScrollWebView.getAcceptCookies()) {
5993                     CookieManager.getInstance().flush();
5994                 }
5995
5996                 // Update the Refresh menu item if the options menu has been created.
5997                 if (optionsMenu != null) {
5998                     // Reset the Refresh title.
5999                     optionsRefreshMenuItem.setTitle(R.string.refresh);
6000
6001                     // Get the app bar and theme preferences.
6002                     boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false);
6003
6004                     // If the icon is displayed in the app bar, reset it according to the theme.
6005                     if (displayAdditionalAppBarIcons) {
6006                         // Set the icon.
6007                         optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled);
6008                     }
6009                 }
6010
6011                 // Clear the cache, history, and logcat if Incognito Mode is enabled.
6012                 if (incognitoModeEnabled) {
6013                     // Clear the cache.  `true` includes disk files.
6014                     nestedScrollWebView.clearCache(true);
6015
6016                     // Clear the back/forward history.
6017                     nestedScrollWebView.clearHistory();
6018
6019                     // Manually delete cache folders.
6020                     try {
6021                         // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
6022                         // which links to `/data/data/com.stoutner.privacybrowser.standard`.
6023                         String privateDataDirectoryString = getApplicationInfo().dataDir;
6024
6025                         // Delete the main cache directory.
6026                         Runtime.getRuntime().exec("rm -rf " + privateDataDirectoryString + "/cache");
6027
6028                         // Delete the secondary `Service Worker` cache directory.
6029                         // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
6030                         Runtime.getRuntime().exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
6031                     } catch (IOException exception) {
6032                         // Do nothing if an error is thrown.
6033                     }
6034
6035                     // Clear the logcat.
6036                     try {
6037                         // Clear the logcat.  `-c` clears the logcat.  `-b all` clears all the buffers (instead of just crash, main, and system).
6038                         Runtime.getRuntime().exec("logcat -b all -c");
6039                     } catch (IOException exception) {
6040                         // Do nothing.
6041                     }
6042                 }
6043
6044                 // Get the current page position.
6045                 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
6046
6047                 // Get the current URL from the nested scroll WebView.  This is more accurate than using the URL passed into the method, which is sometimes not the final one.
6048                 String currentUrl = nestedScrollWebView.getUrl();
6049
6050                 // Get the current tab.
6051                 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
6052
6053                 // Update the URL text bar if the page is currently selected and the user is not currently typing in the URL edit text.
6054                 // Crash records show that, in some crazy way, it is possible for the current URL to be blank at this point.
6055                 // Probably some sort of race condition when Privacy Browser is being resumed.
6056                 if ((tabLayout.getSelectedTabPosition() == currentPagePosition) && !urlEditText.hasFocus() && (currentUrl != null)) {
6057                     // Check to see if the URL is `about:blank`.
6058                     if (currentUrl.equals("about:blank")) {  // The WebView is blank.
6059                         // Display the hint in the URL edit text.
6060                         urlEditText.setText("");
6061
6062                         // Request focus for the URL text box.
6063                         urlEditText.requestFocus();
6064
6065                         // Display the keyboard.
6066                         inputMethodManager.showSoftInput(urlEditText, 0);
6067
6068                         // Apply the domain settings.  This clears any settings from the previous domain.
6069                         applyDomainSettings(nestedScrollWebView, "", true, false, false);
6070
6071                         // Only populate the title text view if the tab has been fully created.
6072                         if (tab != null) {
6073                             // Get the custom view from the tab.
6074                             View tabView = tab.getCustomView();
6075
6076                             // Remove the incorrect warning below that the current tab view might be null.
6077                             assert tabView != null;
6078
6079                             // Get the title text view from the tab.
6080                             TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
6081
6082                             // Set the title as the tab text.
6083                             tabTitleTextView.setText(R.string.new_tab);
6084                         }
6085                     } else {  // The WebView has loaded a webpage.
6086                         // Update the URL edit text if it is not currently being edited.
6087                         if (!urlEditText.hasFocus()) {
6088                             // Sanitize the current URL.  This removes unwanted URL elements that were added by redirects, so that they won't be included if the URL is shared.
6089                             String sanitizedUrl = sanitizeUrl(currentUrl);
6090
6091                             // Display the final URL.  Getting the URL from the WebView instead of using the one provided by `onPageFinished()` makes websites like YouTube function correctly.
6092                             urlEditText.setText(sanitizedUrl);
6093
6094                             // Apply text highlighting to the URL.
6095                             highlightUrlText();
6096                         }
6097
6098                         // Only populate the title text view if the tab has been fully created.
6099                         if (tab != null) {
6100                             // Get the custom view from the tab.
6101                             View tabView = tab.getCustomView();
6102
6103                             // Remove the incorrect warning below that the current tab view might be null.
6104                             assert tabView != null;
6105
6106                             // Get the title text view from the tab.
6107                             TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
6108
6109                             // Set the title as the tab text.  Sometimes `onReceivedTitle()` is not called, especially when navigating history.
6110                             tabTitleTextView.setText(nestedScrollWebView.getTitle());
6111                         }
6112                     }
6113                 }
6114             }
6115
6116             // Handle SSL Certificate errors.  Suppress the lint warning that ignoring the error might be dangerous.
6117             @SuppressLint("WebViewClientOnReceivedSslError")
6118             @Override
6119             public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
6120                 // Get the current website SSL certificate.
6121                 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
6122
6123                 // Extract the individual pieces of information from the current website SSL certificate.
6124                 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
6125                 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
6126                 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
6127                 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
6128                 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
6129                 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
6130                 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
6131                 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
6132
6133                 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
6134                 if (nestedScrollWebView.hasPinnedSslCertificate()) {
6135                     // Get the pinned SSL certificate.
6136                     Pair<String[], Date[]> pinnedSslCertificatePair = nestedScrollWebView.getPinnedSslCertificate();
6137
6138                     // Extract the arrays from the array list.
6139                     String[] pinnedSslCertificateStringArray = pinnedSslCertificatePair.getFirst();
6140                     Date[] pinnedSslCertificateDateArray = pinnedSslCertificatePair.getSecond();
6141
6142                     // Check if the current SSL certificate matches the pinned certificate.
6143                     if (currentWebsiteIssuedToCName.equals(pinnedSslCertificateStringArray[0]) && currentWebsiteIssuedToOName.equals(pinnedSslCertificateStringArray[1]) &&
6144                         currentWebsiteIssuedToUName.equals(pinnedSslCertificateStringArray[2]) && currentWebsiteIssuedByCName.equals(pinnedSslCertificateStringArray[3]) &&
6145                         currentWebsiteIssuedByOName.equals(pinnedSslCertificateStringArray[4]) && currentWebsiteIssuedByUName.equals(pinnedSslCertificateStringArray[5]) &&
6146                         currentWebsiteSslStartDate.equals(pinnedSslCertificateDateArray[0]) && currentWebsiteSslEndDate.equals(pinnedSslCertificateDateArray[1])) {
6147
6148                         // An SSL certificate is pinned and matches the current domain certificate.  Proceed to the website without displaying an error.
6149                         handler.proceed();
6150                     }
6151                 } else {  // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
6152                     // Store the SSL error handler.
6153                     nestedScrollWebView.setSslErrorHandler(handler);
6154
6155                     // Instantiate an SSL certificate error alert dialog.
6156                     DialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error, nestedScrollWebView.getWebViewFragmentId());
6157
6158                     // Try to show the dialog.  The SSL error handler continues to function even when the WebView is paused.  Attempting to display a dialog in that state leads to a crash.
6159                     try {
6160                         // Show the SSL certificate error dialog.
6161                         sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
6162                     } catch (Exception exception) {
6163                         // Add the dialog to the pending dialog array list.  It will be displayed in `onStart()`.
6164                         pendingDialogsArrayList.add(new PendingDialog(sslCertificateErrorDialogFragment, getString(R.string.ssl_certificate_error)));
6165                     }
6166                 }
6167             }
6168         });
6169
6170         // Check to see if the state is being restored.
6171         if (restoringState) {  // The state is being restored.
6172             // Resume the nested scroll WebView JavaScript timers.
6173             nestedScrollWebView.resumeTimers();
6174         } else if (pageNumber == 0) {  // The first page is being loaded.
6175             // Set this nested scroll WebView as the current WebView.
6176             currentWebView = nestedScrollWebView;
6177
6178             // Initialize the URL to load string.
6179             String urlToLoadString;
6180
6181             // Get the intent that started the app.
6182             Intent launchingIntent = getIntent();
6183
6184             // Reset the intent.  This prevents a duplicate tab from being created on restart.
6185             setIntent(new Intent());
6186
6187             // Get the information from the intent.
6188             String launchingIntentAction = launchingIntent.getAction();
6189             Uri launchingIntentUriData = launchingIntent.getData();
6190             String launchingIntentStringExtra = launchingIntent.getStringExtra(Intent.EXTRA_TEXT);
6191
6192             // Parse the launching intent URL.
6193             if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) {  // The intent contains a search string.
6194                 // Create an encoded URL string.
6195                 String encodedUrlString;
6196
6197                 // Sanitize the search input and convert it to a search.
6198                 try {
6199                     encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
6200                 } catch (UnsupportedEncodingException exception) {
6201                     encodedUrlString = "";
6202                 }
6203
6204                 // Store the web search as the URL to load.
6205                 urlToLoadString = searchURL + encodedUrlString;
6206             } else if (launchingIntentUriData != null) {  // The launching intent contains a URL formatted as a URI.
6207                 // Store the URI as a URL.
6208                 urlToLoadString = launchingIntentUriData.toString();
6209             } else if (launchingIntentStringExtra != null) {  // The launching intent contains text that might be a URL.
6210                 // Store the URL.
6211                 urlToLoadString = launchingIntentStringExtra;
6212             } else if (!url.equals("")) {  // The activity has been restarted.
6213                 // Load the saved URL.
6214                 urlToLoadString = url;
6215             } else {  // The is no URL in the intent.
6216                 // Store the homepage to be loaded.
6217                 urlToLoadString = sharedPreferences.getString("homepage", getString(R.string.homepage_default_value));
6218             }
6219
6220             // Load the website if not waiting for the proxy.
6221             if (waitingForProxy) {  // Store the URL to be loaded in the Nested Scroll WebView.
6222                 nestedScrollWebView.setWaitingForProxyUrlString(urlToLoadString);
6223             } else {  // Load the URL.
6224                 loadUrl(nestedScrollWebView, urlToLoadString);
6225             }
6226
6227             // Reset the intent.  This prevents a duplicate tab from being created on a subsequent restart if loading an link from a new intent on restart.
6228             // For example, this prevents a duplicate tab if a link is loaded from the Guide after changing the theme in the guide and then changing the theme again in the main activity.
6229             setIntent(new Intent());
6230         } else {  // This is not the first tab.
6231             // Load the URL.
6232             loadUrl(nestedScrollWebView, url);
6233
6234             // Set the focus and display the keyboard if the URL is blank.
6235             if (url.equals("")) {
6236                 // Request focus for the URL text box.
6237                 urlEditText.requestFocus();
6238
6239                 // Create a display keyboard handler.
6240                 Handler displayKeyboardHandler = new Handler();
6241
6242                 // Create a display keyboard runnable.
6243                 Runnable displayKeyboardRunnable = () -> {
6244                     // Display the keyboard.
6245                     inputMethodManager.showSoftInput(urlEditText, 0);
6246                 };
6247
6248                 // Display the keyboard after 100 milliseconds, which leaves enough time for the tab to transition.
6249                 displayKeyboardHandler.postDelayed(displayKeyboardRunnable, 100);
6250             }
6251         }
6252     }
6253 }