]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/activities/MainWebViewActivity.java
9bea7991873988a291707cced7e440ccb7c40fbf
[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 import kotlin.Pair;
122
123 import com.google.android.material.appbar.AppBarLayout;
124 import com.google.android.material.floatingactionbutton.FloatingActionButton;
125 import com.google.android.material.navigation.NavigationView;
126 import com.google.android.material.snackbar.Snackbar;
127 import com.google.android.material.tabs.TabLayout;
128
129 import com.stoutner.privacybrowser.R;
130 import com.stoutner.privacybrowser.adapters.WebViewPagerAdapter;
131 import com.stoutner.privacybrowser.asynctasks.GetHostIpAddresses;
132 import com.stoutner.privacybrowser.asynctasks.PopulateBlocklists;
133 import com.stoutner.privacybrowser.asynctasks.PrepareSaveDialog;
134 import com.stoutner.privacybrowser.asynctasks.SaveUrl;
135 import com.stoutner.privacybrowser.asynctasks.SaveWebpageImage;
136 import com.stoutner.privacybrowser.dataclasses.PendingDialog;
137 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
138 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
139 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
140 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
141 import com.stoutner.privacybrowser.dialogs.FontSizeDialog;
142 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
143 import com.stoutner.privacybrowser.dialogs.OpenDialog;
144 import com.stoutner.privacybrowser.dialogs.ProxyNotInstalledDialog;
145 import com.stoutner.privacybrowser.dialogs.PinnedMismatchDialog;
146 import com.stoutner.privacybrowser.dialogs.SaveDialog;
147 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
148 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
149 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
150 import com.stoutner.privacybrowser.dialogs.WaitingForProxyDialog;
151 import com.stoutner.privacybrowser.fragments.WebViewTabFragment;
152 import com.stoutner.privacybrowser.helpers.BlocklistHelper;
153 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
154 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
155 import com.stoutner.privacybrowser.helpers.ProxyHelper;
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 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
187         EditBookmarkFolderDialog.EditBookmarkFolderListener, FontSizeDialog.UpdateFontSizeListener, NavigationView.OnNavigationItemSelectedListener, OpenDialog.OpenListener,
188         PinnedMismatchDialog.PinnedMismatchListener, PopulateBlocklists.PopulateBlocklistsListener, SaveDialog.SaveListener, UrlHistoryDialog.NavigateHistoryListener,
189         WebViewTabFragment.NewTabListener {
190
191     // Define the public static variables.
192     public static ExecutorService executorService = Executors.newFixedThreadPool(4);
193     public static String orbotStatus = "unknown";
194     public static ArrayList<PendingDialog> pendingDialogsArrayList =  new ArrayList<>();
195     public static String proxyMode = ProxyHelper.NONE;
196
197     // Declare the public static variables.
198     public static String currentBookmarksFolder;
199     public static boolean restartFromBookmarksActivity;
200     public static WebViewPagerAdapter webViewPagerAdapter;
201
202     // Declare the public static views.
203     public static AppBarLayout appBarLayout;
204
205     // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
206     public final static int UNRECOGNIZED_USER_AGENT = -1;
207     public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
208     public final static int SETTINGS_CUSTOM_USER_AGENT = 11;
209     public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
210     public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
211     public final static int DOMAINS_CUSTOM_USER_AGENT = 12;
212
213     // Define the start activity for result request codes.  The public static entry is accessed from `OpenDialog()`.
214     private final int BROWSE_FILE_UPLOAD_REQUEST_CODE = 0;
215     public final static int BROWSE_OPEN_REQUEST_CODE = 1;
216
217     // Define the saved instance state constants.
218     private final String SAVED_STATE_ARRAY_LIST = "saved_state_array_list";
219     private final String SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST = "saved_nested_scroll_webview_state_array_list";
220     private final String SAVED_TAB_POSITION = "saved_tab_position";
221     private final String PROXY_MODE = "proxy_mode";
222
223     // Define the saved instance state variables.
224     private ArrayList<Bundle> savedStateArrayList;
225     private ArrayList<Bundle> savedNestedScrollWebViewStateArrayList;
226     private int savedTabPosition;
227     private String savedProxyMode;
228
229     // Define the class variables.
230     @SuppressWarnings("rawtypes")
231     AsyncTask populateBlocklists;
232
233     // The current WebView is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
234     // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, `applyProxy()`, and `applyDomainSettings()`.
235     private NestedScrollWebView currentWebView;
236
237     // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
238     private final Map<String, String> customHeaders = new HashMap<>();
239
240     // The search URL is set in `applyAppSettings()` and used in `onNewIntent()`, `loadUrlFromTextBox()`, `initializeApp()`, and `initializeWebView()`.
241     private String searchURL;
242
243     // The blocklists are populated in `finishedPopulatingBlocklists()` and accessed from `initializeWebView()`.
244     private ArrayList<List<String[]>> easyList;
245     private ArrayList<List<String[]>> easyPrivacy;
246     private ArrayList<List<String[]>> fanboysAnnoyanceList;
247     private ArrayList<List<String[]>> fanboysSocialList;
248     private ArrayList<List<String[]>> ultraList;
249     private ArrayList<List<String[]>> ultraPrivacy;
250
251     // The action bar drawer toggle is initialized in `onCreate()` and used in `onResume()`.
252     private ActionBarDrawerToggle actionBarDrawerToggle;
253
254     // The color spans are used in `onCreate()` and `highlightUrlText()`.
255     private ForegroundColorSpan redColorSpan;
256     private ForegroundColorSpan initialGrayColorSpan;
257     private ForegroundColorSpan finalGrayColorSpan;
258
259     // `bookmarksCursor` is used in `onDestroy()`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
260     private Cursor bookmarksCursor;
261
262     // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
263     private CursorAdapter bookmarksCursorAdapter;
264
265     // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
266     private String oldFolderNameString;
267
268     // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
269     private ValueCallback<Uri[]> fileChooserCallback;
270
271     // The default progress view offsets are set in `onCreate()` and used in `initializeWebView()`.
272     private int appBarHeight;
273     private int defaultProgressViewStartOffset;
274     private int defaultProgressViewEndOffset;
275
276     // The URL sanitizers are set in `applyAppSettings()` and used in `sanitizeUrl()`.
277     private boolean sanitizeGoogleAnalytics;
278     private boolean sanitizeFacebookClickIds;
279     private boolean sanitizeTwitterAmpRedirects;
280
281     // Declare the class variables
282     private BookmarksDatabaseHelper bookmarksDatabaseHelper;
283     private boolean bottomAppBar;
284     private boolean displayingFullScreenVideo;
285     private boolean downloadWithExternalApp;
286     private boolean fullScreenBrowsingModeEnabled;
287     private boolean hideAppBar;
288     private boolean incognitoModeEnabled;
289     private boolean inFullScreenBrowsingMode;
290     private boolean loadingNewIntent;
291     private BroadcastReceiver orbotStatusBroadcastReceiver;
292     private ProxyHelper proxyHelper;
293     private boolean reapplyAppSettingsOnRestart;
294     private boolean reapplyDomainSettingsOnRestart;
295     private boolean scrollAppBar;
296     private boolean waitingForProxy;
297     private String webViewDefaultUserAgent;
298
299     // Define the class variables.
300     private ObjectAnimator objectAnimator = new ObjectAnimator();
301     private String saveUrlString = "";
302
303     // Declare the class views.
304     private FrameLayout rootFrameLayout;
305     private DrawerLayout drawerLayout;
306     private CoordinatorLayout coordinatorLayout;
307     private Toolbar toolbar;
308     private RelativeLayout urlRelativeLayout;
309     private EditText urlEditText;
310     private ActionBar actionBar;
311     private LinearLayout findOnPageLinearLayout;
312     private LinearLayout tabsLinearLayout;
313     private TabLayout tabLayout;
314     private SwipeRefreshLayout swipeRefreshLayout;
315     private ViewPager webViewPager;
316     private FrameLayout fullScreenVideoFrameLayout;
317
318     // Declare the class menus.
319     private Menu optionsMenu;
320
321     // Declare the class menu items.
322     private MenuItem navigationBackMenuItem;
323     private MenuItem navigationForwardMenuItem;
324     private MenuItem navigationHistoryMenuItem;
325     private MenuItem navigationRequestsMenuItem;
326     private MenuItem optionsPrivacyMenuItem;
327     private MenuItem optionsRefreshMenuItem;
328     private MenuItem optionsCookiesMenuItem;
329     private MenuItem optionsDomStorageMenuItem;
330     private MenuItem optionsSaveFormDataMenuItem;
331     private MenuItem optionsClearDataMenuItem;
332     private MenuItem optionsClearCookiesMenuItem;
333     private MenuItem optionsClearDomStorageMenuItem;
334     private MenuItem optionsClearFormDataMenuItem;
335     private MenuItem optionsBlocklistsMenuItem;
336     private MenuItem optionsEasyListMenuItem;
337     private MenuItem optionsEasyPrivacyMenuItem;
338     private MenuItem optionsFanboysAnnoyanceListMenuItem;
339     private MenuItem optionsFanboysSocialBlockingListMenuItem;
340     private MenuItem optionsUltraListMenuItem;
341     private MenuItem optionsUltraPrivacyMenuItem;
342     private MenuItem optionsBlockAllThirdPartyRequestsMenuItem;
343     private MenuItem optionsProxyMenuItem;
344     private MenuItem optionsProxyNoneMenuItem;
345     private MenuItem optionsProxyTorMenuItem;
346     private MenuItem optionsProxyI2pMenuItem;
347     private MenuItem optionsProxyCustomMenuItem;
348     private MenuItem optionsUserAgentMenuItem;
349     private MenuItem optionsUserAgentPrivacyBrowserMenuItem;
350     private MenuItem optionsUserAgentWebViewDefaultMenuItem;
351     private MenuItem optionsUserAgentFirefoxOnAndroidMenuItem;
352     private MenuItem optionsUserAgentChromeOnAndroidMenuItem;
353     private MenuItem optionsUserAgentSafariOnIosMenuItem;
354     private MenuItem optionsUserAgentFirefoxOnLinuxMenuItem;
355     private MenuItem optionsUserAgentChromiumOnLinuxMenuItem;
356     private MenuItem optionsUserAgentFirefoxOnWindowsMenuItem;
357     private MenuItem optionsUserAgentChromeOnWindowsMenuItem;
358     private MenuItem optionsUserAgentEdgeOnWindowsMenuItem;
359     private MenuItem optionsUserAgentInternetExplorerOnWindowsMenuItem;
360     private MenuItem optionsUserAgentSafariOnMacosMenuItem;
361     private MenuItem optionsUserAgentCustomMenuItem;
362     private MenuItem optionsSwipeToRefreshMenuItem;
363     private MenuItem optionsWideViewportMenuItem;
364     private MenuItem optionsDisplayImagesMenuItem;
365     private MenuItem optionsDarkWebViewMenuItem;
366     private MenuItem optionsFontSizeMenuItem;
367     private MenuItem optionsAddOrEditDomainMenuItem;
368
369     // This variable won't be needed once the class is migrated to Kotlin, as can be seen in LogcatActivity or AboutVersionFragment.
370     private Activity resultLauncherActivityHandle;
371
372     // Define the save URL activity result launcher.  It must be defined before `onCreate()` is run or the app will crash.
373     private final ActivityResultLauncher<String> saveUrlActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.CreateDocument(),
374             new ActivityResultCallback<Uri>() {
375                 @Override
376                 public void onActivityResult(Uri fileUri) {
377                     // Only save the URL if the file URI is not null, which happens if the user exited the file picker by pressing back.
378                     if (fileUri != null) {
379                         new SaveUrl(getApplicationContext(), resultLauncherActivityHandle, fileUri, currentWebView.getSettings().getUserAgentString(), currentWebView.getAcceptCookies()).execute(saveUrlString);
380                     }
381
382                     // Reset the save URL string.
383                     saveUrlString = "";
384                 }
385             });
386
387     // Define the save webpage archive activity result launcher.  It must be defined before `onCreate()` is run or the app will crash.
388     private final ActivityResultLauncher<String> saveWebpageArchiveActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.CreateDocument(),
389             new ActivityResultCallback<Uri>() {
390                 @Override
391                 public void onActivityResult(Uri fileUri) {
392                     // Only save the webpage archive if the file URI is not null, which happens if the user exited the file picker by pressing back.
393                     if (fileUri != null) {
394                         try {
395                             // Create a temporary MHT file.
396                             File temporaryMhtFile = File.createTempFile("temporary_mht_file", ".mht", getCacheDir());
397
398                             // Save the temporary MHT file.
399                             currentWebView.saveWebArchive(temporaryMhtFile.toString(), false, callbackValue -> {
400                                 if (callbackValue != null) {  // The temporary MHT file was saved successfully.
401                                     try {
402                                         // Create a temporary MHT file input stream.
403                                         FileInputStream temporaryMhtFileInputStream = new FileInputStream(temporaryMhtFile);
404
405                                         // Get an output stream for the save webpage file path.
406                                         OutputStream mhtOutputStream = getContentResolver().openOutputStream(fileUri);
407
408                                         // Create a transfer byte array.
409                                         byte[] transferByteArray = new byte[1024];
410
411                                         // Create an integer to track the number of bytes read.
412                                         int bytesRead;
413
414                                         // Copy the temporary MHT file input stream to the MHT output stream.
415                                         while ((bytesRead = temporaryMhtFileInputStream.read(transferByteArray)) > 0) {
416                                             mhtOutputStream.write(transferByteArray, 0, bytesRead);
417                                         }
418
419                                         // Close the streams.
420                                         mhtOutputStream.close();
421                                         temporaryMhtFileInputStream.close();
422
423                                         // Initialize the file name string from the file URI last path segment.
424                                         String fileNameString = fileUri.getLastPathSegment();
425
426                                         // Query the exact file name if the API >= 26.
427                                         if (Build.VERSION.SDK_INT >= 26) {
428                                             // Get a cursor from the content resolver.
429                                             Cursor contentResolverCursor = resultLauncherActivityHandle.getContentResolver().query(fileUri, null, null, null);
430
431                                             // Move to the fist row.
432                                             contentResolverCursor.moveToFirst();
433
434                                             // Get the file name from the cursor.
435                                             fileNameString = contentResolverCursor.getString(contentResolverCursor.getColumnIndexOrThrow(OpenableColumns.DISPLAY_NAME));
436
437                                             // Close the cursor.
438                                             contentResolverCursor.close();
439                                         }
440
441                                         // Display a snackbar.
442                                         Snackbar.make(currentWebView, getString(R.string.file_saved) + "  " + fileNameString, Snackbar.LENGTH_SHORT).show();
443                                     } catch (Exception exception) {
444                                         // Display a snackbar with the exception.
445                                         Snackbar.make(currentWebView, getString(R.string.error_saving_file) + "  " + exception, Snackbar.LENGTH_INDEFINITE).show();
446                                     } finally {
447                                         // Delete the temporary MHT file.
448                                         //noinspection ResultOfMethodCallIgnored
449                                         temporaryMhtFile.delete();
450                                     }
451                                 } else {  // There was an unspecified error while saving the temporary MHT file.
452                                     // Display an error snackbar.
453                                     Snackbar.make(currentWebView, getString(R.string.error_saving_file), Snackbar.LENGTH_INDEFINITE).show();
454                                 }
455                             });
456                         } catch (IOException ioException) {
457                             // Display a snackbar with the IO exception.
458                             Snackbar.make(currentWebView, getString(R.string.error_saving_file) + "  " + ioException, Snackbar.LENGTH_INDEFINITE).show();
459                         }
460                     }
461                 }
462             });
463
464     // Define the save webpage image activity result launcher.  It must be defined before `onCreate()` is run or the app will crash.
465     private final ActivityResultLauncher<String> saveWebpageImageActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.CreateDocument(),
466             new ActivityResultCallback<Uri>() {
467                 @Override
468                 public void onActivityResult(Uri fileUri) {
469                     // Only save the webpage image if the file URI is not null, which happens if the user exited the file picker by pressing back.
470                     if (fileUri != null) {
471                         // Save the webpage image.
472                         new SaveWebpageImage(resultLauncherActivityHandle, fileUri, currentWebView).execute();
473                     }
474                 }
475             });
476
477     // Remove the warning about needing to override `performClick()` when using an `OnTouchListener` with WebView.
478     @SuppressLint("ClickableViewAccessibility")
479     @Override
480     protected void onCreate(Bundle savedInstanceState) {
481         // Run the default commands.
482         super.onCreate(savedInstanceState);
483
484         // Populate the result launcher activity.  This will no longer be needed once the activity has transitioned to Kotlin.
485         resultLauncherActivityHandle = this;
486
487         // Check to see if the activity has been restarted.
488         if (savedInstanceState != null) {
489             // Store the saved instance state variables.
490             savedStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_STATE_ARRAY_LIST);
491             savedNestedScrollWebViewStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST);
492             savedTabPosition = savedInstanceState.getInt(SAVED_TAB_POSITION);
493             savedProxyMode = savedInstanceState.getString(PROXY_MODE);
494         }
495
496         // Initialize the default preference values the first time the program is run.  `false` keeps this command from resetting any current preferences back to default.
497         PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
498
499         // Get a handle for the shared preferences.
500         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
501
502         // Get the preferences.
503         String appTheme = sharedPreferences.getString("app_theme", getString(R.string.app_theme_default_value));
504         boolean allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false);
505         bottomAppBar = sharedPreferences.getBoolean(getString(R.string.bottom_app_bar_key), false);
506
507         // Get the theme entry values string array.
508         String[] appThemeEntryValuesStringArray = getResources().getStringArray(R.array.app_theme_entry_values);
509
510         // 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.
511         if (appTheme.equals(appThemeEntryValuesStringArray[1])) {  // The light theme is selected.
512             // Apply the light theme.
513             AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
514         } else if (appTheme.equals(appThemeEntryValuesStringArray[2])) {  // The dark theme is selected.
515             // Apply the dark theme.
516             AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
517         } else {  // The system default theme is selected.
518             if (Build.VERSION.SDK_INT >= 28) {  // The system default theme is supported.
519                 // Follow the system default theme.
520                 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
521             } else {  // The system default theme is not supported.
522                 // Follow the battery saver mode.
523                 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
524             }
525         }
526
527         // Disable screenshots if not allowed.
528         if (!allowScreenshots) {
529             getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
530         }
531
532         // 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.
533         WebView.enableSlowWholeDocumentDraw();
534
535         // Set the theme.
536         setTheme(R.style.PrivacyBrowser);
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 proxy helper.
604         proxyHelper = new ProxyHelper();
605
606         // Initialize the app.
607         initializeApp();
608
609         // Apply the app settings from the shared preferences.
610         applyAppSettings();
611
612         // Populate the blocklists.
613         populateBlocklists = new PopulateBlocklists(this, this).execute();
614     }
615
616     @Override
617     protected void onNewIntent(Intent intent) {
618         // Run the default commands.
619         super.onNewIntent(intent);
620
621         // Replace the intent that started the app with this one.
622         setIntent(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         }
696     }
697
698     @Override
699     public void onRestart() {
700         // Run the default commands.
701         super.onRestart();
702
703         // Apply the app settings if returning from the Settings activity.
704         if (reapplyAppSettingsOnRestart) {
705             // Reset the reapply app settings on restart tracker.
706             reapplyAppSettingsOnRestart = false;
707
708             // Apply the app settings.
709             applyAppSettings();
710         }
711
712         // Apply the domain settings if returning from the settings or domains activity.
713         if (reapplyDomainSettingsOnRestart) {
714             // Reset the reapply domain settings on restart tracker.
715             reapplyDomainSettingsOnRestart = false;
716
717             // Reapply the domain settings for each tab.
718             for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
719                 // Get the WebView tab fragment.
720                 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
721
722                 // Get the fragment view.
723                 View fragmentView = webViewTabFragment.getView();
724
725                 // Only reload the WebViews if they exist.
726                 if (fragmentView != null) {
727                     // Get the nested scroll WebView from the tab fragment.
728                     NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
729
730                     // Reset the current domain name so the domain settings will be reapplied.
731                     nestedScrollWebView.setCurrentDomainName("");
732
733                     // Reapply the domain settings if the URL is not null, which can happen if an empty tab is active when returning from settings.
734                     if (nestedScrollWebView.getUrl() != null) {
735                         applyDomainSettings(nestedScrollWebView, nestedScrollWebView.getUrl(), false, true, false);
736                     }
737                 }
738             }
739         }
740
741         // Update the bookmarks drawer if returning from the Bookmarks activity.
742         if (restartFromBookmarksActivity) {
743             // Close the bookmarks drawer.
744             drawerLayout.closeDrawer(GravityCompat.END);
745
746             // Reload the bookmarks drawer.
747             loadBookmarksFolder();
748
749             // Reset `restartFromBookmarksActivity`.
750             restartFromBookmarksActivity = false;
751         }
752
753         // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.  This can be important if the screen was rotated.
754         updatePrivacyIcons(true);
755     }
756
757     // `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.
758     @Override
759     public void onStart() {
760         // Run the default commands.
761         super.onStart();
762
763         // Resume any WebViews.
764         for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
765             // Get the WebView tab fragment.
766             WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
767
768             // Get the fragment view.
769             View fragmentView = webViewTabFragment.getView();
770
771             // Only resume the WebViews if they exist (they won't when the app is first created).
772             if (fragmentView != null) {
773                 // Get the nested scroll WebView from the tab fragment.
774                 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
775
776                 // Resume the nested scroll WebView.
777                 nestedScrollWebView.onResume();
778             }
779         }
780
781         // Resume the nested scroll WebView JavaScript timers.  This is a global command that resumes JavaScript timers on all WebViews.
782         if (currentWebView != null) {
783             currentWebView.resumeTimers();
784         }
785
786         // Reapply the proxy settings if the system is using a proxy.  This redisplays the appropriate alert dialog.
787         if (!proxyMode.equals(ProxyHelper.NONE)) {
788             applyProxy(false);
789         }
790
791         // Reapply any system UI flags.
792         if (displayingFullScreenVideo || inFullScreenBrowsingMode) {  // The system is displaying a website or a video in full screen mode.
793             /* Hide the system bars.
794              * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
795              * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
796              * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
797              * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
798              */
799             rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
800                     View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
801         }
802
803         // Show any pending dialogs.
804         for (int i = 0; i < pendingDialogsArrayList.size(); i++) {
805             // Get the pending dialog from the array list.
806             PendingDialog pendingDialog = pendingDialogsArrayList.get(i);
807
808             // Show the pending dialog.
809             pendingDialog.dialogFragment.show(getSupportFragmentManager(), pendingDialog.tag);
810         }
811
812         // Clear the pending dialogs array list.
813         pendingDialogsArrayList.clear();
814     }
815
816     // `onStop()` runs after `onPause()`.  It is used instead of `onPause()` so the commands are not called every time the screen is partially hidden.
817     @Override
818     public void onStop() {
819         // Run the default commands.
820         super.onStop();
821
822         for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
823             // Get the WebView tab fragment.
824             WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
825
826             // Get the fragment view.
827             View fragmentView = webViewTabFragment.getView();
828
829             // Only pause the WebViews if they exist (they won't when the app is first created).
830             if (fragmentView != null) {
831                 // Get the nested scroll WebView from the tab fragment.
832                 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
833
834                 // Pause the nested scroll WebView.
835                 nestedScrollWebView.onPause();
836             }
837         }
838
839         // Pause the WebView JavaScript timers.  This is a global command that pauses JavaScript on all WebViews.
840         if (currentWebView != null) {
841             currentWebView.pauseTimers();
842         }
843     }
844
845     @Override
846     public void onSaveInstanceState(@NonNull Bundle savedInstanceState) {
847         // Run the default commands.
848         super.onSaveInstanceState(savedInstanceState);
849
850         // Create the saved state array lists.
851         ArrayList<Bundle> savedStateArrayList = new ArrayList<>();
852         ArrayList<Bundle> savedNestedScrollWebViewStateArrayList = new ArrayList<>();
853
854         // Get the URLs from each tab.
855         for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
856             // Get the WebView tab fragment.
857             WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
858
859             // Get the fragment view.
860             View fragmentView = webViewTabFragment.getView();
861
862             if (fragmentView != null) {
863                 // Get the nested scroll WebView from the tab fragment.
864                 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
865
866                 // Create saved state bundle.
867                 Bundle savedStateBundle = new Bundle();
868
869                 // Get the current states.
870                 nestedScrollWebView.saveState(savedStateBundle);
871                 Bundle savedNestedScrollWebViewStateBundle = nestedScrollWebView.saveNestedScrollWebViewState();
872
873                 // Store the saved states in the array lists.
874                 savedStateArrayList.add(savedStateBundle);
875                 savedNestedScrollWebViewStateArrayList.add(savedNestedScrollWebViewStateBundle);
876             }
877         }
878
879         // Get the current tab position.
880         int currentTabPosition = tabLayout.getSelectedTabPosition();
881
882         // Store the saved states in the bundle.
883         savedInstanceState.putParcelableArrayList(SAVED_STATE_ARRAY_LIST, savedStateArrayList);
884         savedInstanceState.putParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST, savedNestedScrollWebViewStateArrayList);
885         savedInstanceState.putInt(SAVED_TAB_POSITION, currentTabPosition);
886         savedInstanceState.putString(PROXY_MODE, proxyMode);
887     }
888
889     @Override
890     public void onDestroy() {
891         // Unregister the orbot status broadcast receiver if it exists.
892         if (orbotStatusBroadcastReceiver != null) {
893             this.unregisterReceiver(orbotStatusBroadcastReceiver);
894         }
895
896         // Close the bookmarks cursor if it exists.
897         if (bookmarksCursor != null) {
898             bookmarksCursor.close();
899         }
900
901         // Close the bookmarks database if it exists.
902         if (bookmarksDatabaseHelper != null) {
903             bookmarksDatabaseHelper.close();
904         }
905
906         // Stop populating the blocklists if the AsyncTask is running in the background.
907         if (populateBlocklists != null) {
908             populateBlocklists.cancel(true);
909         }
910
911         // Run the default commands.
912         super.onDestroy();
913     }
914
915     @Override
916     public boolean onCreateOptionsMenu(Menu menu) {
917         // Inflate the menu.  This adds items to the action bar if it is present.
918         getMenuInflater().inflate(R.menu.webview_options_menu, menu);
919
920         // Store a handle for the options menu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons()`.
921         optionsMenu = menu;
922
923         // Get handles for the menu items.
924         optionsPrivacyMenuItem = menu.findItem(R.id.javascript);
925         optionsRefreshMenuItem = menu.findItem(R.id.refresh);
926         MenuItem bookmarksMenuItem = menu.findItem(R.id.bookmarks);
927         optionsCookiesMenuItem = menu.findItem(R.id.cookies);
928         optionsDomStorageMenuItem = menu.findItem(R.id.dom_storage);
929         optionsSaveFormDataMenuItem = menu.findItem(R.id.save_form_data);  // Form data can be removed once the minimum API >= 26.
930         optionsClearDataMenuItem = menu.findItem(R.id.clear_data);
931         optionsClearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
932         optionsClearDomStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
933         optionsClearFormDataMenuItem = menu.findItem(R.id.clear_form_data);  // Form data can be removed once the minimum API >= 26.
934         optionsBlocklistsMenuItem = menu.findItem(R.id.blocklists);
935         optionsEasyListMenuItem = menu.findItem(R.id.easylist);
936         optionsEasyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
937         optionsFanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
938         optionsFanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
939         optionsUltraListMenuItem = menu.findItem(R.id.ultralist);
940         optionsUltraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
941         optionsBlockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
942         optionsProxyMenuItem = menu.findItem(R.id.proxy);
943         optionsProxyNoneMenuItem = menu.findItem(R.id.proxy_none);
944         optionsProxyTorMenuItem = menu.findItem(R.id.proxy_tor);
945         optionsProxyI2pMenuItem = menu.findItem(R.id.proxy_i2p);
946         optionsProxyCustomMenuItem = menu.findItem(R.id.proxy_custom);
947         optionsUserAgentMenuItem = menu.findItem(R.id.user_agent);
948         optionsUserAgentPrivacyBrowserMenuItem = menu.findItem(R.id.user_agent_privacy_browser);
949         optionsUserAgentWebViewDefaultMenuItem = menu.findItem(R.id.user_agent_webview_default);
950         optionsUserAgentFirefoxOnAndroidMenuItem = menu.findItem(R.id.user_agent_firefox_on_android);
951         optionsUserAgentChromeOnAndroidMenuItem = menu.findItem(R.id.user_agent_chrome_on_android);
952         optionsUserAgentSafariOnIosMenuItem = menu.findItem(R.id.user_agent_safari_on_ios);
953         optionsUserAgentFirefoxOnLinuxMenuItem = menu.findItem(R.id.user_agent_firefox_on_linux);
954         optionsUserAgentChromiumOnLinuxMenuItem = menu.findItem(R.id.user_agent_chromium_on_linux);
955         optionsUserAgentFirefoxOnWindowsMenuItem = menu.findItem(R.id.user_agent_firefox_on_windows);
956         optionsUserAgentChromeOnWindowsMenuItem = menu.findItem(R.id.user_agent_chrome_on_windows);
957         optionsUserAgentEdgeOnWindowsMenuItem = menu.findItem(R.id.user_agent_edge_on_windows);
958         optionsUserAgentInternetExplorerOnWindowsMenuItem = menu.findItem(R.id.user_agent_internet_explorer_on_windows);
959         optionsUserAgentSafariOnMacosMenuItem = menu.findItem(R.id.user_agent_safari_on_macos);
960         optionsUserAgentCustomMenuItem = menu.findItem(R.id.user_agent_custom);
961         optionsSwipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
962         optionsWideViewportMenuItem = menu.findItem(R.id.wide_viewport);
963         optionsDisplayImagesMenuItem = menu.findItem(R.id.display_images);
964         optionsDarkWebViewMenuItem = menu.findItem(R.id.dark_webview);
965         optionsFontSizeMenuItem = menu.findItem(R.id.font_size);
966         optionsAddOrEditDomainMenuItem = menu.findItem(R.id.add_or_edit_domain);
967
968         // Set the initial status of the privacy icons.  `false` does not call `invalidateOptionsMenu` as the last step.
969         updatePrivacyIcons(false);
970
971         // Only display the form data menu items if the API < 26.
972         optionsSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
973         optionsClearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
974
975         // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
976         optionsClearFormDataMenuItem.setEnabled(Build.VERSION.SDK_INT < 26);
977
978         // Get the shared preferences.
979         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
980
981         // Get the dark theme and app bar preferences.
982         boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false);
983
984         // 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.
985         if (displayAdditionalAppBarIcons) {
986             optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
987             bookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
988             optionsCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
989         } else { //Do not display the additional icons.
990             optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
991             bookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
992             optionsCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
993         }
994
995         // Replace Refresh with Stop if a URL is already loading.
996         if (currentWebView != null && currentWebView.getProgress() != 100) {
997             // Set the title.
998             optionsRefreshMenuItem.setTitle(R.string.stop);
999
1000             // 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.
1001             if (displayAdditionalAppBarIcons) {
1002                 optionsRefreshMenuItem.setIcon(R.drawable.close_blue);
1003             }
1004         }
1005
1006         // Done.
1007         return true;
1008     }
1009
1010     @Override
1011     public boolean onPrepareOptionsMenu(Menu menu) {
1012         // Get a handle for the cookie manager.
1013         CookieManager cookieManager = CookieManager.getInstance();
1014
1015         // Initialize the current user agent string and the font size.
1016         String currentUserAgent = getString(R.string.user_agent_privacy_browser);
1017         int fontSize = 100;
1018
1019         // 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.
1020         if (currentWebView != null) {
1021             // Set the add or edit domain text.
1022             if (currentWebView.getDomainSettingsApplied()) {
1023                 optionsAddOrEditDomainMenuItem.setTitle(R.string.edit_domain_settings);
1024             } else {
1025                 optionsAddOrEditDomainMenuItem.setTitle(R.string.add_domain_settings);
1026             }
1027
1028             // Get the current user agent from the WebView.
1029             currentUserAgent = currentWebView.getSettings().getUserAgentString();
1030
1031             // Get the current font size from the
1032             fontSize = currentWebView.getSettings().getTextZoom();
1033
1034             // Set the status of the menu item checkboxes.
1035             optionsDomStorageMenuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1036             optionsSaveFormDataMenuItem.setChecked(currentWebView.getSettings().getSaveFormData());  // Form data can be removed once the minimum API >= 26.
1037             optionsEasyListMenuItem.setChecked(currentWebView.getEasyListEnabled());
1038             optionsEasyPrivacyMenuItem.setChecked(currentWebView.getEasyPrivacyEnabled());
1039             optionsFanboysAnnoyanceListMenuItem.setChecked(currentWebView.getFanboysAnnoyanceListEnabled());
1040             optionsFanboysSocialBlockingListMenuItem.setChecked(currentWebView.getFanboysSocialBlockingListEnabled());
1041             optionsUltraListMenuItem.setChecked(currentWebView.getUltraListEnabled());
1042             optionsUltraPrivacyMenuItem.setChecked(currentWebView.getUltraPrivacyEnabled());
1043             optionsBlockAllThirdPartyRequestsMenuItem.setChecked(currentWebView.getBlockAllThirdPartyRequests());
1044             optionsSwipeToRefreshMenuItem.setChecked(currentWebView.getSwipeToRefresh());
1045             optionsWideViewportMenuItem.setChecked(currentWebView.getSettings().getUseWideViewPort());
1046             optionsDisplayImagesMenuItem.setChecked(currentWebView.getSettings().getLoadsImagesAutomatically());
1047
1048             // Initialize the display names for the blocklists with the number of blocked requests.
1049             optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
1050             optionsEasyListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYLIST) + " - " + getString(R.string.easylist));
1051             optionsEasyPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYPRIVACY) + " - " + getString(R.string.easyprivacy));
1052             optionsFanboysAnnoyanceListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " + getString(R.string.fanboys_annoyance_list));
1053             optionsFanboysSocialBlockingListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " + getString(R.string.fanboys_social_blocking_list));
1054             optionsUltraListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRALIST) + " - " + getString(R.string.ultralist));
1055             optionsUltraPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRAPRIVACY) + " - " + getString(R.string.ultraprivacy));
1056             optionsBlockAllThirdPartyRequestsMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " + getString(R.string.block_all_third_party_requests));
1057
1058             // Enable DOM Storage if JavaScript is enabled.
1059             optionsDomStorageMenuItem.setEnabled(currentWebView.getSettings().getJavaScriptEnabled());
1060
1061             // Set the checkbox status for dark WebView if the WebView supports it.
1062             if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
1063                 optionsDarkWebViewMenuItem.setChecked(WebSettingsCompat.getForceDark(currentWebView.getSettings()) == WebSettingsCompat.FORCE_DARK_ON);
1064             }
1065         }
1066
1067         // Set the cookies menu item checked status.
1068         optionsCookiesMenuItem.setChecked(cookieManager.acceptCookie());
1069
1070         // Enable Clear Cookies if there are any.
1071         optionsClearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1072
1073         // 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`.
1074         String privateDataDirectoryString = getApplicationInfo().dataDir;
1075
1076         // Get a count of the number of files in the Local Storage directory.
1077         File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1078         int localStorageDirectoryNumberOfFiles = 0;
1079         if (localStorageDirectory.exists()) {
1080             // `Objects.requireNonNull` removes a lint warning that `localStorageDirectory.list` might produce a null pointed exception if it is dereferenced.
1081             localStorageDirectoryNumberOfFiles = Objects.requireNonNull(localStorageDirectory.list()).length;
1082         }
1083
1084         // Get a count of the number of files in the IndexedDB directory.
1085         File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1086         int indexedDBDirectoryNumberOfFiles = 0;
1087         if (indexedDBDirectory.exists()) {
1088             // `Objects.requireNonNull` removes a lint warning that `indexedDBDirectory.list` might produce a null pointed exception if it is dereferenced.
1089             indexedDBDirectoryNumberOfFiles = Objects.requireNonNull(indexedDBDirectory.list()).length;
1090         }
1091
1092         // Enable Clear DOM Storage if there is any.
1093         optionsClearDomStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1094
1095         // Enable Clear Form Data is there is any.  This can be removed once the minimum API >= 26.
1096         if (Build.VERSION.SDK_INT < 26) {
1097             // Get the WebView database.
1098             WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1099
1100             // Enable the clear form data menu item if there is anything to clear.
1101             optionsClearFormDataMenuItem.setEnabled(webViewDatabase.hasFormData());
1102         }
1103
1104         // Enable Clear Data if any of the submenu items are enabled.
1105         optionsClearDataMenuItem.setEnabled(optionsClearCookiesMenuItem.isEnabled() || optionsClearDomStorageMenuItem.isEnabled() || optionsClearFormDataMenuItem.isEnabled());
1106
1107         // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
1108         optionsFanboysSocialBlockingListMenuItem.setEnabled(!optionsFanboysAnnoyanceListMenuItem.isChecked());
1109
1110         // Set the proxy title and check the applied proxy.
1111         switch (proxyMode) {
1112             case ProxyHelper.NONE:
1113                 // Set the proxy title.
1114                 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_none));
1115
1116                 // Check the proxy None radio button.
1117                 optionsProxyNoneMenuItem.setChecked(true);
1118                 break;
1119
1120             case ProxyHelper.TOR:
1121                 // Set the proxy title.
1122                 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_tor));
1123
1124                 // Check the proxy Tor radio button.
1125                 optionsProxyTorMenuItem.setChecked(true);
1126                 break;
1127
1128             case ProxyHelper.I2P:
1129                 // Set the proxy title.
1130                 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_i2p));
1131
1132                 // Check the proxy I2P radio button.
1133                 optionsProxyI2pMenuItem.setChecked(true);
1134                 break;
1135
1136             case ProxyHelper.CUSTOM:
1137                 // Set the proxy title.
1138                 optionsProxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_custom));
1139
1140                 // Check the proxy Custom radio button.
1141                 optionsProxyCustomMenuItem.setChecked(true);
1142                 break;
1143         }
1144
1145         // Select the current user agent menu item.  A switch statement cannot be used because the user agents are not compile time constants.
1146         if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) {  // Privacy Browser.
1147             // Update the user agent menu item title.
1148             optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_privacy_browser));
1149
1150             // Select the Privacy Browser radio box.
1151             optionsUserAgentPrivacyBrowserMenuItem.setChecked(true);
1152         } else if (currentUserAgent.equals(webViewDefaultUserAgent)) {  // WebView Default.
1153             // Update the user agent menu item title.
1154             optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_webview_default));
1155
1156             // Select the WebView Default radio box.
1157             optionsUserAgentWebViewDefaultMenuItem.setChecked(true);
1158         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) {  // Firefox on Android.
1159             // Update the user agent menu item title.
1160             optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_android));
1161
1162             // Select the Firefox on Android radio box.
1163             optionsUserAgentFirefoxOnAndroidMenuItem.setChecked(true);
1164         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) {  // Chrome on Android.
1165             // Update the user agent menu item title.
1166             optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_android));
1167
1168             // Select the Chrome on Android radio box.
1169             optionsUserAgentChromeOnAndroidMenuItem.setChecked(true);
1170         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) {  // Safari on iOS.
1171             // Update the user agent menu item title.
1172             optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_ios));
1173
1174             // Select the Safari on iOS radio box.
1175             optionsUserAgentSafariOnIosMenuItem.setChecked(true);
1176         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) {  // Firefox on Linux.
1177             // Update the user agent menu item title.
1178             optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_linux));
1179
1180             // Select the Firefox on Linux radio box.
1181             optionsUserAgentFirefoxOnLinuxMenuItem.setChecked(true);
1182         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) {  // Chromium on Linux.
1183             // Update the user agent menu item title.
1184             optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chromium_on_linux));
1185
1186             // Select the Chromium on Linux radio box.
1187             optionsUserAgentChromiumOnLinuxMenuItem.setChecked(true);
1188         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) {  // Firefox on Windows.
1189             // Update the user agent menu item title.
1190             optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_windows));
1191
1192             // Select the Firefox on Windows radio box.
1193             optionsUserAgentFirefoxOnWindowsMenuItem.setChecked(true);
1194         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) {  // Chrome on Windows.
1195             // Update the user agent menu item title.
1196             optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_windows));
1197
1198             // Select the Chrome on Windows radio box.
1199             optionsUserAgentChromeOnWindowsMenuItem.setChecked(true);
1200         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) {  // Edge on Windows.
1201             // Update the user agent menu item title.
1202             optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_edge_on_windows));
1203
1204             // Select the Edge on Windows radio box.
1205             optionsUserAgentEdgeOnWindowsMenuItem.setChecked(true);
1206         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) {  // Internet Explorer on Windows.
1207             // Update the user agent menu item title.
1208             optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_internet_explorer_on_windows));
1209
1210             // Select the Internet on Windows radio box.
1211             optionsUserAgentInternetExplorerOnWindowsMenuItem.setChecked(true);
1212         } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) {  // Safari on macOS.
1213             // Update the user agent menu item title.
1214             optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_macos));
1215
1216             // Select the Safari on macOS radio box.
1217             optionsUserAgentSafariOnMacosMenuItem.setChecked(true);
1218         } else {  // Custom user agent.
1219             // Update the user agent menu item title.
1220             optionsUserAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_custom));
1221
1222             // Select the Custom radio box.
1223             optionsUserAgentCustomMenuItem.setChecked(true);
1224         }
1225
1226         // Set the font size title.
1227         optionsFontSizeMenuItem.setTitle(getString(R.string.font_size) + " - " + fontSize + "%");
1228
1229         // Run all the other default commands.
1230         super.onPrepareOptionsMenu(menu);
1231
1232         // Display the menu.
1233         return true;
1234     }
1235
1236     @Override
1237     public boolean onOptionsItemSelected(MenuItem menuItem) {
1238         // Get a handle for the shared preferences.
1239         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1240
1241         // Get a handle for the cookie manager.
1242         CookieManager cookieManager = CookieManager.getInstance();
1243
1244         // Get the selected menu item ID.
1245         int menuItemId = menuItem.getItemId();
1246
1247         // Run the commands that correlate to the selected menu item.
1248         if (menuItemId == R.id.javascript) {  // JavaScript.
1249             // Toggle the JavaScript status.
1250             currentWebView.getSettings().setJavaScriptEnabled(!currentWebView.getSettings().getJavaScriptEnabled());
1251
1252             // Update the privacy icon.
1253             updatePrivacyIcons(true);
1254
1255             // Display a `Snackbar`.
1256             if (currentWebView.getSettings().getJavaScriptEnabled()) {  // JavaScrip is enabled.
1257                 Snackbar.make(webViewPager, R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1258             } else if (cookieManager.acceptCookie()) {  // JavaScript is disabled, but first-party cookies are enabled.
1259                 Snackbar.make(webViewPager, R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1260             } else {  // Privacy mode.
1261                 Snackbar.make(webViewPager, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1262             }
1263
1264             // Reload the current WebView.
1265             currentWebView.reload();
1266
1267             // Consume the event.
1268             return true;
1269         } else if (menuItemId == R.id.refresh) {  // Refresh.
1270             // Run the command that correlates to the current status of the menu item.
1271             if (menuItem.getTitle().equals(getString(R.string.refresh))) {  // The refresh button was pushed.
1272                 // Reload the current WebView.
1273                 currentWebView.reload();
1274             } else {  // The stop button was pushed.
1275                 // Stop the loading of the WebView.
1276                 currentWebView.stopLoading();
1277             }
1278
1279             // Consume the event.
1280             return true;
1281         } else if (menuItemId == R.id.bookmarks) {  // Bookmarks.
1282             // Open the bookmarks drawer.
1283             drawerLayout.openDrawer(GravityCompat.END);
1284
1285             // Consume the event.
1286             return true;
1287         } else if (menuItemId == R.id.cookies) {  // Cookies.
1288             // Switch the first-party cookie status.
1289             cookieManager.setAcceptCookie(!cookieManager.acceptCookie());
1290
1291             // Store the cookie status.
1292             currentWebView.setAcceptCookies(cookieManager.acceptCookie());
1293
1294             // Update the menu checkbox.
1295             menuItem.setChecked(cookieManager.acceptCookie());
1296
1297             // Update the privacy icon.
1298             updatePrivacyIcons(true);
1299
1300             // Display a snackbar.
1301             if (cookieManager.acceptCookie()) {  // Cookies are enabled.
1302                 Snackbar.make(webViewPager, R.string.cookies_enabled, Snackbar.LENGTH_SHORT).show();
1303             } else if (currentWebView.getSettings().getJavaScriptEnabled()) {  // JavaScript is still enabled.
1304                 Snackbar.make(webViewPager, R.string.cookies_disabled, Snackbar.LENGTH_SHORT).show();
1305             } else {  // Privacy mode.
1306                 Snackbar.make(webViewPager, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1307             }
1308
1309             // Reload the current WebView.
1310             currentWebView.reload();
1311
1312             // Consume the event.
1313             return true;
1314         } else if (menuItemId == R.id.dom_storage) {  // DOM storage.
1315             // Toggle the status of domStorageEnabled.
1316             currentWebView.getSettings().setDomStorageEnabled(!currentWebView.getSettings().getDomStorageEnabled());
1317
1318             // Update the menu checkbox.
1319             menuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1320
1321             // Update the privacy icon.
1322             updatePrivacyIcons(true);
1323
1324             // Display a snackbar.
1325             if (currentWebView.getSettings().getDomStorageEnabled()) {
1326                 Snackbar.make(webViewPager, R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1327             } else {
1328                 Snackbar.make(webViewPager, R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1329             }
1330
1331             // Reload the current WebView.
1332             currentWebView.reload();
1333
1334             // Consume the event.
1335             return true;
1336         } else if (menuItemId == R.id.save_form_data) {  // Form data.  This can be removed once the minimum API >= 26.
1337             // Switch the status of saveFormDataEnabled.
1338             currentWebView.getSettings().setSaveFormData(!currentWebView.getSettings().getSaveFormData());
1339
1340             // Update the menu checkbox.
1341             menuItem.setChecked(currentWebView.getSettings().getSaveFormData());
1342
1343             // Display a snackbar.
1344             if (currentWebView.getSettings().getSaveFormData()) {
1345                 Snackbar.make(webViewPager, R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1346             } else {
1347                 Snackbar.make(webViewPager, R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1348             }
1349
1350             // Update the privacy icon.
1351             updatePrivacyIcons(true);
1352
1353             // Reload the current WebView.
1354             currentWebView.reload();
1355
1356             // Consume the event.
1357             return true;
1358         } else if (menuItemId == R.id.clear_cookies) {  // Clear cookies.
1359             // Create a snackbar.
1360             Snackbar.make(webViewPager, R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1361                     .setAction(R.string.undo, v -> {
1362                         // Do nothing because everything will be handled by `onDismissed()` below.
1363                     })
1364                     .addCallback(new Snackbar.Callback() {
1365                         @Override
1366                         public void onDismissed(Snackbar snackbar, int event) {
1367                             if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) {  // The snackbar was dismissed without the undo button being pushed.
1368                                 // Delete the cookies.
1369                                 cookieManager.removeAllCookies(null);
1370                             }
1371                         }
1372                     })
1373                     .show();
1374
1375             // Consume the event.
1376             return true;
1377         } else if (menuItemId == R.id.clear_dom_storage) {  // Clear DOM storage.
1378             // Create a snackbar.
1379             Snackbar.make(webViewPager, R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1380                     .setAction(R.string.undo, v -> {
1381                         // Do nothing because everything will be handled by `onDismissed()` below.
1382                     })
1383                     .addCallback(new Snackbar.Callback() {
1384                         @Override
1385                         public void onDismissed(Snackbar snackbar, int event) {
1386                             if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) {  // The snackbar was dismissed without the undo button being pushed.
1387                                 // Delete the DOM Storage.
1388                                 WebStorage webStorage = WebStorage.getInstance();
1389                                 webStorage.deleteAllData();
1390
1391                                 // Initialize a handler to manually delete the DOM storage files and directories.
1392                                 Handler deleteDomStorageHandler = new Handler();
1393
1394                                 // Setup a runnable to manually delete the DOM storage files and directories.
1395                                 Runnable deleteDomStorageRunnable = () -> {
1396                                     try {
1397                                         // Get a handle for the runtime.
1398                                         Runtime runtime = Runtime.getRuntime();
1399
1400                                         // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1401                                         // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1402                                         String privateDataDirectoryString = getApplicationInfo().dataDir;
1403
1404                                         // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1405                                         Process deleteLocalStorageProcess = runtime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1406
1407                                         // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1408                                         Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1409                                         Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1410                                         Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1411                                         Process deleteDatabasesProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1412
1413                                         // Wait for the processes to finish.
1414                                         deleteLocalStorageProcess.waitFor();
1415                                         deleteIndexProcess.waitFor();
1416                                         deleteQuotaManagerProcess.waitFor();
1417                                         deleteQuotaManagerJournalProcess.waitFor();
1418                                         deleteDatabasesProcess.waitFor();
1419                                     } catch (Exception exception) {
1420                                         // Do nothing if an error is thrown.
1421                                     }
1422                                 };
1423
1424                                 // Manually delete the DOM storage files after 200 milliseconds.
1425                                 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
1426                             }
1427                         }
1428                     })
1429                     .show();
1430
1431             // Consume the event.
1432             return true;
1433         } else if (menuItemId == R.id.clear_form_data) {  // Clear form data.  This can be remove once the minimum API >= 26.
1434             // Create a snackbar.
1435             Snackbar.make(webViewPager, R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1436                     .setAction(R.string.undo, v -> {
1437                         // Do nothing because everything will be handled by `onDismissed()` below.
1438                     })
1439                     .addCallback(new Snackbar.Callback() {
1440                         @Override
1441                         public void onDismissed(Snackbar snackbar, int event) {
1442                             if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) {  // The snackbar was dismissed without the undo button being pushed.
1443                                 // Get a handle for the webView database.
1444                                 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1445
1446                                 // Delete the form data.
1447                                 webViewDatabase.clearFormData();
1448                             }
1449                         }
1450                     })
1451                     .show();
1452
1453             // Consume the event.
1454             return true;
1455         } else if (menuItemId == R.id.easylist) {  // EasyList.
1456             // Toggle the EasyList status.
1457             currentWebView.setEasyListEnabled(!currentWebView.getEasyListEnabled());
1458
1459             // Update the menu checkbox.
1460             menuItem.setChecked(currentWebView.getEasyListEnabled());
1461
1462             // Reload the current WebView.
1463             currentWebView.reload();
1464
1465             // Consume the event.
1466             return true;
1467         } else if (menuItemId == R.id.easyprivacy) {  // EasyPrivacy.
1468             // Toggle the EasyPrivacy status.
1469             currentWebView.setEasyPrivacyEnabled(!currentWebView.getEasyPrivacyEnabled());
1470
1471             // Update the menu checkbox.
1472             menuItem.setChecked(currentWebView.getEasyPrivacyEnabled());
1473
1474             // Reload the current WebView.
1475             currentWebView.reload();
1476
1477             // Consume the event.
1478             return true;
1479         } else if (menuItemId == R.id.fanboys_annoyance_list) {  // Fanboy's Annoyance List.
1480             // Toggle Fanboy's Annoyance List status.
1481             currentWebView.setFanboysAnnoyanceListEnabled(!currentWebView.getFanboysAnnoyanceListEnabled());
1482
1483             // Update the menu checkbox.
1484             menuItem.setChecked(currentWebView.getFanboysAnnoyanceListEnabled());
1485
1486             // Update the status of Fanboy's Social Blocking List.
1487             optionsFanboysSocialBlockingListMenuItem.setEnabled(!currentWebView.getFanboysAnnoyanceListEnabled());
1488
1489             // Reload the current WebView.
1490             currentWebView.reload();
1491
1492             // Consume the event.
1493             return true;
1494         } else if (menuItemId == R.id.fanboys_social_blocking_list) {  // Fanboy's Social Blocking List.
1495             // Toggle Fanboy's Social Blocking List status.
1496             currentWebView.setFanboysSocialBlockingListEnabled(!currentWebView.getFanboysSocialBlockingListEnabled());
1497
1498             // Update the menu checkbox.
1499             menuItem.setChecked(currentWebView.getFanboysSocialBlockingListEnabled());
1500
1501             // Reload the current WebView.
1502             currentWebView.reload();
1503
1504             // Consume the event.
1505             return true;
1506         } else if (menuItemId == R.id.ultralist) {  // UltraList.
1507             // Toggle the UltraList status.
1508             currentWebView.setUltraListEnabled(!currentWebView.getUltraListEnabled());
1509
1510             // Update the menu checkbox.
1511             menuItem.setChecked(currentWebView.getUltraListEnabled());
1512
1513             // Reload the current WebView.
1514             currentWebView.reload();
1515
1516             // Consume the event.
1517             return true;
1518         } else if (menuItemId == R.id.ultraprivacy) {  // UltraPrivacy.
1519             // Toggle the UltraPrivacy status.
1520             currentWebView.setUltraPrivacyEnabled(!currentWebView.getUltraPrivacyEnabled());
1521
1522             // Update the menu checkbox.
1523             menuItem.setChecked(currentWebView.getUltraPrivacyEnabled());
1524
1525             // Reload the current WebView.
1526             currentWebView.reload();
1527
1528             // Consume the event.
1529             return true;
1530         } else if (menuItemId == R.id.block_all_third_party_requests) {  // Block all third-party requests.
1531             //Toggle the third-party requests blocker status.
1532             currentWebView.setBlockAllThirdPartyRequests(!currentWebView.getBlockAllThirdPartyRequests());
1533
1534             // Update the menu checkbox.
1535             menuItem.setChecked(currentWebView.getBlockAllThirdPartyRequests());
1536
1537             // Reload the current WebView.
1538             currentWebView.reload();
1539
1540             // Consume the event.
1541             return true;
1542         } else if (menuItemId == R.id.proxy_none) {  // Proxy - None.
1543             // Update the proxy mode.
1544             proxyMode = ProxyHelper.NONE;
1545
1546             // Apply the proxy mode.
1547             applyProxy(true);
1548
1549             // Consume the event.
1550             return true;
1551         } else if (menuItemId == R.id.proxy_tor) {  // Proxy - Tor.
1552             // Update the proxy mode.
1553             proxyMode = ProxyHelper.TOR;
1554
1555             // Apply the proxy mode.
1556             applyProxy(true);
1557
1558             // Consume the event.
1559             return true;
1560         } else if (menuItemId == R.id.proxy_i2p) {  // Proxy - I2P.
1561             // Update the proxy mode.
1562             proxyMode = ProxyHelper.I2P;
1563
1564             // Apply the proxy mode.
1565             applyProxy(true);
1566
1567             // Consume the event.
1568             return true;
1569         } else if (menuItemId == R.id.proxy_custom) {  // Proxy - Custom.
1570             // Update the proxy mode.
1571             proxyMode = ProxyHelper.CUSTOM;
1572
1573             // Apply the proxy mode.
1574             applyProxy(true);
1575
1576             // Consume the event.
1577             return true;
1578         } else if (menuItemId == R.id.user_agent_privacy_browser) {  // User Agent - Privacy Browser.
1579             // Update the user agent.
1580             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
1581
1582             // Reload the current WebView.
1583             currentWebView.reload();
1584
1585             // Consume the event.
1586             return true;
1587         } else if (menuItemId == R.id.user_agent_webview_default) {  // User Agent - WebView Default.
1588             // Update the user agent.
1589             currentWebView.getSettings().setUserAgentString("");
1590
1591             // Reload the current WebView.
1592             currentWebView.reload();
1593
1594             // Consume the event.
1595             return true;
1596         } else if (menuItemId == R.id.user_agent_firefox_on_android) {  // User Agent - Firefox on Android.
1597             // Update the user agent.
1598             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
1599
1600             // Reload the current WebView.
1601             currentWebView.reload();
1602
1603             // Consume the event.
1604             return true;
1605         } else if (menuItemId == R.id.user_agent_chrome_on_android) {  // User Agent - Chrome on Android.
1606             // Update the user agent.
1607             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
1608
1609             // Reload the current WebView.
1610             currentWebView.reload();
1611
1612             // Consume the event.
1613             return true;
1614         } else if (menuItemId == R.id.user_agent_safari_on_ios) {  // User Agent - Safari on iOS.
1615             // Update the user agent.
1616             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
1617
1618             // Reload the current WebView.
1619             currentWebView.reload();
1620
1621             // Consume the event.
1622             return true;
1623         } else if (menuItemId == R.id.user_agent_firefox_on_linux) {  // User Agent - Firefox on Linux.
1624             // Update the user agent.
1625             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
1626
1627             // Reload the current WebView.
1628             currentWebView.reload();
1629
1630             // Consume the event.
1631             return true;
1632         } else if (menuItemId == R.id.user_agent_chromium_on_linux) {  // User Agent - Chromium on Linux.
1633             // Update the user agent.
1634             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
1635
1636             // Reload the current WebView.
1637             currentWebView.reload();
1638
1639             // Consume the event.
1640             return true;
1641         } else if (menuItemId == R.id.user_agent_firefox_on_windows) {  // User Agent - Firefox on Windows.
1642             // Update the user agent.
1643             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
1644
1645             // Reload the current WebView.
1646             currentWebView.reload();
1647
1648             // Consume the event.
1649             return true;
1650         } else if (menuItemId == R.id.user_agent_chrome_on_windows) {  // User Agent - Chrome on Windows.
1651             // Update the user agent.
1652             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
1653
1654             // Reload the current WebView.
1655             currentWebView.reload();
1656
1657             // Consume the event.
1658             return true;
1659         } else if (menuItemId == R.id.user_agent_edge_on_windows) {  // User Agent - Edge on Windows.
1660             // Update the user agent.
1661             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
1662
1663             // Reload the current WebView.
1664             currentWebView.reload();
1665
1666             // Consume the event.
1667             return true;
1668         } else if (menuItemId == R.id.user_agent_internet_explorer_on_windows) {  // User Agent - Internet Explorer on Windows.
1669             // Update the user agent.
1670             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
1671
1672             // Reload the current WebView.
1673             currentWebView.reload();
1674
1675             // Consume the event.
1676             return true;
1677         } else if (menuItemId == R.id.user_agent_safari_on_macos) {  // User Agent - Safari on macOS.
1678             // Update the user agent.
1679             currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
1680
1681             // Reload the current WebView.
1682             currentWebView.reload();
1683
1684             // Consume the event.
1685             return true;
1686         } else if (menuItemId == R.id.user_agent_custom) {  // User Agent - Custom.
1687             // Update the user agent.
1688             currentWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
1689
1690             // Reload the current WebView.
1691             currentWebView.reload();
1692
1693             // Consume the event.
1694             return true;
1695         } else if (menuItemId == R.id.font_size) {  // Font size.
1696             // Instantiate the font size dialog.
1697             DialogFragment fontSizeDialogFragment = FontSizeDialog.displayDialog(currentWebView.getSettings().getTextZoom());
1698
1699             // Show the font size dialog.
1700             fontSizeDialogFragment.show(getSupportFragmentManager(), getString(R.string.font_size));
1701
1702             // Consume the event.
1703             return true;
1704         } else if (menuItemId == R.id.swipe_to_refresh) {  // Swipe to refresh.
1705             // Toggle the stored status of swipe to refresh.
1706             currentWebView.setSwipeToRefresh(!currentWebView.getSwipeToRefresh());
1707
1708             // Update the swipe refresh layout.
1709             if (currentWebView.getSwipeToRefresh()) {  // Swipe to refresh is enabled.
1710                 // Only enable the swipe refresh layout if the WebView is scrolled to the top.  It is updated every time the scroll changes.
1711                 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
1712             } else {  // Swipe to refresh is disabled.
1713                 // Disable the swipe refresh layout.
1714                 swipeRefreshLayout.setEnabled(false);
1715             }
1716
1717             // Consume the event.
1718             return true;
1719         } else if (menuItemId == R.id.wide_viewport) {  // Wide viewport.
1720             // Toggle the viewport.
1721             currentWebView.getSettings().setUseWideViewPort(!currentWebView.getSettings().getUseWideViewPort());
1722
1723             // Consume the event.
1724             return true;
1725         } else if (menuItemId == R.id.display_images) {  // Display images.
1726             // Toggle the displaying of images.
1727             if (currentWebView.getSettings().getLoadsImagesAutomatically()) {  // Images are currently loaded automatically.
1728                 // Disable loading of images.
1729                 currentWebView.getSettings().setLoadsImagesAutomatically(false);
1730
1731                 // Reload the website to remove existing images.
1732                 currentWebView.reload();
1733             } else {  // Images are not currently loaded automatically.
1734                 // Enable loading of images.  Missing images will be loaded without the need for a reload.
1735                 currentWebView.getSettings().setLoadsImagesAutomatically(true);
1736             }
1737
1738             // Consume the event.
1739             return true;
1740         } else if (menuItemId == R.id.dark_webview) {  // Dark WebView.
1741             // Check to see if dark WebView is supported by this WebView.
1742             if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
1743                 // Toggle the dark WebView setting.
1744                 if (WebSettingsCompat.getForceDark(currentWebView.getSettings()) == WebSettingsCompat.FORCE_DARK_ON) {  // Dark WebView is currently enabled.
1745                     // Turn off dark WebView.
1746                     WebSettingsCompat.setForceDark(currentWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
1747                 } else {  // Dark WebView is currently disabled.
1748                     // Turn on dark WebView.
1749                     WebSettingsCompat.setForceDark(currentWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
1750                 }
1751             }
1752
1753             // Consume the event.
1754             return true;
1755         } else if (menuItemId == R.id.find_on_page) {  // Find on page.
1756             // Get a handle for the views.
1757             Toolbar toolbar = findViewById(R.id.toolbar);
1758             LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
1759             EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
1760
1761             // Set the minimum height of the find on page linear layout to match the toolbar.
1762             findOnPageLinearLayout.setMinimumHeight(toolbar.getHeight());
1763
1764             // Hide the toolbar.
1765             toolbar.setVisibility(View.GONE);
1766
1767             // Show the find on page linear layout.
1768             findOnPageLinearLayout.setVisibility(View.VISIBLE);
1769
1770             // Display the keyboard.  The app must wait 200 ms before running the command to work around a bug in Android.
1771             // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1772             findOnPageEditText.postDelayed(() -> {
1773                 // Set the focus on the find on page edit text.
1774                 findOnPageEditText.requestFocus();
1775
1776                 // Get a handle for the input method manager.
1777                 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1778
1779                 // Remove the lint warning below that the input method manager might be null.
1780                 assert inputMethodManager != null;
1781
1782                 // Display the keyboard.  `0` sets no input flags.
1783                 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1784             }, 200);
1785
1786             // Consume the event.
1787             return true;
1788         } else if (menuItemId == R.id.print) {  // Print.
1789             // Get a print manager instance.
1790             PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1791
1792             // Remove the lint error below that print manager might be null.
1793             assert printManager != null;
1794
1795             // Create a print document adapter from the current WebView.
1796             PrintDocumentAdapter printDocumentAdapter = currentWebView.createPrintDocumentAdapter(getString(R.string.print));
1797
1798             // Print the document.
1799             printManager.print(getString(R.string.privacy_browser_webpage), printDocumentAdapter, null);
1800
1801             // Consume the event.
1802             return true;
1803         } else if (menuItemId == R.id.save_url) {  // Save URL.
1804             // Check the download preference.
1805             if (downloadWithExternalApp) {  // Download with an external app.
1806                 downloadUrlWithExternalApp(currentWebView.getCurrentUrl());
1807             } else {  // Handle the download inside of Privacy Browser.
1808                 // Prepare the save dialog.  The dialog will be displayed once the file size and the content disposition have been acquired.
1809                 new PrepareSaveDialog(this, this, getSupportFragmentManager(), currentWebView.getSettings().getUserAgentString(),
1810                         currentWebView.getAcceptCookies()).execute(currentWebView.getCurrentUrl());
1811             }
1812
1813             // Consume the event.
1814             return true;
1815         } else if (menuItemId == R.id.save_archive) {
1816             // Open the file picker with a default file name built from the current domain name.
1817             saveWebpageArchiveActivityResultLauncher.launch(currentWebView.getCurrentDomainName() + ".mht");
1818
1819             // Consume the event.
1820             return true;
1821         } else if (menuItemId == R.id.save_image) {  // Save image.
1822             // Open the file picker with a default file name built from the current domain name.
1823             saveWebpageImageActivityResultLauncher.launch(currentWebView.getCurrentDomainName() + ".png");
1824
1825             // Consume the event.
1826             return true;
1827         } else if (menuItemId == R.id.add_to_homescreen) {  // Add to homescreen.
1828             // Instantiate the create home screen shortcut dialog.
1829             DialogFragment createHomeScreenShortcutDialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView.getTitle(), currentWebView.getUrl(),
1830                     currentWebView.getFavoriteOrDefaultIcon());
1831
1832             // Show the create home screen shortcut dialog.
1833             createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
1834
1835             // Consume the event.
1836             return true;
1837         } else if (menuItemId == R.id.view_source) {  // View source.
1838             // Create an intent to launch the view source activity.
1839             Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
1840
1841             // Add the variables to the intent.
1842             viewSourceIntent.putExtra(ViewSourceActivityKt.CURRENT_URL, currentWebView.getUrl());
1843             viewSourceIntent.putExtra(ViewSourceActivityKt.USER_AGENT, currentWebView.getSettings().getUserAgentString());
1844
1845             // Make it so.
1846             startActivity(viewSourceIntent);
1847
1848             // Consume the event.
1849             return true;
1850         } else if (menuItemId == R.id.share_message) {  // Share a message.
1851             // Prepare the share string.
1852             String shareString = currentWebView.getTitle() + " – " + currentWebView.getUrl();
1853
1854             // Create the share intent.
1855             Intent shareMessageIntent = new Intent(Intent.ACTION_SEND);
1856
1857             // Add the share string to the intent.
1858             shareMessageIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1859
1860             // Set the MIME type.
1861             shareMessageIntent.setType("text/plain");
1862
1863             // Set the intent to open in a new task.
1864             shareMessageIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1865
1866             // Make it so.
1867             startActivity(Intent.createChooser(shareMessageIntent, getString(R.string.share_message)));
1868
1869             // Consume the event.
1870             return true;
1871         } else if (menuItemId == R.id.share_url) {  // Share URL.
1872             // Create the share intent.
1873             Intent shareUrlIntent = new Intent(Intent.ACTION_SEND);
1874
1875             // Add the URL to the intent.
1876             shareUrlIntent.putExtra(Intent.EXTRA_TEXT, currentWebView.getUrl());
1877
1878             // Add the title to the intent.
1879             shareUrlIntent.putExtra(Intent.EXTRA_SUBJECT, currentWebView.getTitle());
1880
1881             // Set the MIME type.
1882             shareUrlIntent.setType("text/plain");
1883
1884             // Set the intent to open in a new task.
1885             shareUrlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1886
1887             //Make it so.
1888             startActivity(Intent.createChooser(shareUrlIntent, getString(R.string.share_url)));
1889
1890             // Consume the event.
1891             return true;
1892         } else if (menuItemId == R.id.open_with_app) {  // Open with app.
1893             // Open the URL with an outside app.
1894             openWithApp(currentWebView.getUrl());
1895
1896             // Consume the event.
1897             return true;
1898         } else if (menuItemId == R.id.open_with_browser) {  // Open with browser.
1899             // Open the URL with an outside browser.
1900             openWithBrowser(currentWebView.getUrl());
1901
1902             // Consume the event.
1903             return true;
1904         } else if (menuItemId == R.id.add_or_edit_domain) {  // Add or edit domain.
1905             // Check if domain settings currently exist.
1906             if (currentWebView.getDomainSettingsApplied()) {  // Edit the current domain settings.
1907                 // Reapply the domain settings on returning to `MainWebViewActivity`.
1908                 reapplyDomainSettingsOnRestart = true;
1909
1910                 // Create an intent to launch the domains activity.
1911                 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1912
1913                 // Add the extra information to the intent.
1914                 domainsIntent.putExtra("load_domain", currentWebView.getDomainSettingsDatabaseId());
1915                 domainsIntent.putExtra("close_on_back", true);
1916                 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1917                 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1918
1919                 // Get the current certificate.
1920                 SslCertificate sslCertificate = currentWebView.getCertificate();
1921
1922                 // Check to see if the SSL certificate is populated.
1923                 if (sslCertificate != null) {
1924                     // Extract the certificate to strings.
1925                     String issuedToCName = sslCertificate.getIssuedTo().getCName();
1926                     String issuedToOName = sslCertificate.getIssuedTo().getOName();
1927                     String issuedToUName = sslCertificate.getIssuedTo().getUName();
1928                     String issuedByCName = sslCertificate.getIssuedBy().getCName();
1929                     String issuedByOName = sslCertificate.getIssuedBy().getOName();
1930                     String issuedByUName = sslCertificate.getIssuedBy().getUName();
1931                     long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1932                     long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1933
1934                     // Add the certificate to the intent.
1935                     domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1936                     domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1937                     domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1938                     domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1939                     domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1940                     domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1941                     domainsIntent.putExtra("ssl_start_date", startDateLong);
1942                     domainsIntent.putExtra("ssl_end_date", endDateLong);
1943                 }
1944
1945                 // Make it so.
1946                 startActivity(domainsIntent);
1947             } else {  // Add a new domain.
1948                 // Apply the new domain settings on returning to `MainWebViewActivity`.
1949                 reapplyDomainSettingsOnRestart = true;
1950
1951                 // Get the current domain
1952                 Uri currentUri = Uri.parse(currentWebView.getUrl());
1953                 String currentDomain = currentUri.getHost();
1954
1955                 // Initialize the database handler.
1956                 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this);
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         // Initialize the bookmarks database helper.
3386         bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this);
3387
3388         // Initialize `currentBookmarksFolder`.  `""` is the home folder in the database.
3389         currentBookmarksFolder = "";
3390
3391         // Load the home folder, which is `""` in the database.
3392         loadBookmarksFolder();
3393
3394         bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
3395             // Convert the id from long to int to match the format of the bookmarks database.
3396             int databaseId = (int) id;
3397
3398             // Get the bookmark cursor for this ID.
3399             Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseId);
3400
3401             // Move the bookmark cursor to the first row.
3402             bookmarkCursor.moveToFirst();
3403
3404             // Act upon the bookmark according to the type.
3405             if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {  // The selected bookmark is a folder.
3406                 // Store the new folder name in `currentBookmarksFolder`.
3407                 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME));
3408
3409                 // Load the new folder.
3410                 loadBookmarksFolder();
3411             } else {  // The selected bookmark is not a folder.
3412                 // Load the bookmark URL.
3413                 loadUrl(currentWebView, bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_URL)));
3414
3415                 // Close the bookmarks drawer.
3416                 drawerLayout.closeDrawer(GravityCompat.END);
3417             }
3418
3419             // Close the `Cursor`.
3420             bookmarkCursor.close();
3421         });
3422
3423         bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
3424             // Convert the database ID from `long` to `int`.
3425             int databaseId = (int) id;
3426
3427             // Find out if the selected bookmark is a folder.
3428             boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
3429
3430             // Check to see if the bookmark is a folder.
3431             if (isFolder) {  // The bookmark is a folder.
3432                 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
3433                 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME));
3434
3435                 // Instantiate the edit folder bookmark dialog.
3436                 DialogFragment editBookmarkFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
3437
3438                 // Show the edit folder bookmark dialog.
3439                 editBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.edit_folder));
3440             } else {  // The bookmark is not a folder.
3441                 // Get the bookmark cursor for this ID.
3442                 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseId);
3443
3444                 // Move the bookmark cursor to the first row.
3445                 bookmarkCursor.moveToFirst();
3446
3447                 // Load the bookmark in a new tab but do not switch to the tab or close the drawer.
3448                 addNewTab(bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_URL)), false);
3449
3450                 // Display a snackbar.
3451                 Snackbar.make(drawerLayout, R.string.bookmark_opened_in_background, Snackbar.LENGTH_SHORT).show();
3452             }
3453
3454             // Consume the event.
3455             return true;
3456         });
3457
3458         // The drawer listener is used to update the navigation menu.
3459         drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
3460             @Override
3461             public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
3462             }
3463
3464             @Override
3465             public void onDrawerOpened(@NonNull View drawerView) {
3466             }
3467
3468             @Override
3469             public void onDrawerClosed(@NonNull View drawerView) {
3470                 // Reset the drawer icon when the drawer is closed.  Otherwise, it is an arrow if the drawer is open when the app is restarted.
3471                 actionBarDrawerToggle.syncState();
3472             }
3473
3474             @Override
3475             public void onDrawerStateChanged(int newState) {
3476                 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) {  // A drawer is opening or closing.
3477                     // Update the navigation menu items if the WebView is not null.
3478                     if (currentWebView != null) {
3479                         navigationBackMenuItem.setEnabled(currentWebView.canGoBack());
3480                         navigationForwardMenuItem.setEnabled(currentWebView.canGoForward());
3481                         navigationHistoryMenuItem.setEnabled((currentWebView.canGoBack() || currentWebView.canGoForward()));
3482                         navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
3483
3484                         // Hide the keyboard (if displayed).
3485                         inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3486                     }
3487
3488                     // 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.
3489                     urlEditText.clearFocus();
3490
3491                     // 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.
3492                     if (currentWebView != null) {
3493                         // Clearing the focus from the WebView removes any text selection markers and context menus, which otherwise draw above the open drawers.
3494                         currentWebView.clearFocus();
3495                     }
3496                 }
3497             }
3498         });
3499
3500         // 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).
3501         customHeaders.put("X-Requested-With", "");
3502
3503         // Inflate a bare WebView to get the default user agent.  It is not used to render content on the screen.
3504         @SuppressLint("InflateParams") View webViewLayout = getLayoutInflater().inflate(R.layout.bare_webview, null, false);
3505
3506         // Get a handle for the WebView.
3507         WebView bareWebView = webViewLayout.findViewById(R.id.bare_webview);
3508
3509         // Store the default user agent.
3510         webViewDefaultUserAgent = bareWebView.getSettings().getUserAgentString();
3511
3512         // Destroy the bare WebView.
3513         bareWebView.destroy();
3514     }
3515
3516     private void applyAppSettings() {
3517         // Get a handle for the shared preferences.
3518         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3519
3520         // Store the values from the shared preferences in variables.
3521         incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3522         sanitizeGoogleAnalytics = sharedPreferences.getBoolean("google_analytics", true);
3523         sanitizeFacebookClickIds = sharedPreferences.getBoolean("facebook_click_ids", true);
3524         sanitizeTwitterAmpRedirects = sharedPreferences.getBoolean("twitter_amp_redirects", true);
3525         proxyMode = sharedPreferences.getString("proxy", getString(R.string.proxy_default_value));
3526         fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3527         downloadWithExternalApp = sharedPreferences.getBoolean(getString(R.string.download_with_external_app_key), false);
3528         hideAppBar = sharedPreferences.getBoolean("hide_app_bar", true);
3529         scrollAppBar = sharedPreferences.getBoolean(getString(R.string.scroll_app_bar_key), true);
3530
3531         // Apply the saved proxy mode if the app has been restarted.
3532         if (savedProxyMode != null) {
3533             // Apply the saved proxy mode.
3534             proxyMode = savedProxyMode;
3535
3536             // Reset the saved proxy mode.
3537             savedProxyMode = null;
3538         }
3539
3540         // Get the search string.
3541         String searchString = sharedPreferences.getString("search", getString(R.string.search_default_value));
3542
3543         // Set the search string.
3544         if (searchString.equals("Custom URL")) {  // A custom search string is used.
3545             searchURL = sharedPreferences.getString("search_custom_url", getString(R.string.search_custom_url_default_value));
3546         } else {  // A custom search string is not used.
3547             searchURL = searchString;
3548         }
3549
3550         // Apply the proxy.
3551         applyProxy(false);
3552
3553         // Adjust the layout and scrolling parameters according to the position of the app bar.
3554         if (bottomAppBar) {  // The app bar is on the bottom.
3555             // Adjust the UI.
3556             if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) {  // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
3557                 // Reset the WebView padding to fill the available space.
3558                 swipeRefreshLayout.setPadding(0, 0, 0, 0);
3559             } else {  // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
3560                 // Move the WebView above the app bar layout.
3561                 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight);
3562
3563                 // Show the app bar if it is scrolled off the screen.
3564                 if (appBarLayout.getTranslationY() != 0) {
3565                     // Animate the bottom app bar onto the screen.
3566                     objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0);
3567
3568                     // Make it so.
3569                     objectAnimator.start();
3570                 }
3571             }
3572         } else {  // The app bar is on the top.
3573             // Get the current layout parameters.  Using coordinator layout parameters allows the `setBehavior()` command and using app bar layout parameters allows the `setScrollFlags()` command.
3574             CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
3575             AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) toolbar.getLayoutParams();
3576             AppBarLayout.LayoutParams findOnPageLayoutParams = (AppBarLayout.LayoutParams) findOnPageLinearLayout.getLayoutParams();
3577             AppBarLayout.LayoutParams tabsLayoutParams = (AppBarLayout.LayoutParams) tabsLinearLayout.getLayoutParams();
3578
3579             // Add the scrolling behavior to the layout parameters.
3580             if (scrollAppBar) {
3581                 // Enable scrolling of the app bar.
3582                 swipeRefreshLayoutParams.setBehavior(new AppBarLayout.ScrollingViewBehavior());
3583                 toolbarLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3584                 findOnPageLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3585                 tabsLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3586             } else {
3587                 // Disable scrolling of the app bar.
3588                 swipeRefreshLayoutParams.setBehavior(null);
3589                 toolbarLayoutParams.setScrollFlags(0);
3590                 findOnPageLayoutParams.setScrollFlags(0);
3591                 tabsLayoutParams.setScrollFlags(0);
3592
3593                 // Expand the app bar if it is currently collapsed.
3594                 appBarLayout.setExpanded(true);
3595             }
3596
3597             // Set the app bar scrolling for each WebView.
3598             for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3599                 // Get the WebView tab fragment.
3600                 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3601
3602                 // Get the fragment view.
3603                 View fragmentView = webViewTabFragment.getView();
3604
3605                 // Only modify the WebViews if they exist.
3606                 if (fragmentView != null) {
3607                     // Get the nested scroll WebView from the tab fragment.
3608                     NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3609
3610                     // Set the app bar scrolling.
3611                     nestedScrollWebView.setNestedScrollingEnabled(scrollAppBar);
3612                 }
3613             }
3614         }
3615
3616         // Update the full screen browsing mode settings.
3617         if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {  // Privacy Browser is currently in full screen browsing mode.
3618             // Update the visibility of the app bar, which might have changed in the settings.
3619             if (hideAppBar) {
3620                 // Hide the tab linear layout.
3621                 tabsLinearLayout.setVisibility(View.GONE);
3622
3623                 // Hide the action bar.
3624                 actionBar.hide();
3625             } else {
3626                 // Show the tab linear layout.
3627                 tabsLinearLayout.setVisibility(View.VISIBLE);
3628
3629                 // Show the action bar.
3630                 actionBar.show();
3631             }
3632
3633             /* Hide the system bars.
3634              * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3635              * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
3636              * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3637              * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3638              */
3639             rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
3640                     View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3641         } else {  // Privacy Browser is not in full screen browsing mode.
3642             // 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.
3643             inFullScreenBrowsingMode = false;
3644
3645             // Show the tab linear layout.
3646             tabsLinearLayout.setVisibility(View.VISIBLE);
3647
3648             // Show the action bar.
3649             actionBar.show();
3650
3651             // Remove the `SYSTEM_UI` flags from the root frame layout.
3652             rootFrameLayout.setSystemUiVisibility(0);
3653         }
3654     }
3655
3656     @Override
3657     public void navigateHistory(@NonNull String url, int steps) {
3658         // Apply the domain settings.
3659         applyDomainSettings(currentWebView, url, false, false, false);
3660
3661         // Load the history entry.
3662         currentWebView.goBackOrForward(steps);
3663     }
3664
3665     @Override
3666     public void pinnedErrorGoBack() {
3667         // Get the current web back forward list.
3668         WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
3669
3670         // Get the previous entry URL.
3671         String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
3672
3673         // Apply the domain settings.
3674         applyDomainSettings(currentWebView, previousUrl, false, false, false);
3675
3676         // Go back.
3677         currentWebView.goBack();
3678     }
3679
3680     // `reloadWebsite` is used if returning from the Domains activity.  Otherwise JavaScript might not function correctly if it is newly enabled.
3681     @SuppressLint("SetJavaScriptEnabled")
3682     private void applyDomainSettings(NestedScrollWebView nestedScrollWebView, String url, boolean resetTab, boolean reloadWebsite, boolean loadUrl) {
3683         // Store the current URL.
3684         nestedScrollWebView.setCurrentUrl(url);
3685
3686         // Parse the URL into a URI.
3687         Uri uri = Uri.parse(url);
3688
3689         // Extract the domain from `uri`.
3690         String newHostName = uri.getHost();
3691
3692         // Strings don't like to be null.
3693         if (newHostName == null) {
3694             newHostName = "";
3695         }
3696
3697         // 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.
3698         if (!nestedScrollWebView.getCurrentDomainName().equals(newHostName) || newHostName.equals("")) {
3699             // Set the new host name as the current domain name.
3700             nestedScrollWebView.setCurrentDomainName(newHostName);
3701
3702             // Reset the ignoring of pinned domain information.
3703             nestedScrollWebView.setIgnorePinnedDomainInformation(false);
3704
3705             // Clear any pinned SSL certificate or IP addresses.
3706             nestedScrollWebView.clearPinnedSslCertificate();
3707             nestedScrollWebView.setPinnedIpAddresses("");
3708
3709             // Reset the favorite icon if specified.
3710             if (resetTab) {
3711                 // Initialize the favorite icon.
3712                 nestedScrollWebView.initializeFavoriteIcon();
3713
3714                 // Get the current page position.
3715                 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
3716
3717                 // Get the corresponding tab.
3718                 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
3719
3720                 // Update the tab if it isn't null, which sometimes happens when restarting from the background.
3721                 if (tab != null) {
3722                     // Get the tab custom view.
3723                     View tabCustomView = tab.getCustomView();
3724
3725                     // Remove the warning below that the tab custom view might be null.
3726                     assert tabCustomView != null;
3727
3728                     // Get the tab views.
3729                     ImageView tabFavoriteIconImageView = tabCustomView.findViewById(R.id.favorite_icon_imageview);
3730                     TextView tabTitleTextView = tabCustomView.findViewById(R.id.title_textview);
3731
3732                     // Set the default favorite icon as the favorite icon for this tab.
3733                     tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nestedScrollWebView.getFavoriteOrDefaultIcon(), 64, 64, true));
3734
3735                     // Set the loading title text.
3736                     tabTitleTextView.setText(R.string.loading);
3737                 }
3738             }
3739
3740             // Initialize the database handler.
3741             DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this);
3742
3743             // Get a full cursor from `domainsDatabaseHelper`.
3744             Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3745
3746             // Initialize `domainSettingsSet`.
3747             Set<String> domainSettingsSet = new HashSet<>();
3748
3749             // Get the domain name column index.
3750             int domainNameColumnIndex = domainNameCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.DOMAIN_NAME);
3751
3752             // Populate the domain settings set.
3753             for (int i = 0; i < domainNameCursor.getCount(); i++) {
3754                 // Move the domains cursor to the current row.
3755                 domainNameCursor.moveToPosition(i);
3756
3757                 // Store the domain name in the domain settings set.
3758                 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3759             }
3760
3761             // Close the domain name cursor.
3762             domainNameCursor.close();
3763
3764             // Initialize the domain name in database variable.
3765             String domainNameInDatabase = null;
3766
3767             // Check the hostname against the domain settings set.
3768             if (domainSettingsSet.contains(newHostName)) {  // The hostname is contained in the domain settings set.
3769                 // Record the domain name in the database.
3770                 domainNameInDatabase = newHostName;
3771
3772                 // Set the domain settings applied tracker to true.
3773                 nestedScrollWebView.setDomainSettingsApplied(true);
3774             } else {  // The hostname is not contained in the domain settings set.
3775                 // Set the domain settings applied tracker to false.
3776                 nestedScrollWebView.setDomainSettingsApplied(false);
3777             }
3778
3779             // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3780             while (!nestedScrollWebView.getDomainSettingsApplied() && newHostName.contains(".")) {  // Stop checking if domain settings are already applied or there are no more `.` in the hostname.
3781                 if (domainSettingsSet.contains("*." + newHostName)) {  // Check the host name prepended by `*.`.
3782                     // Set the domain settings applied tracker to true.
3783                     nestedScrollWebView.setDomainSettingsApplied(true);
3784
3785                     // Store the applied domain names as it appears in the database.
3786                     domainNameInDatabase = "*." + newHostName;
3787                 }
3788
3789                 // Strip out the lowest subdomain of of the host name.
3790                 newHostName = newHostName.substring(newHostName.indexOf(".") + 1);
3791             }
3792
3793
3794             // Get a handle for the shared preferences.
3795             SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3796
3797             // Store the general preference information.
3798             String defaultFontSizeString = sharedPreferences.getString("font_size", getString(R.string.font_size_default_value));
3799             String defaultUserAgentName = sharedPreferences.getString("user_agent", getString(R.string.user_agent_default_value));
3800             boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
3801             String webViewTheme = sharedPreferences.getString("webview_theme", getString(R.string.webview_theme_default_value));
3802             boolean wideViewport = sharedPreferences.getBoolean("wide_viewport", true);
3803             boolean displayWebpageImages = sharedPreferences.getBoolean("display_webpage_images", true);
3804
3805             // Get the WebView theme entry values string array.
3806             String[] webViewThemeEntryValuesStringArray = getResources().getStringArray(R.array.webview_theme_entry_values);
3807
3808             // Get a handle for the cookie manager.
3809             CookieManager cookieManager = CookieManager.getInstance();
3810
3811             // Initialize the user agent array adapter and string array.
3812             ArrayAdapter<CharSequence> userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item);
3813             String[] userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
3814
3815             if (nestedScrollWebView.getDomainSettingsApplied()) {  // The url has custom domain settings.
3816                 // Remove the incorrect lint warning below that the domain name in database might be null.
3817                 assert domainNameInDatabase != null;
3818
3819                 // Get a cursor for the current host.
3820                 Cursor currentDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3821
3822                 // Move to the first position.
3823                 currentDomainSettingsCursor.moveToFirst();
3824
3825                 // Get the settings from the cursor.
3826                 nestedScrollWebView.setDomainSettingsDatabaseId(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ID)));
3827                 nestedScrollWebView.getSettings().setJavaScriptEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3828                 nestedScrollWebView.setAcceptCookies(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.COOKIES)) == 1);
3829                 nestedScrollWebView.getSettings().setDomStorageEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3830                 // Form data can be removed once the minimum API >= 26.
3831                 boolean saveFormData = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3832                 nestedScrollWebView.setEasyListEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3833                 nestedScrollWebView.setEasyPrivacyEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3834                 nestedScrollWebView.setFanboysAnnoyanceListEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3835                 nestedScrollWebView.setFanboysSocialBlockingListEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(
3836                         DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3837                 nestedScrollWebView.setUltraListEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ULTRALIST)) == 1);
3838                 nestedScrollWebView.setUltraPrivacyEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1);
3839                 nestedScrollWebView.setBlockAllThirdPartyRequests(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
3840                 String userAgentName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.USER_AGENT));
3841                 int fontSize = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.FONT_SIZE));
3842                 int swipeToRefreshInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
3843                 int webViewThemeInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.WEBVIEW_THEME));
3844                 int wideViewportInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.WIDE_VIEWPORT));
3845                 int displayWebpageImagesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.DISPLAY_IMAGES));
3846                 boolean pinnedSslCertificate = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3847                 String pinnedSslIssuedToCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3848                 String pinnedSslIssuedToOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3849                 String pinnedSslIssuedToUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3850                 String pinnedSslIssuedByCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3851                 String pinnedSslIssuedByOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3852                 String pinnedSslIssuedByUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3853                 Date pinnedSslStartDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_START_DATE)));
3854                 Date pinnedSslEndDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_END_DATE)));
3855                 boolean pinnedIpAddresses = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.PINNED_IP_ADDRESSES)) == 1);
3856                 String pinnedHostIpAddresses = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.IP_ADDRESSES));
3857
3858                 // Close the current host domain settings cursor.
3859                 currentDomainSettingsCursor.close();
3860
3861                 // If there is a pinned SSL certificate, store it in the WebView.
3862                 if (pinnedSslCertificate) {
3863                     nestedScrollWebView.setPinnedSslCertificate(pinnedSslIssuedToCName, pinnedSslIssuedToOName, pinnedSslIssuedToUName, pinnedSslIssuedByCName, pinnedSslIssuedByOName, pinnedSslIssuedByUName,
3864                             pinnedSslStartDate, pinnedSslEndDate);
3865                 }
3866
3867                 // If there is a pinned IP address, store it in the WebView.
3868                 if (pinnedIpAddresses) {
3869                     nestedScrollWebView.setPinnedIpAddresses(pinnedHostIpAddresses);
3870                 }
3871
3872                 // Apply the cookie domain settings.
3873                 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptCookies());
3874
3875                 // Apply the form data setting if the API < 26.
3876                 if (Build.VERSION.SDK_INT < 26) {
3877                     nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
3878                 }
3879
3880                 // Apply the font size.
3881                 try {  // Try the specified font size to see if it is valid.
3882                     if (fontSize == 0) {  // Apply the default font size.
3883                             // Try to set the font size from the value in the app settings.
3884                             nestedScrollWebView.getSettings().setTextZoom(Integer.parseInt(defaultFontSizeString));
3885                     } else {  // Apply the font size from domain settings.
3886                         nestedScrollWebView.getSettings().setTextZoom(fontSize);
3887                     }
3888                 } catch (Exception exception) {  // The specified font size is invalid
3889                     // Set the font size to be 100%
3890                     nestedScrollWebView.getSettings().setTextZoom(100);
3891                 }
3892
3893                 // Set the user agent.
3894                 if (userAgentName.equals(getString(R.string.system_default_user_agent))) {  // Use the system default user agent.
3895                     // Get the array position of the default user agent name.
3896                     int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3897
3898                     // Set the user agent according to the system default.
3899                     switch (defaultUserAgentArrayPosition) {
3900                         case UNRECOGNIZED_USER_AGENT:  // The default user agent name is not on the canonical list.
3901                             // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3902                             nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
3903                             break;
3904
3905                         case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3906                             // Set the user agent to `""`, which uses the default value.
3907                             nestedScrollWebView.getSettings().setUserAgentString("");
3908                             break;
3909
3910                         case SETTINGS_CUSTOM_USER_AGENT:
3911                             // Set the default custom user agent.
3912                             nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
3913                             break;
3914
3915                         default:
3916                             // Get the user agent string from the user agent data array
3917                             nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
3918                     }
3919                 } else {  // Set the user agent according to the stored name.
3920                     // Get the array position of the user agent name.
3921                     int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
3922
3923                     switch (userAgentArrayPosition) {
3924                         case UNRECOGNIZED_USER_AGENT:  // The user agent name contains a custom user agent.
3925                             nestedScrollWebView.getSettings().setUserAgentString(userAgentName);
3926                             break;
3927
3928                         case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3929                             // Set the user agent to `""`, which uses the default value.
3930                             nestedScrollWebView.getSettings().setUserAgentString("");
3931                             break;
3932
3933                         default:
3934                             // Get the user agent string from the user agent data array.
3935                             nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3936                     }
3937                 }
3938
3939                 // Set swipe to refresh.
3940                 switch (swipeToRefreshInt) {
3941                     case DomainsDatabaseHelper.SYSTEM_DEFAULT:
3942                         // Store the swipe to refresh status in the nested scroll WebView.
3943                         nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
3944
3945                         // Update the swipe refresh layout.
3946                         if (defaultSwipeToRefresh) {  // Swipe to refresh is enabled.
3947                             // Only enable the swipe refresh layout if the WebView is scrolled to the top.  It is updated every time the scroll changes.
3948                             swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
3949                         } else {  // Swipe to refresh is disabled.
3950                             // Disable the swipe refresh layout.
3951                             swipeRefreshLayout.setEnabled(false);
3952                         }
3953                         break;
3954
3955                     case DomainsDatabaseHelper.ENABLED:
3956                         // Store the swipe to refresh status in the nested scroll WebView.
3957                         nestedScrollWebView.setSwipeToRefresh(true);
3958
3959                         // Only enable the swipe refresh layout if the WebView is scrolled to the top.  It is updated every time the scroll changes.
3960                         swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
3961                         break;
3962
3963                     case DomainsDatabaseHelper.DISABLED:
3964                         // Store the swipe to refresh status in the nested scroll WebView.
3965                         nestedScrollWebView.setSwipeToRefresh(false);
3966
3967                         // Disable swipe to refresh.
3968                         swipeRefreshLayout.setEnabled(false);
3969                 }
3970
3971                 // Check to see if WebView themes are supported.
3972                 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
3973                     // Set the WebView theme.
3974                     switch (webViewThemeInt) {
3975                         case DomainsDatabaseHelper.SYSTEM_DEFAULT:
3976                             // Set the WebView theme.  A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
3977                             if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) {  // The light theme is selected.
3978                                 // Turn off the WebView dark mode.
3979                                 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
3980                             } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) {  // The dark theme is selected.
3981                                 // Turn on the WebView dark mode.
3982                                 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
3983                             } else {  // The system default theme is selected.
3984                                 // Get the current system theme status.
3985                                 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
3986
3987                                 // Set the WebView theme according to the current system theme status.
3988                                 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {  // The system is in day mode.
3989                                     // Turn off the WebView dark mode.
3990                                     WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
3991                                 } else {  // The system is in night mode.
3992                                     // Turn on the WebView dark mode.
3993                                     WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
3994                                 }
3995                             }
3996                             break;
3997
3998                         case DomainsDatabaseHelper.LIGHT_THEME:
3999                             // Turn off the WebView dark mode.
4000                             WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4001                             break;
4002
4003                         case DomainsDatabaseHelper.DARK_THEME:
4004                             // Turn on the WebView dark mode.
4005                             WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4006                             break;
4007                     }
4008                 }
4009
4010                 // Set the viewport.
4011                 switch (wideViewportInt) {
4012                     case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4013                         nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
4014                         break;
4015
4016                     case DomainsDatabaseHelper.ENABLED:
4017                         nestedScrollWebView.getSettings().setUseWideViewPort(true);
4018                         break;
4019
4020                     case DomainsDatabaseHelper.DISABLED:
4021                         nestedScrollWebView.getSettings().setUseWideViewPort(false);
4022                         break;
4023                 }
4024
4025                 // Set the loading of webpage images.
4026                 switch (displayWebpageImagesInt) {
4027                     case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4028                         nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4029                         break;
4030
4031                     case DomainsDatabaseHelper.ENABLED:
4032                         nestedScrollWebView.getSettings().setLoadsImagesAutomatically(true);
4033                         break;
4034
4035                     case DomainsDatabaseHelper.DISABLED:
4036                         nestedScrollWebView.getSettings().setLoadsImagesAutomatically(false);
4037                         break;
4038                 }
4039
4040                 // Set a background on the URL relative layout to indicate that custom domain settings are being used.
4041                 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.domain_settings_url_background, null));
4042             } else {  // The new URL does not have custom domain settings.  Load the defaults.
4043                 // Store the values from the shared preferences.
4044                 nestedScrollWebView.getSettings().setJavaScriptEnabled(sharedPreferences.getBoolean("javascript", false));
4045                 nestedScrollWebView.setAcceptCookies(sharedPreferences.getBoolean(getString(R.string.cookies_key), false));
4046                 nestedScrollWebView.getSettings().setDomStorageEnabled(sharedPreferences.getBoolean("dom_storage", false));
4047                 boolean saveFormData = sharedPreferences.getBoolean("save_form_data", false);  // Form data can be removed once the minimum API >= 26.
4048                 nestedScrollWebView.setEasyListEnabled(sharedPreferences.getBoolean("easylist", true));
4049                 nestedScrollWebView.setEasyPrivacyEnabled(sharedPreferences.getBoolean("easyprivacy", true));
4050                 nestedScrollWebView.setFanboysAnnoyanceListEnabled(sharedPreferences.getBoolean("fanboys_annoyance_list", true));
4051                 nestedScrollWebView.setFanboysSocialBlockingListEnabled(sharedPreferences.getBoolean("fanboys_social_blocking_list", true));
4052                 nestedScrollWebView.setUltraListEnabled(sharedPreferences.getBoolean("ultralist", true));
4053                 nestedScrollWebView.setUltraPrivacyEnabled(sharedPreferences.getBoolean("ultraprivacy", true));
4054                 nestedScrollWebView.setBlockAllThirdPartyRequests(sharedPreferences.getBoolean("block_all_third_party_requests", false));
4055
4056                 // Apply the default cookie setting.
4057                 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptCookies());
4058
4059                 // Apply the default font size setting.
4060                 try {
4061                     // Try to set the font size from the value in the app settings.
4062                     nestedScrollWebView.getSettings().setTextZoom(Integer.parseInt(defaultFontSizeString));
4063                 } catch (Exception exception) {
4064                     // If the app settings value is invalid, set the font size to 100%.
4065                     nestedScrollWebView.getSettings().setTextZoom(100);
4066                 }
4067
4068                 // Apply the form data setting if the API < 26.
4069                 if (Build.VERSION.SDK_INT < 26) {
4070                     nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
4071                 }
4072
4073                 // Store the swipe to refresh status in the nested scroll WebView.
4074                 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
4075
4076                 // Update the swipe refresh layout.
4077                 if (defaultSwipeToRefresh) {  // Swipe to refresh is enabled.
4078                     // Only enable the swipe refresh layout if the WebView is scrolled to the top.  It is updated every time the scroll changes.
4079                     swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
4080                 } else {  // Swipe to refresh is disabled.
4081                     // Disable the swipe refresh layout.
4082                     swipeRefreshLayout.setEnabled(false);
4083                 }
4084
4085                 // Reset the pinned variables.
4086                 nestedScrollWebView.setDomainSettingsDatabaseId(-1);
4087
4088                 // Get the array position of the user agent name.
4089                 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4090
4091                 // Set the user agent.
4092                 switch (userAgentArrayPosition) {
4093                     case UNRECOGNIZED_USER_AGENT:  // The default user agent name is not on the canonical list.
4094                         // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4095                         nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
4096                         break;
4097
4098                     case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4099                         // Set the user agent to `""`, which uses the default value.
4100                         nestedScrollWebView.getSettings().setUserAgentString("");
4101                         break;
4102
4103                     case SETTINGS_CUSTOM_USER_AGENT:
4104                         // Set the default custom user agent.
4105                         nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
4106                         break;
4107
4108                     default:
4109                         // Get the user agent string from the user agent data array
4110                         nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4111                 }
4112
4113                 // Apply the WebView theme if supported by the installed WebView.
4114                 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
4115                     // Set the WebView theme.  A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
4116                     if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) {  // The light theme is selected.
4117                         // Turn off the WebView dark mode.
4118                         WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4119                     } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) {  // The dark theme is selected.
4120                         // Turn on the WebView dark mode.
4121                         WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4122                     } else {  // The system default theme is selected.
4123                         // Get the current system theme status.
4124                         int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4125
4126                         // Set the WebView theme according to the current system theme status.
4127                         if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {  // The system is in day mode.
4128                             // Turn off the WebView dark mode.
4129                             WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4130                         } else {  // The system is in night mode.
4131                             // Turn on the WebView dark mode.
4132                             WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4133                         }
4134                     }
4135                 }
4136
4137                 // Set the viewport.
4138                 nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
4139
4140                 // Set the loading of webpage images.
4141                 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4142
4143                 // Set a transparent background on the URL relative layout.
4144                 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.color.transparent, null));
4145             }
4146
4147             // Close the domains database helper.
4148             domainsDatabaseHelper.close();
4149
4150             // Update the privacy icons.
4151             updatePrivacyIcons(true);
4152         }
4153
4154         // Reload the website if returning from the Domains activity.
4155         if (reloadWebsite) {
4156             nestedScrollWebView.reload();
4157         }
4158
4159         // 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.
4160         if (loadUrl) {
4161             nestedScrollWebView.loadUrl(url, customHeaders);
4162         }
4163     }
4164
4165     private void applyProxy(boolean reloadWebViews) {
4166         // Set the proxy according to the mode.
4167         proxyHelper.setProxy(getApplicationContext(), appBarLayout, proxyMode);
4168
4169         // Reset the waiting for proxy tracker.
4170         waitingForProxy = false;
4171
4172         // Get the current theme status.
4173         int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4174
4175         // Update the user interface and reload the WebViews if requested.
4176         switch (proxyMode) {
4177             case ProxyHelper.NONE:
4178                 // Initialize a color background typed value.
4179                 TypedValue colorBackgroundTypedValue = new TypedValue();
4180
4181                 // Get the color background from the theme.
4182                 getTheme().resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true);
4183
4184                 // Get the color background int from the typed value.
4185                 int colorBackgroundInt = colorBackgroundTypedValue.data;
4186
4187                 // Set the default app bar layout background.
4188                 appBarLayout.setBackgroundColor(colorBackgroundInt);
4189                 break;
4190
4191             case ProxyHelper.TOR:
4192                 // Set the app bar background to indicate proxying through Orbot is enabled.
4193                 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4194                     appBarLayout.setBackgroundResource(R.color.blue_50);
4195                 } else {
4196                     appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4197                 }
4198
4199                 // Check to see if Orbot is installed.
4200                 try {
4201                     // Get the package manager.
4202                     PackageManager packageManager = getPackageManager();
4203
4204                     // 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.
4205                     packageManager.getPackageInfo("org.torproject.android", 0);
4206
4207                     // Check to see if the proxy is ready.
4208                     if (!orbotStatus.equals(ProxyHelper.ORBOT_STATUS_ON)) {  // Orbot is not ready.
4209                         // Set the waiting for proxy status.
4210                         waitingForProxy = true;
4211
4212                         // Show the waiting for proxy dialog if it isn't already displayed.
4213                         if (getSupportFragmentManager().findFragmentByTag(getString(R.string.waiting_for_proxy_dialog)) == null) {
4214                             // Get a handle for the waiting for proxy alert dialog.
4215                             DialogFragment waitingForProxyDialogFragment = new WaitingForProxyDialog();
4216
4217                             // Try to show the dialog.  Sometimes the window is not yet active if returning from Settings.
4218                             try {
4219                                 // Show the waiting for proxy alert dialog.
4220                                 waitingForProxyDialogFragment.show(getSupportFragmentManager(), getString(R.string.waiting_for_proxy_dialog));
4221                             } catch (Exception waitingForTorException) {
4222                                 // Add the dialog to the pending dialog array list.  It will be displayed in `onStart()`.
4223                                 pendingDialogsArrayList.add(new PendingDialog(waitingForProxyDialogFragment, getString(R.string.waiting_for_proxy_dialog)));
4224                             }
4225                         }
4226                     }
4227                 } catch (PackageManager.NameNotFoundException exception) {  // Orbot is not installed.
4228                     // Show the Orbot not installed dialog if it is not already displayed.
4229                     if (getSupportFragmentManager().findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
4230                         // Get a handle for the Orbot not installed alert dialog.
4231                         DialogFragment orbotNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode);
4232
4233                         // Try to show the dialog.  Sometimes the window is not yet active if returning from Settings.
4234                         try {
4235                             // Display the Orbot not installed alert dialog.
4236                             orbotNotInstalledDialogFragment.show(getSupportFragmentManager(), getString(R.string.proxy_not_installed_dialog));
4237                         } catch (Exception orbotNotInstalledException) {
4238                             // Add the dialog to the pending dialog array list.  It will be displayed in `onStart()`.
4239                             pendingDialogsArrayList.add(new PendingDialog(orbotNotInstalledDialogFragment, getString(R.string.proxy_not_installed_dialog)));
4240                         }
4241                     }
4242                 }
4243                 break;
4244
4245             case ProxyHelper.I2P:
4246                 // Set the app bar background to indicate proxying through Orbot is enabled.
4247                 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4248                     appBarLayout.setBackgroundResource(R.color.blue_50);
4249                 } else {
4250                     appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4251                 }
4252
4253                 // Check to see if I2P is installed.
4254                 try {
4255                     // Get the package manager.
4256                     PackageManager packageManager = getPackageManager();
4257
4258                     // 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.
4259                     packageManager.getPackageInfo("net.i2p.android.router", 0);
4260                 } catch (PackageManager.NameNotFoundException exception) {  // I2P is not installed.
4261                     // Sow the I2P not installed dialog if it is not already displayed.
4262                     if (getSupportFragmentManager().findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
4263                         // Get a handle for the waiting for proxy alert dialog.
4264                         DialogFragment i2pNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode);
4265
4266                         // Try to show the dialog.  Sometimes the window is not yet active if returning from Settings.
4267                         try {
4268                             // Display the I2P not installed alert dialog.
4269                             i2pNotInstalledDialogFragment.show(getSupportFragmentManager(), getString(R.string.proxy_not_installed_dialog));
4270                         } catch (Exception i2pNotInstalledException) {
4271                             // Add the dialog to the pending dialog array list.  It will be displayed in `onStart()`.
4272                             pendingDialogsArrayList.add(new PendingDialog(i2pNotInstalledDialogFragment, getString(R.string.proxy_not_installed_dialog)));
4273                         }
4274                     }
4275                 }
4276                 break;
4277
4278             case ProxyHelper.CUSTOM:
4279                 // Set the app bar background to indicate proxying through Orbot is enabled.
4280                 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4281                     appBarLayout.setBackgroundResource(R.color.blue_50);
4282                 } else {
4283                     appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4284                 }
4285                 break;
4286         }
4287
4288         // Reload the WebViews if requested and not waiting for the proxy.
4289         if (reloadWebViews && !waitingForProxy) {
4290             // Reload the WebViews.
4291             for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4292                 // Get the WebView tab fragment.
4293                 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4294
4295                 // Get the fragment view.
4296                 View fragmentView = webViewTabFragment.getView();
4297
4298                 // Only reload the WebViews if they exist.
4299                 if (fragmentView != null) {
4300                     // Get the nested scroll WebView from the tab fragment.
4301                     NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4302
4303                     // Reload the WebView.
4304                     nestedScrollWebView.reload();
4305                 }
4306             }
4307         }
4308     }
4309
4310     private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
4311         // Only update the privacy icons if the options menu and the current WebView have already been populated.
4312         if ((optionsMenu != null) && (currentWebView != null)) {
4313             // Update the privacy icon.
4314             if (currentWebView.getSettings().getJavaScriptEnabled()) {  // JavaScript is enabled.
4315                 optionsPrivacyMenuItem.setIcon(R.drawable.javascript_enabled);
4316             } else if (currentWebView.getAcceptCookies()) {  // JavaScript is disabled but cookies are enabled.
4317                 optionsPrivacyMenuItem.setIcon(R.drawable.warning);
4318             } else {  // All the dangerous features are disabled.
4319                 optionsPrivacyMenuItem.setIcon(R.drawable.privacy_mode);
4320             }
4321
4322             // Update the cookies icon.
4323             if (currentWebView.getAcceptCookies()) {
4324                 optionsCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
4325             } else {
4326                 optionsCookiesMenuItem.setIcon(R.drawable.cookies_disabled);
4327             }
4328
4329             // Update the refresh icon.
4330             if (optionsRefreshMenuItem.getTitle() == getString(R.string.refresh)) {  // The refresh icon is displayed.
4331                 // Set the icon.  Once the minimum API is >= 26, the blue and black icons can be combined with a tint list.
4332                 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled);
4333             } else {  // The stop icon is displayed.
4334                 // Set the icon.  Once the minimum API is >= 26, the blue and black icons can be combined with a tint list.
4335                 optionsRefreshMenuItem.setIcon(R.drawable.close_blue);
4336             }
4337
4338             // `invalidateOptionsMenu()` calls `onPrepareOptionsMenu()` and redraws the icons in the app bar.
4339             if (runInvalidateOptionsMenu) {
4340                 invalidateOptionsMenu();
4341             }
4342         }
4343     }
4344
4345     private void highlightUrlText() {
4346         // Only highlight the URL text if the box is not currently selected.
4347         if (!urlEditText.hasFocus()) {
4348             // Get the URL string.
4349             String urlString = urlEditText.getText().toString();
4350
4351             // Highlight the URL according to the protocol.
4352             if (urlString.startsWith("file://") || urlString.startsWith("content://")) {  // This is a file or content URL.
4353                 // De-emphasize everything before the file name.
4354                 urlEditText.getText().setSpan(initialGrayColorSpan, 0, urlString.lastIndexOf("/") + 1,Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4355             } else {  // This is a web URL.
4356                 // Get the index of the `/` immediately after the domain name.
4357                 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
4358
4359                 // Create a base URL string.
4360                 String baseUrl;
4361
4362                 // Get the base URL.
4363                 if (endOfDomainName > 0) {  // There is at least one character after the base URL.
4364                     // Get the base URL.
4365                     baseUrl = urlString.substring(0, endOfDomainName);
4366                 } else {  // There are no characters after the base URL.
4367                     // Set the base URL to be the entire URL string.
4368                     baseUrl = urlString;
4369                 }
4370
4371                 // Get the index of the last `.` in the domain.
4372                 int lastDotIndex = baseUrl.lastIndexOf(".");
4373
4374                 // Get the index of the penultimate `.` in the domain.
4375                 int penultimateDotIndex = baseUrl.lastIndexOf(".", lastDotIndex - 1);
4376
4377                 // Markup the beginning of the URL.
4378                 if (urlString.startsWith("http://")) {  // Highlight the protocol of connections that are not encrypted.
4379                     urlEditText.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4380
4381                     // De-emphasize subdomains.
4382                     if (penultimateDotIndex > 0) {  // There is more than one subdomain in the domain name.
4383                         urlEditText.getText().setSpan(initialGrayColorSpan, 7, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4384                     }
4385                 } else if (urlString.startsWith("https://")) {  // De-emphasize the protocol of connections that are encrypted.
4386                     if (penultimateDotIndex > 0) {  // There is more than one subdomain in the domain name.
4387                         // De-emphasize the protocol and the additional subdomains.
4388                         urlEditText.getText().setSpan(initialGrayColorSpan, 0, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4389                     } else {  // There is only one subdomain in the domain name.
4390                         // De-emphasize only the protocol.
4391                         urlEditText.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4392                     }
4393                 }
4394
4395                 // De-emphasize the text after the domain name.
4396                 if (endOfDomainName > 0) {
4397                     urlEditText.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4398                 }
4399             }
4400         }
4401     }
4402
4403     private void loadBookmarksFolder() {
4404         // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
4405         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
4406
4407         // Populate the bookmarks cursor adapter.
4408         bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
4409             @Override
4410             public View newView(Context context, Cursor cursor, ViewGroup parent) {
4411                 // Inflate the individual item layout.
4412                 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
4413             }
4414
4415             @Override
4416             public void bindView(View view, Context context, Cursor cursor) {
4417                 // Get handles for the views.
4418                 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
4419                 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
4420
4421                 // Get the favorite icon byte array from the cursor.
4422                 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.FAVORITE_ICON));
4423
4424                 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
4425                 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
4426
4427                 // Display the bitmap in `bookmarkFavoriteIcon`.
4428                 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4429
4430                 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4431                 String bookmarkNameString = cursor.getString(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME));
4432                 bookmarkNameTextView.setText(bookmarkNameString);
4433
4434                 // Make the font bold for folders.
4435                 if (cursor.getInt(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4436                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4437                 } else {  // Reset the font to default for normal bookmarks.
4438                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4439                 }
4440             }
4441         };
4442
4443         // Get a handle for the bookmarks list view.
4444         ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
4445
4446         // Populate the list view with the adapter.
4447         bookmarksListView.setAdapter(bookmarksCursorAdapter);
4448
4449         // Get a handle for the bookmarks title text view.
4450         TextView bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
4451
4452         // Set the bookmarks drawer title.
4453         if (currentBookmarksFolder.isEmpty()) {
4454             bookmarksTitleTextView.setText(R.string.bookmarks);
4455         } else {
4456             bookmarksTitleTextView.setText(currentBookmarksFolder);
4457         }
4458     }
4459
4460     private void openWithApp(String url) {
4461         // Create an open with app intent with `ACTION_VIEW`.
4462         Intent openWithAppIntent = new Intent(Intent.ACTION_VIEW);
4463
4464         // Set the URI but not the MIME type.  This should open all available apps.
4465         openWithAppIntent.setData(Uri.parse(url));
4466
4467         // Flag the intent to open in a new task.
4468         openWithAppIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4469
4470         // Try the intent.
4471         try {
4472             // Show the chooser.
4473             startActivity(openWithAppIntent);
4474         } catch (ActivityNotFoundException exception) {  // There are no apps available to open the URL.
4475             // Show a snackbar with the error.
4476             Snackbar.make(currentWebView, getString(R.string.error) + "  " + exception, Snackbar.LENGTH_INDEFINITE).show();
4477         }
4478     }
4479
4480     private void openWithBrowser(String url) {
4481         // Create an open with browser intent with `ACTION_VIEW`.
4482         Intent openWithBrowserIntent = new Intent(Intent.ACTION_VIEW);
4483
4484         // Set the URI and the MIME type.  `"text/html"` should load browser options.
4485         openWithBrowserIntent.setDataAndType(Uri.parse(url), "text/html");
4486
4487         // Flag the intent to open in a new task.
4488         openWithBrowserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4489
4490         // Try the intent.
4491         try {
4492             // Show the chooser.
4493             startActivity(openWithBrowserIntent);
4494         } catch (ActivityNotFoundException exception) {  // There are no browsers available to open the URL.
4495             // Show a snackbar with the error.
4496             Snackbar.make(currentWebView, getString(R.string.error) + "  " + exception, Snackbar.LENGTH_INDEFINITE).show();
4497         }
4498     }
4499
4500     private String sanitizeUrl(String url) {
4501         // Sanitize Google Analytics.
4502         if (sanitizeGoogleAnalytics) {
4503             // Remove `?utm_`.
4504             if (url.contains("?utm_")) {
4505                 url = url.substring(0, url.indexOf("?utm_"));
4506             }
4507
4508             // Remove `&utm_`.
4509             if (url.contains("&utm_")) {
4510                 url = url.substring(0, url.indexOf("&utm_"));
4511             }
4512         }
4513
4514         // Sanitize Facebook Click IDs.
4515         if (sanitizeFacebookClickIds) {
4516             // Remove `?fbclid=`.
4517             if (url.contains("?fbclid=")) {
4518                 url = url.substring(0, url.indexOf("?fbclid="));
4519             }
4520
4521             // Remove `&fbclid=`.
4522             if (url.contains("&fbclid=")) {
4523                 url = url.substring(0, url.indexOf("&fbclid="));
4524             }
4525
4526             // Remove `?fbadid=`.
4527             if (url.contains("?fbadid=")) {
4528                 url = url.substring(0, url.indexOf("?fbadid="));
4529             }
4530
4531             // Remove `&fbadid=`.
4532             if (url.contains("&fbadid=")) {
4533                 url = url.substring(0, url.indexOf("&fbadid="));
4534             }
4535         }
4536
4537         // Sanitize Twitter AMP redirects.
4538         if (sanitizeTwitterAmpRedirects) {
4539             // Remove `?amp=1`.
4540             if (url.contains("?amp=1")) {
4541                 url = url.substring(0, url.indexOf("?amp=1"));
4542             }
4543         }
4544
4545         // Return the sanitized URL.
4546         return url;
4547     }
4548
4549     public void finishedPopulatingBlocklists(ArrayList<ArrayList<List<String[]>>> combinedBlocklists) {
4550         // Store the blocklists.
4551         easyList = combinedBlocklists.get(0);
4552         easyPrivacy = combinedBlocklists.get(1);
4553         fanboysAnnoyanceList = combinedBlocklists.get(2);
4554         fanboysSocialList = combinedBlocklists.get(3);
4555         ultraList = combinedBlocklists.get(4);
4556         ultraPrivacy = combinedBlocklists.get(5);
4557
4558         // Check to see if the activity has been restarted with a saved state.
4559         if ((savedStateArrayList == null) || (savedStateArrayList.size() == 0)) {  // The activity has not been restarted or it was restarted on start to force the night theme.
4560             // Add the first tab.
4561             addNewTab("", true);
4562         } else {  // The activity has been restarted.
4563             // Restore each tab.  Once the minimum API >= 24, a `forEach()` command can be used.
4564             for (int i = 0; i < savedStateArrayList.size(); i++) {
4565                 // Add a new tab.
4566                 tabLayout.addTab(tabLayout.newTab());
4567
4568                 // Get the new tab.
4569                 TabLayout.Tab newTab = tabLayout.getTabAt(i);
4570
4571                 // Remove the lint warning below that the current tab might be null.
4572                 assert newTab != null;
4573
4574                 // Set a custom view on the new tab.
4575                 newTab.setCustomView(R.layout.tab_custom_view);
4576
4577                 // Add the new page.
4578                 webViewPagerAdapter.restorePage(savedStateArrayList.get(i), savedNestedScrollWebViewStateArrayList.get(i));
4579             }
4580
4581             // Reset the saved state variables.
4582             savedStateArrayList = null;
4583             savedNestedScrollWebViewStateArrayList = null;
4584
4585             // Restore the selected tab position.
4586             if (savedTabPosition == 0) {  // The first tab is selected.
4587                 // Set the first page as the current WebView.
4588                 setCurrentWebView(0);
4589             } else {  // the first tab is not selected.
4590                 // Move to the selected tab.
4591                 webViewPager.setCurrentItem(savedTabPosition);
4592             }
4593
4594             // Get the intent that started the app.
4595             Intent intent = getIntent();
4596
4597             // Reset the intent.  This prevents a duplicate tab from being created on restart.
4598             setIntent(new Intent());
4599
4600             // Get the information from the intent.
4601             String intentAction = intent.getAction();
4602             Uri intentUriData = intent.getData();
4603             String intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT);
4604
4605             // Determine if this is a web search.
4606             boolean isWebSearch = ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH));
4607
4608             // 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.
4609             if (intentUriData != null || intentStringExtra != null || isWebSearch) {
4610                 // Get the shared preferences.
4611                 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4612
4613                 // Create a URL string.
4614                 String url;
4615
4616                 // If the intent action is a web search, perform the search.
4617                 if (isWebSearch) {  // The intent is a web search.
4618                     // Create an encoded URL string.
4619                     String encodedUrlString;
4620
4621                     // Sanitize the search input and convert it to a search.
4622                     try {
4623                         encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
4624                     } catch (UnsupportedEncodingException exception) {
4625                         encodedUrlString = "";
4626                     }
4627
4628                     // Add the base search URL.
4629                     url = searchURL + encodedUrlString;
4630                 } else if (intentUriData != null) {  // The intent contains a URL formatted as a URI.
4631                     // Set the intent data as the URL.
4632                     url = intentUriData.toString();
4633                 } else {  // The intent contains a string, which might be a URL.
4634                     // Set the intent string as the URL.
4635                     url = intentStringExtra;
4636                 }
4637
4638                 // Add a new tab if specified in the preferences.
4639                 if (sharedPreferences.getBoolean("open_intents_in_new_tab", true)) {  // Load the URL in a new tab.
4640                     // Set the loading new intent flag.
4641                     loadingNewIntent = true;
4642
4643                     // Add a new tab.
4644                     addNewTab(url, true);
4645                 } else {  // Load the URL in the current tab.
4646                     // Make it so.
4647                     loadUrl(currentWebView, url);
4648                 }
4649             }
4650         }
4651     }
4652
4653     public void addTab(View view) {
4654         // Add a new tab with a blank URL.
4655         addNewTab("", true);
4656     }
4657
4658     private void addNewTab(String url, boolean moveToTab) {
4659         // Clear the focus from the URL edit text, so that it will be populated with the information from the new tab.
4660         urlEditText.clearFocus();
4661
4662         // Get the new page number.  The page numbers are 0 indexed, so the new page number will match the current count.
4663         int newTabNumber = tabLayout.getTabCount();
4664
4665         // Add a new tab.
4666         tabLayout.addTab(tabLayout.newTab());
4667
4668         // Get the new tab.
4669         TabLayout.Tab newTab = tabLayout.getTabAt(newTabNumber);
4670
4671         // Remove the lint warning below that the current tab might be null.
4672         assert newTab != null;
4673
4674         // Set a custom view on the new tab.
4675         newTab.setCustomView(R.layout.tab_custom_view);
4676
4677         // Add the new WebView page.
4678         webViewPagerAdapter.addPage(newTabNumber, webViewPager, url, moveToTab);
4679
4680         // Show the app bar if it is at the bottom of the screen and the new tab is taking focus.
4681         if (bottomAppBar && moveToTab && (appBarLayout.getTranslationY() != 0)) {
4682             // Animate the bottom app bar onto the screen.
4683             objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0);
4684
4685             // Make it so.
4686             objectAnimator.start();
4687         }
4688     }
4689
4690     public void closeTab(View view) {
4691         // Run the command according to the number of tabs.
4692         if (tabLayout.getTabCount() > 1) {  // There is more than one tab open.
4693             // Close the current tab.
4694             closeCurrentTab();
4695         } else {  // There is only one tab open.
4696             clearAndExit();
4697         }
4698     }
4699
4700     private void closeCurrentTab() {
4701         // Get the current tab number.
4702         int currentTabNumber = tabLayout.getSelectedTabPosition();
4703
4704         // Delete the current tab.
4705         tabLayout.removeTabAt(currentTabNumber);
4706
4707         // 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,
4708         // meaning that the current WebView must be reset.  Otherwise it will happen automatically as the selected tab number changes.
4709         if (webViewPagerAdapter.deletePage(currentTabNumber, webViewPager)) {
4710             setCurrentWebView(currentTabNumber);
4711         }
4712     }
4713
4714     private void exitFullScreenVideo() {
4715         // Re-enable the screen timeout.
4716         fullScreenVideoFrameLayout.setKeepScreenOn(false);
4717
4718         // Unset the full screen video flag.
4719         displayingFullScreenVideo = false;
4720
4721         // Remove all the views from the full screen video frame layout.
4722         fullScreenVideoFrameLayout.removeAllViews();
4723
4724         // Hide the full screen video frame layout.
4725         fullScreenVideoFrameLayout.setVisibility(View.GONE);
4726
4727         // Enable the sliding drawers.
4728         drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
4729
4730         // Show the coordinator layout.
4731         coordinatorLayout.setVisibility(View.VISIBLE);
4732
4733         // Apply the appropriate full screen mode flags.
4734         if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {  // Privacy Browser is currently in full screen browsing mode.
4735             // Hide the app bar if specified.
4736             if (hideAppBar) {
4737                 // Hide the tab linear layout.
4738                 tabsLinearLayout.setVisibility(View.GONE);
4739
4740                 // Hide the action bar.
4741                 actionBar.hide();
4742             }
4743
4744             /* Hide the system bars.
4745              * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4746              * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4747              * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4748              * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4749              */
4750             rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
4751                     View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
4752         } else {  // Switch to normal viewing mode.
4753             // Remove the `SYSTEM_UI` flags from the root frame layout.
4754             rootFrameLayout.setSystemUiVisibility(0);
4755         }
4756     }
4757
4758     private void clearAndExit() {
4759         // Get a handle for the shared preferences.
4760         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4761
4762         // Close the bookmarks cursor and database.
4763         bookmarksCursor.close();
4764         bookmarksDatabaseHelper.close();
4765
4766         // Get the status of the clear everything preference.
4767         boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
4768
4769         // Get a handle for the runtime.
4770         Runtime runtime = Runtime.getRuntime();
4771
4772         // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
4773         // which links to `/data/data/com.stoutner.privacybrowser.standard`.
4774         String privateDataDirectoryString = getApplicationInfo().dataDir;
4775
4776         // Clear cookies.
4777         if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
4778             // Request the cookies be deleted.
4779             CookieManager.getInstance().removeAllCookies(null);
4780
4781             // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4782             try {
4783                 // Two commands must be used because `Runtime.exec()` does not like `*`.
4784                 Process deleteCookiesProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
4785                 Process deleteCookiesJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
4786
4787                 // Wait until the processes have finished.
4788                 deleteCookiesProcess.waitFor();
4789                 deleteCookiesJournalProcess.waitFor();
4790             } catch (Exception exception) {
4791                 // Do nothing if an error is thrown.
4792             }
4793         }
4794
4795         // Clear DOM storage.
4796         if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
4797             // Ask `WebStorage` to clear the DOM storage.
4798             WebStorage webStorage = WebStorage.getInstance();
4799             webStorage.deleteAllData();
4800
4801             // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4802             try {
4803                 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4804                 Process deleteLocalStorageProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
4805
4806                 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
4807                 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
4808                 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
4809                 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
4810                 Process deleteDatabaseProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
4811
4812                 // Wait until the processes have finished.
4813                 deleteLocalStorageProcess.waitFor();
4814                 deleteIndexProcess.waitFor();
4815                 deleteQuotaManagerProcess.waitFor();
4816                 deleteQuotaManagerJournalProcess.waitFor();
4817                 deleteDatabaseProcess.waitFor();
4818             } catch (Exception exception) {
4819                 // Do nothing if an error is thrown.
4820             }
4821         }
4822
4823         // Clear form data if the API < 26.
4824         if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
4825             WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
4826             webViewDatabase.clearFormData();
4827
4828             // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4829             try {
4830                 // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
4831                 Process deleteWebDataProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
4832                 Process deleteWebDataJournalProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
4833
4834                 // Wait until the processes have finished.
4835                 deleteWebDataProcess.waitFor();
4836                 deleteWebDataJournalProcess.waitFor();
4837             } catch (Exception exception) {
4838                 // Do nothing if an error is thrown.
4839             }
4840         }
4841
4842         // Clear the logcat.
4843         if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_logcat_key), true)) {
4844             try {
4845                 // Clear the logcat.  `-c` clears the logcat.  `-b all` clears all the buffers (instead of just crash, main, and system).
4846                 Process process = Runtime.getRuntime().exec("logcat -b all -c");
4847
4848                 // Wait for the process to finish.
4849                 process.waitFor();
4850             } catch (IOException|InterruptedException exception) {
4851                 // Do nothing.
4852             }
4853         }
4854
4855         // Clear the cache.
4856         if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
4857             // Clear the cache from each WebView.
4858             for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4859                 // Get the WebView tab fragment.
4860                 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4861
4862                 // Get the WebView fragment view.
4863                 View webViewFragmentView = webViewTabFragment.getView();
4864
4865                 // Only clear the cache if the WebView exists.
4866                 if (webViewFragmentView != null) {
4867                     // Get the nested scroll WebView from the tab fragment.
4868                     NestedScrollWebView nestedScrollWebView = webViewFragmentView.findViewById(R.id.nestedscroll_webview);
4869
4870                     // Clear the cache for this WebView.
4871                     nestedScrollWebView.clearCache(true);
4872                 }
4873             }
4874
4875             // Manually delete the cache directories.
4876             try {
4877                 // Delete the main cache directory.
4878                 Process deleteCacheProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/cache");
4879
4880                 // Delete the secondary `Service Worker` cache directory.
4881                 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4882                 Process deleteServiceWorkerProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
4883
4884                 // Wait until the processes have finished.
4885                 deleteCacheProcess.waitFor();
4886                 deleteServiceWorkerProcess.waitFor();
4887             } catch (Exception exception) {
4888                 // Do nothing if an error is thrown.
4889             }
4890         }
4891
4892         // Wipe out each WebView.
4893         for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4894             // Get the WebView tab fragment.
4895             WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4896
4897             // Get the WebView frame layout.
4898             FrameLayout webViewFrameLayout = (FrameLayout) webViewTabFragment.getView();
4899
4900             // Only wipe out the WebView if it exists.
4901             if (webViewFrameLayout != null) {
4902                 // Get the nested scroll WebView from the tab fragment.
4903                 NestedScrollWebView nestedScrollWebView = webViewFrameLayout.findViewById(R.id.nestedscroll_webview);
4904
4905                 // Clear SSL certificate preferences for this WebView.
4906                 nestedScrollWebView.clearSslPreferences();
4907
4908                 // Clear the back/forward history for this WebView.
4909                 nestedScrollWebView.clearHistory();
4910
4911                 // Remove all the views from the frame layout.
4912                 webViewFrameLayout.removeAllViews();
4913
4914                 // Destroy the internal state of the WebView.
4915                 nestedScrollWebView.destroy();
4916             }
4917         }
4918
4919         // Clear the custom headers.
4920         customHeaders.clear();
4921
4922         // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
4923         // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
4924         if (clearEverything) {
4925             try {
4926                 // Delete the folder.
4927                 Process deleteAppWebviewProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
4928
4929                 // Wait until the process has finished.
4930                 deleteAppWebviewProcess.waitFor();
4931             } catch (Exception exception) {
4932                 // Do nothing if an error is thrown.
4933             }
4934         }
4935
4936         // Close Privacy Browser.  `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
4937         finishAndRemoveTask();
4938
4939         // Remove the terminated program from RAM.  The status code is `0`.
4940         System.exit(0);
4941     }
4942
4943     public void bookmarksBack(View view) {
4944         if (currentBookmarksFolder.isEmpty()) {  // The home folder is displayed.
4945             // close the bookmarks drawer.
4946             drawerLayout.closeDrawer(GravityCompat.END);
4947         } else {  // A subfolder is displayed.
4948             // Place the former parent folder in `currentFolder`.
4949             currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolderName(currentBookmarksFolder);
4950
4951             // Load the new folder.
4952             loadBookmarksFolder();
4953         }
4954     }
4955
4956     private void setCurrentWebView(int pageNumber) {
4957         // Stop the swipe to refresh indicator if it is running
4958         swipeRefreshLayout.setRefreshing(false);
4959
4960         // Get the WebView tab fragment.
4961         WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(pageNumber);
4962
4963         // Get the fragment view.
4964         View webViewFragmentView = webViewTabFragment.getView();
4965
4966         // Set the current WebView if the fragment view is not null.
4967         if (webViewFragmentView != null) {  // The fragment has been populated.
4968             // Store the current WebView.
4969             currentWebView = webViewFragmentView.findViewById(R.id.nestedscroll_webview);
4970
4971             // Update the status of swipe to refresh.
4972             if (currentWebView.getSwipeToRefresh()) {  // Swipe to refresh is enabled.
4973                 // Enable the swipe refresh layout if the WebView is scrolled all the way to the top.  It is updated every time the scroll changes.
4974                 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
4975             } else {  // Swipe to refresh is disabled.
4976                 // Disable the swipe refresh layout.
4977                 swipeRefreshLayout.setEnabled(false);
4978             }
4979
4980             // Get a handle for the cookie manager.
4981             CookieManager cookieManager = CookieManager.getInstance();
4982
4983             // Set the cookie status.
4984             cookieManager.setAcceptCookie(currentWebView.getAcceptCookies());
4985
4986             // Update the privacy icons.  `true` redraws the icons in the app bar.
4987             updatePrivacyIcons(true);
4988
4989             // Get a handle for the input method manager.
4990             InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
4991
4992             // Remove the lint warning below that the input method manager might be null.
4993             assert inputMethodManager != null;
4994
4995             // Get the current URL.
4996             String url = currentWebView.getUrl();
4997
4998             // Update the URL edit text if not loading a new intent.  Otherwise, this will be handled by `onPageStarted()` (if called) and `onPageFinished()`.
4999             if (!loadingNewIntent) {  // A new intent is not being loaded.
5000                 if ((url == null) || url.equals("about:blank")) {  // The WebView is blank.
5001                     // Display the hint in the URL edit text.
5002                     urlEditText.setText("");
5003
5004                     // Request focus for the URL text box.
5005                     urlEditText.requestFocus();
5006
5007                     // Display the keyboard.
5008                     inputMethodManager.showSoftInput(urlEditText, 0);
5009                 } else {  // The WebView has a loaded URL.
5010                     // Clear the focus from the URL text box.
5011                     urlEditText.clearFocus();
5012
5013                     // Hide the soft keyboard.
5014                     inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
5015
5016                     // Display the current URL in the URL text box.
5017                     urlEditText.setText(url);
5018
5019                     // Highlight the URL text.
5020                     highlightUrlText();
5021                 }
5022             } else {  // A new intent is being loaded.
5023                 // Reset the loading new intent tracker.
5024                 loadingNewIntent = false;
5025             }
5026
5027             // Set the background to indicate the domain settings status.
5028             if (currentWebView.getDomainSettingsApplied()) {
5029                 // Set a background on the URL relative layout to indicate that custom domain settings are being used.
5030                 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.domain_settings_url_background, null));
5031             } else {
5032                 // Remove any background on the URL relative layout.
5033                 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.color.transparent, null));
5034             }
5035         } else {  // The fragment has not been populated.  Try again in 100 milliseconds.
5036             // Create a handler to set the current WebView.
5037             Handler setCurrentWebViewHandler = new Handler();
5038
5039             // Create a runnable to set the current WebView.
5040             Runnable setCurrentWebWebRunnable = () -> {
5041                 // Set the current WebView.
5042                 setCurrentWebView(pageNumber);
5043             };
5044
5045             // Try setting the current WebView again after 100 milliseconds.
5046             setCurrentWebViewHandler.postDelayed(setCurrentWebWebRunnable, 100);
5047         }
5048     }
5049
5050     @SuppressLint("ClickableViewAccessibility")
5051     @Override
5052     public void initializeWebView(NestedScrollWebView nestedScrollWebView, int pageNumber, ProgressBar progressBar, String url, Boolean restoringState) {
5053         // Get a handle for the shared preferences.
5054         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
5055
5056         // Get the WebView theme.
5057         String webViewTheme = sharedPreferences.getString("webview_theme", getString(R.string.webview_theme_default_value));
5058
5059         // Get the WebView theme entry values string array.
5060         String[] webViewThemeEntryValuesStringArray = getResources().getStringArray(R.array.webview_theme_entry_values);
5061
5062         // Apply the WebView theme if supported by the installed WebView.
5063         if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
5064             // Set the WebView theme.  A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
5065             if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) {  // The light theme is selected.
5066                 // Turn off the WebView dark mode.
5067                 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
5068
5069                 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
5070                 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
5071                 nestedScrollWebView.setVisibility(View.VISIBLE);
5072             } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) {  // The dark theme is selected.
5073                 // Turn on the WebView dark mode.
5074                 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
5075             } else {  // The system default theme is selected.
5076                 // Get the current system theme status.
5077                 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
5078
5079                 // Set the WebView theme according to the current system theme status.
5080                 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {  // The system is in day mode.
5081                     // Turn off the WebView dark mode.
5082                     WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
5083
5084                     // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
5085                     // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
5086                     nestedScrollWebView.setVisibility(View.VISIBLE);
5087                 } else {  // The system is in night mode.
5088                     // Turn on the WebView dark mode.
5089                     WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
5090                 }
5091             }
5092         }
5093
5094         // Get a handle for the activity
5095         Activity activity = this;
5096
5097         // Get a handle for the input method manager.
5098         InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
5099
5100         // Instantiate the blocklist helper.
5101         BlocklistHelper blocklistHelper = new BlocklistHelper();
5102
5103         // Remove the lint warning below that the input method manager might be null.
5104         assert inputMethodManager != null;
5105
5106         // Set the app bar scrolling.
5107         nestedScrollWebView.setNestedScrollingEnabled(scrollAppBar);
5108
5109         // Allow pinch to zoom.
5110         nestedScrollWebView.getSettings().setBuiltInZoomControls(true);
5111
5112         // Hide zoom controls.
5113         nestedScrollWebView.getSettings().setDisplayZoomControls(false);
5114
5115         // Don't allow mixed content (HTTP and HTTPS) on the same website.
5116         nestedScrollWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);
5117
5118         // Set the WebView to load in overview mode (zoomed out to the maximum width).
5119         nestedScrollWebView.getSettings().setLoadWithOverviewMode(true);
5120
5121         // Explicitly disable geolocation.
5122         nestedScrollWebView.getSettings().setGeolocationEnabled(false);
5123
5124         // Allow loading of file:// URLs.  This is necessary for opening MHT web archives, which are copies into a temporary cache location.
5125         nestedScrollWebView.getSettings().setAllowFileAccess(true);
5126
5127         // Create a double-tap gesture detector to toggle full-screen mode.
5128         GestureDetector doubleTapGestureDetector = new GestureDetector(getApplicationContext(), new GestureDetector.SimpleOnGestureListener() {
5129             // Override `onDoubleTap()`.  All other events are handled using the default settings.
5130             @Override
5131             public boolean onDoubleTap(MotionEvent event) {
5132                 if (fullScreenBrowsingModeEnabled) {  // Only process the double-tap if full screen browsing mode is enabled.
5133                     // Toggle the full screen browsing mode tracker.
5134                     inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
5135
5136                     // Toggle the full screen browsing mode.
5137                     if (inFullScreenBrowsingMode) {  // Switch to full screen mode.
5138                         // Hide the app bar if specified.
5139                         if (hideAppBar) {  // The app bar is hidden.
5140                             // Close the find on page bar if it is visible.
5141                             closeFindOnPage(null);
5142
5143                             // Hide the tab linear layout.
5144                             tabsLinearLayout.setVisibility(View.GONE);
5145
5146                             // Hide the action bar.
5147                             actionBar.hide();
5148
5149                             // Set layout and scrolling parameters according to the position of the app bar.
5150                             if (bottomAppBar) {  // The app bar is at the bottom.
5151                                 // Reset the WebView padding to fill the available space.
5152                                 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5153                             } else {  // The app bar is at the top.
5154                                 // Check to see if the app bar is normally scrolled.
5155                                 if (scrollAppBar) {  // The app bar is scrolled when it is displayed.
5156                                     // Get the swipe refresh layout parameters.
5157                                     CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
5158
5159                                     // Remove the off-screen scrolling layout.
5160                                     swipeRefreshLayoutParams.setBehavior(null);
5161                                 } else {  // The app bar is not scrolled when it is displayed.
5162                                     // Remove the padding from the top of the swipe refresh layout.
5163                                     swipeRefreshLayout.setPadding(0, 0, 0, 0);
5164
5165                                     // The swipe refresh circle must be moved above the now removed status bar location.
5166                                     swipeRefreshLayout.setProgressViewOffset(false, -200, defaultProgressViewEndOffset);
5167                                 }
5168                             }
5169                         } else {  // The app bar is not hidden.
5170                             // Adjust the UI for the bottom app bar.
5171                             if (bottomAppBar) {
5172                                 // Adjust the UI according to the scrolling of the app bar.
5173                                 if (scrollAppBar) {
5174                                     // Reset the WebView padding to fill the available space.
5175                                     swipeRefreshLayout.setPadding(0, 0, 0, 0);
5176                                 } else {
5177                                     // Move the WebView above the app bar layout.
5178                                     swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight);
5179                                 }
5180                             }
5181                         }
5182
5183                         /* Hide the system bars.
5184                          * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5185                          * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5186                          * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5187                          * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5188                          */
5189                         rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5190                                 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5191                     } else {  // Switch to normal viewing mode.
5192                         // Show the app bar if it was hidden.
5193                         if (hideAppBar) {
5194                             // Show the tab linear layout.
5195                             tabsLinearLayout.setVisibility(View.VISIBLE);
5196
5197                             // Show the action bar.
5198                             actionBar.show();
5199                         }
5200
5201                         // Set layout and scrolling parameters according to the position of the app bar.
5202                         if (bottomAppBar) {  // The app bar is at the bottom.
5203                             // Adjust the UI.
5204                             if (scrollAppBar) {
5205                                 // Reset the WebView padding to fill the available space.
5206                                 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5207                             } else {
5208                                 // Move the WebView above the app bar layout.
5209                                 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight);
5210                             }
5211                         } else {  // The app bar is at the top.
5212                             // Check to see if the app bar is normally scrolled.
5213                             if (scrollAppBar) {  // The app bar is scrolled when it is displayed.
5214                                 // Get the swipe refresh layout parameters.
5215                                 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
5216
5217                                 // Add the off-screen scrolling layout.
5218                                 swipeRefreshLayoutParams.setBehavior(new AppBarLayout.ScrollingViewBehavior());
5219                             } else {  // The app bar is not scrolled when it is displayed.
5220                                 // The swipe refresh layout must be manually moved below the app bar layout.
5221                                 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0);
5222
5223                                 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5224                                 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight);
5225                             }
5226                         }
5227
5228                         // Remove the `SYSTEM_UI` flags from the root frame layout.
5229                         rootFrameLayout.setSystemUiVisibility(0);
5230                     }
5231
5232                     // Consume the double-tap.
5233                     return true;
5234                 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
5235                     return false;
5236                 }
5237             }
5238
5239             @Override
5240             public boolean onFling(MotionEvent motionEvent1, MotionEvent motionEvent2, float velocityX, float velocityY) {
5241                 // Scroll the bottom app bar if enabled.
5242                 if (bottomAppBar && scrollAppBar && !objectAnimator.isRunning()) {
5243                     // Calculate the Y change.
5244                     float motionY = motionEvent2.getY() - motionEvent1.getY();
5245
5246                     // Scroll the app bar if the change is greater than 100 pixels.
5247                     if (motionY > 50) {
5248                         // Animate the bottom app bar onto the screen.
5249                         objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0);
5250                     } else if (motionY < -50) {
5251                         // Animate the bottom app bar off the screen.
5252                         objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", appBarLayout.getHeight());
5253                     }
5254
5255                     // Make it so.
5256                     objectAnimator.start();
5257                 }
5258
5259                 // Do not consume the event.
5260                 return false;
5261             }
5262         });
5263
5264         // Pass all touch events on the WebView through the double-tap gesture detector.
5265         nestedScrollWebView.setOnTouchListener((View view, MotionEvent event) -> {
5266             // Call `performClick()` on the view, which is required for accessibility.
5267             view.performClick();
5268
5269             // Send the event to the gesture detector.
5270             return doubleTapGestureDetector.onTouchEvent(event);
5271         });
5272
5273         // Register the WebView for a context menu.  This is used to see link targets and download images.
5274         registerForContextMenu(nestedScrollWebView);
5275
5276         // Allow the downloading of files.
5277         nestedScrollWebView.setDownloadListener((String downloadUrl, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
5278             // Check the download preference.
5279             if (downloadWithExternalApp) {  // Download with an external app.
5280                 downloadUrlWithExternalApp(downloadUrl);
5281             } else {  // Handle the download inside of Privacy Browser.
5282                 // Define a formatted file size string.
5283                 String formattedFileSizeString;
5284
5285                 // Process the content length if it contains data.
5286                 if (contentLength > 0) {  // The content length is greater than 0.
5287                     // Format the content length as a string.
5288                     formattedFileSizeString = NumberFormat.getInstance().format(contentLength) + " " + getString(R.string.bytes);
5289                 } else {  // The content length is not greater than 0.
5290                     // Set the formatted file size string to be `unknown size`.
5291                     formattedFileSizeString = getString(R.string.unknown_size);
5292                 }
5293
5294                 // Get the file name from the content disposition.
5295                 String fileNameString = PrepareSaveDialog.getFileNameFromHeaders(this, contentDisposition, mimetype, downloadUrl);
5296
5297                 // Instantiate the save dialog.
5298                 DialogFragment saveDialogFragment = SaveDialog.saveUrl(downloadUrl, formattedFileSizeString, fileNameString, userAgent,
5299                         nestedScrollWebView.getAcceptCookies());
5300
5301                 // 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.
5302                 try {
5303                     // Show the save dialog.  It must be named `save_dialog` so that the file picker can update the file name.
5304                     saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
5305                 } catch (Exception exception) {  // The dialog could not be shown.
5306                     // Add the dialog to the pending dialog array list.  It will be displayed in `onStart()`.
5307                     pendingDialogsArrayList.add(new PendingDialog(saveDialogFragment, getString(R.string.save_dialog)));
5308                 }
5309             }
5310         });
5311
5312         // Update the find on page count.
5313         nestedScrollWebView.setFindListener(new WebView.FindListener() {
5314             // Get a handle for `findOnPageCountTextView`.
5315             final TextView findOnPageCountTextView = findViewById(R.id.find_on_page_count_textview);
5316
5317             @Override
5318             public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
5319                 if ((isDoneCounting) && (numberOfMatches == 0)) {  // There are no matches.
5320                     // Set `findOnPageCountTextView` to `0/0`.
5321                     findOnPageCountTextView.setText(R.string.zero_of_zero);
5322                 } else if (isDoneCounting) {  // There are matches.
5323                     // `activeMatchOrdinal` is zero-based.
5324                     int activeMatch = activeMatchOrdinal + 1;
5325
5326                     // Build the match string.
5327                     String matchString = activeMatch + "/" + numberOfMatches;
5328
5329                     // Set `findOnPageCountTextView`.
5330                     findOnPageCountTextView.setText(matchString);
5331                 }
5332             }
5333         });
5334
5335         // Process scroll changes.
5336         nestedScrollWebView.setOnScrollChangeListener((view, scrollX, scrollY, oldScrollX, oldScrollY) -> {
5337             // Set the swipe to refresh status.
5338             if (nestedScrollWebView.getSwipeToRefresh()) {
5339                 // Only enable swipe to refresh if the WebView is scrolled to the top.
5340                 swipeRefreshLayout.setEnabled(nestedScrollWebView.getScrollY() == 0);
5341             } else {
5342                 // Disable swipe to refresh.
5343                 swipeRefreshLayout.setEnabled(false);
5344             }
5345
5346             // Reinforce the system UI visibility flags if in full screen browsing mode.
5347             // This hides the status and navigation bars, which are displayed if other elements are shown, like dialog boxes, the options menu, or the keyboard.
5348             if (inFullScreenBrowsingMode) {
5349                 /* Hide the system bars.
5350                  * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5351                  * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5352                  * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5353                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5354                  */
5355                 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5356                         View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5357             }
5358         });
5359
5360         // Set the web chrome client.
5361         nestedScrollWebView.setWebChromeClient(new WebChromeClient() {
5362             // Update the progress bar when a page is loading.
5363             @Override
5364             public void onProgressChanged(WebView view, int progress) {
5365                 // Update the progress bar.
5366                 progressBar.setProgress(progress);
5367
5368                 // Set the visibility of the progress bar.
5369                 if (progress < 100) {
5370                     // Show the progress bar.
5371                     progressBar.setVisibility(View.VISIBLE);
5372                 } else {
5373                     // Hide the progress bar.
5374                     progressBar.setVisibility(View.GONE);
5375
5376                     //Stop the swipe to refresh indicator if it is running
5377                     swipeRefreshLayout.setRefreshing(false);
5378
5379                     // 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.
5380                     nestedScrollWebView.setVisibility(View.VISIBLE);
5381                 }
5382             }
5383
5384             // Set the favorite icon when it changes.
5385             @Override
5386             public void onReceivedIcon(WebView view, Bitmap icon) {
5387                 // Only update the favorite icon if the website has finished loading.
5388                 if (progressBar.getVisibility() == View.GONE) {
5389                     // Store the new favorite icon.
5390                     nestedScrollWebView.setFavoriteOrDefaultIcon(icon);
5391
5392                     // Get the current page position.
5393                     int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5394
5395                     // Get the current tab.
5396                     TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
5397
5398                     // Check to see if the tab has been populated.
5399                     if (tab != null) {
5400                         // Get the custom view from the tab.
5401                         View tabView = tab.getCustomView();
5402
5403                         // Check to see if the custom tab view has been populated.
5404                         if (tabView != null) {
5405                             // Get the favorite icon image view from the tab.
5406                             ImageView tabFavoriteIconImageView = tabView.findViewById(R.id.favorite_icon_imageview);
5407
5408                             // Display the favorite icon in the tab.
5409                             tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
5410                         }
5411                     }
5412                 }
5413             }
5414
5415             // Save a copy of the title when it changes.
5416             @Override
5417             public void onReceivedTitle(WebView view, String title) {
5418                 // Get the current page position.
5419                 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5420
5421                 // Get the current tab.
5422                 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
5423
5424                 // Only populate the title text view if the tab has been fully created.
5425                 if (tab != null) {
5426                     // Get the custom view from the tab.
5427                     View tabView = tab.getCustomView();
5428
5429                     // Only populate the title text view if the tab view has been fully populated.
5430                     if (tabView != null) {
5431                         // Get the title text view from the tab.
5432                         TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
5433
5434                         // Set the title according to the URL.
5435                         if (title.equals("about:blank")) {
5436                             // Set the title to indicate a new tab.
5437                             tabTitleTextView.setText(R.string.new_tab);
5438                         } else {
5439                             // Set the title as the tab text.
5440                             tabTitleTextView.setText(title);
5441                         }
5442                     }
5443                 }
5444             }
5445
5446             // Enter full screen video.
5447             @Override
5448             public void onShowCustomView(View video, CustomViewCallback callback) {
5449                 // Set the full screen video flag.
5450                 displayingFullScreenVideo = true;
5451
5452                 // Hide the keyboard.
5453                 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
5454
5455                 // Hide the coordinator layout.
5456                 coordinatorLayout.setVisibility(View.GONE);
5457
5458                 /* Hide the system bars.
5459                  * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5460                  * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5461                  * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5462                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5463                  */
5464                 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5465                         View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5466
5467                 // Disable the sliding drawers.
5468                 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
5469
5470                 // Add the video view to the full screen video frame layout.
5471                 fullScreenVideoFrameLayout.addView(video);
5472
5473                 // Show the full screen video frame layout.
5474                 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
5475
5476                 // Disable the screen timeout while the video is playing.  YouTube does this automatically, but not all other videos do.
5477                 fullScreenVideoFrameLayout.setKeepScreenOn(true);
5478             }
5479
5480             // Exit full screen video.
5481             @Override
5482             public void onHideCustomView() {
5483                 // Exit the full screen video.
5484                 exitFullScreenVideo();
5485             }
5486
5487             // Upload files.
5488             @Override
5489             public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
5490                 // Store the file path callback.
5491                 fileChooserCallback = filePathCallback;
5492
5493                 // Create an intent to open a chooser based on the file chooser parameters.
5494                 Intent fileChooserIntent = fileChooserParams.createIntent();
5495
5496                 // Get a handle for the package manager.
5497                 PackageManager packageManager = getPackageManager();
5498
5499                 // Check to see if the file chooser intent resolves to an installed package.
5500                 if (fileChooserIntent.resolveActivity(packageManager) != null) {  // The file chooser intent is fine.
5501                     // Start the file chooser intent.
5502                     startActivityForResult(fileChooserIntent, BROWSE_FILE_UPLOAD_REQUEST_CODE);
5503                 } else {  // The file chooser intent will cause a crash.
5504                     // Create a generic intent to open a chooser.
5505                     Intent genericFileChooserIntent = new Intent(Intent.ACTION_GET_CONTENT);
5506
5507                     // Request an openable file.
5508                     genericFileChooserIntent.addCategory(Intent.CATEGORY_OPENABLE);
5509
5510                     // Set the file type to everything.
5511                     genericFileChooserIntent.setType("*/*");
5512
5513                     // Start the generic file chooser intent.
5514                     startActivityForResult(genericFileChooserIntent, BROWSE_FILE_UPLOAD_REQUEST_CODE);
5515                 }
5516                 return true;
5517             }
5518         });
5519
5520         nestedScrollWebView.setWebViewClient(new WebViewClient() {
5521             // `shouldOverrideUrlLoading` makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
5522             // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
5523             @Override
5524             public boolean shouldOverrideUrlLoading(WebView view, String url) {
5525                 // Sanitize the url.
5526                 url = sanitizeUrl(url);
5527
5528                 // Handle the URL according to the type.
5529                 if (url.startsWith("http")) {  // Load the URL in Privacy Browser.
5530                     // Load the URL.  By using `loadUrl()`, instead of `loadUrlFromBase()`, the Referer header will never be sent.
5531                     loadUrl(nestedScrollWebView, url);
5532
5533                     // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
5534                     // Custom headers cannot be added if false is returned and the WebView handles the loading of the URL.
5535                     return true;
5536                 } else if (url.startsWith("mailto:")) {  // Load the email address in an external email program.
5537                     // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
5538                     Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
5539
5540                     // Parse the url and set it as the data for the intent.
5541                     emailIntent.setData(Uri.parse(url));
5542
5543                     // Open the email program in a new task instead of as part of Privacy Browser.
5544                     emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5545
5546                     try {
5547                         // Make it so.
5548                         startActivity(emailIntent);
5549                     } catch (ActivityNotFoundException exception) {
5550                         // Display a snackbar.
5551                         Snackbar.make(currentWebView, getString(R.string.error) + "  " + exception, Snackbar.LENGTH_INDEFINITE).show();
5552                     }
5553
5554
5555                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5556                     return true;
5557                 } else if (url.startsWith("tel:")) {  // Load the phone number in the dialer.
5558                     // Open the dialer and load the phone number, but wait for the user to place the call.
5559                     Intent dialIntent = new Intent(Intent.ACTION_DIAL);
5560
5561                     // Add the phone number to the intent.
5562                     dialIntent.setData(Uri.parse(url));
5563
5564                     // Open the dialer in a new task instead of as part of Privacy Browser.
5565                     dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5566
5567                     try {
5568                         // Make it so.
5569                         startActivity(dialIntent);
5570                     } catch (ActivityNotFoundException exception) {
5571                         // Display a snackbar.
5572                         Snackbar.make(currentWebView, getString(R.string.error) + "  " + exception, Snackbar.LENGTH_INDEFINITE).show();
5573                     }
5574
5575                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5576                     return true;
5577                 } else {  // Load a system chooser to select an app that can handle the URL.
5578                     // Open an app that can handle the URL.
5579                     Intent genericIntent = new Intent(Intent.ACTION_VIEW);
5580
5581                     // Add the URL to the intent.
5582                     genericIntent.setData(Uri.parse(url));
5583
5584                     // List all apps that can handle the URL instead of just opening the first one.
5585                     genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
5586
5587                     // Open the app in a new task instead of as part of Privacy Browser.
5588                     genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5589
5590                     // Start the app or display a snackbar if no app is available to handle the URL.
5591                     try {
5592                         startActivity(genericIntent);
5593                     } catch (ActivityNotFoundException exception) {
5594                         Snackbar.make(nestedScrollWebView, getString(R.string.unrecognized_url) + "  " + url, Snackbar.LENGTH_SHORT).show();
5595                     }
5596
5597                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5598                     return true;
5599                 }
5600             }
5601
5602             // Check requests against the block lists.  The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
5603             @Override
5604             public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest webResourceRequest) {
5605                 // Get the URL.
5606                 String url = webResourceRequest.getUrl().toString();
5607
5608                 // Check to see if the resource request is for the main URL.
5609                 if (url.equals(nestedScrollWebView.getCurrentUrl())) {
5610                     // `return null` loads the resource request, which should never be blocked if it is the main URL.
5611                     return null;
5612                 }
5613
5614                 // 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.
5615                 while (ultraPrivacy == null) {
5616                     // The wait must be synchronized, which only lets one thread run on it at a time, or `java.lang.IllegalMonitorStateException` is thrown.
5617                     synchronized (this) {
5618                         try {
5619                             // Check to see if the blocklists have been populated after 100 ms.
5620                             wait(100);
5621                         } catch (InterruptedException exception) {
5622                             // Do nothing.
5623                         }
5624                     }
5625                 }
5626
5627                 // Create an empty web resource response to be used if the resource request is blocked.
5628                 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
5629
5630                 // Reset the whitelist results tracker.
5631                 String[] whitelistResultStringArray = null;
5632
5633                 // Initialize the third party request tracker.
5634                 boolean isThirdPartyRequest = false;
5635
5636                 // Get the current URL.  `.getUrl()` throws an error because operations on the WebView cannot be made from this thread.
5637                 String currentBaseDomain = nestedScrollWebView.getCurrentDomainName();
5638
5639                 // Store a copy of the current domain for use in later requests.
5640                 String currentDomain = currentBaseDomain;
5641
5642                 // Get the request host name.
5643                 String requestBaseDomain = webResourceRequest.getUrl().getHost();
5644
5645                 // Only check for third-party requests if the current base domain is not empty and the request domain is not null.
5646                 if (!currentBaseDomain.isEmpty() && (requestBaseDomain != null)) {
5647                     // Determine the current base domain.
5648                     while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) {  // There is at least one subdomain.
5649                         // Remove the first subdomain.
5650                         currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
5651                     }
5652
5653                     // Determine the request base domain.
5654                     while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) {  // There is at least one subdomain.
5655                         // Remove the first subdomain.
5656                         requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
5657                     }
5658
5659                     // Update the third party request tracker.
5660                     isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
5661                 }
5662
5663                 // Get the current WebView page position.
5664                 int webViewPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5665
5666                 // Determine if the WebView is currently displayed.
5667                 boolean webViewDisplayed = (webViewPagePosition == tabLayout.getSelectedTabPosition());
5668
5669                 // Block third-party requests if enabled.
5670                 if (isThirdPartyRequest && nestedScrollWebView.getBlockAllThirdPartyRequests()) {
5671                     // Add the result to the resource requests.
5672                     nestedScrollWebView.addResourceRequest(new String[]{BlocklistHelper.REQUEST_THIRD_PARTY, url});
5673
5674                     // Increment the blocked requests counters.
5675                     nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5676                     nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS);
5677
5678                     // Update the titles of the blocklist menu items if the WebView is currently displayed.
5679                     if (webViewDisplayed) {
5680                         // Updating the UI must be run from the UI thread.
5681                         activity.runOnUiThread(() -> {
5682                             // Update the menu item titles.
5683                             navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5684
5685                             // Update the options menu if it has been populated.
5686                             if (optionsMenu != null) {
5687                                 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5688                                 optionsBlockAllThirdPartyRequestsMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " +
5689                                         getString(R.string.block_all_third_party_requests));
5690                             }
5691                         });
5692                     }
5693
5694                     // Return an empty web resource response.
5695                     return emptyWebResourceResponse;
5696                 }
5697
5698                 // Check UltraList if it is enabled.
5699                 if (nestedScrollWebView.getUltraListEnabled()) {
5700                     // Check the URL against UltraList.
5701                     String[] ultraListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraList);
5702
5703                     // Process the UltraList results.
5704                     if (ultraListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) {  // The resource request matched UltraList's blacklist.
5705                         // Add the result to the resource requests.
5706                         nestedScrollWebView.addResourceRequest(new String[] {ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]});
5707
5708                         // Increment the blocked requests counters.
5709                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5710                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRALIST);
5711
5712                         // Update the titles of the blocklist menu items if the WebView is currently displayed.
5713                         if (webViewDisplayed) {
5714                             // Updating the UI must be run from the UI thread.
5715                             activity.runOnUiThread(() -> {
5716                                 // Update the menu item titles.
5717                                 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5718
5719                                 // Update the options menu if it has been populated.
5720                                 if (optionsMenu != null) {
5721                                     optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5722                                     optionsUltraListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRALIST) + " - " + getString(R.string.ultralist));
5723                                 }
5724                             });
5725                         }
5726
5727                         // The resource request was blocked.  Return an empty web resource response.
5728                         return emptyWebResourceResponse;
5729                     } else if (ultraListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) {  // The resource request matched UltraList's whitelist.
5730                         // Add a whitelist entry to the resource requests array.
5731                         nestedScrollWebView.addResourceRequest(new String[] {ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]});
5732
5733                         // The resource request has been allowed by UltraPrivacy.  `return null` loads the requested resource.
5734                         return null;
5735                     }
5736                 }
5737
5738                 // Check UltraPrivacy if it is enabled.
5739                 if (nestedScrollWebView.getUltraPrivacyEnabled()) {
5740                     // Check the URL against UltraPrivacy.
5741                     String[] ultraPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraPrivacy);
5742
5743                     // Process the UltraPrivacy results.
5744                     if (ultraPrivacyResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) {  // The resource request matched UltraPrivacy's blacklist.
5745                         // Add the result to the resource requests.
5746                         nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5747                                 ultraPrivacyResults[5]});
5748
5749                         // Increment the blocked requests counters.
5750                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5751                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRAPRIVACY);
5752
5753                         // Update the titles of the blocklist menu items if the WebView is currently displayed.
5754                         if (webViewDisplayed) {
5755                             // Updating the UI must be run from the UI thread.
5756                             activity.runOnUiThread(() -> {
5757                                 // Update the menu item titles.
5758                                 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5759
5760                                 // Update the options menu if it has been populated.
5761                                 if (optionsMenu != null) {
5762                                     optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5763                                     optionsUltraPrivacyMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRAPRIVACY) + " - " + getString(R.string.ultraprivacy));
5764                                 }
5765                             });
5766                         }
5767
5768                         // The resource request was blocked.  Return an empty web resource response.
5769                         return emptyWebResourceResponse;
5770                     } else if (ultraPrivacyResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) {  // The resource request matched UltraPrivacy's whitelist.
5771                         // Add a whitelist entry to the resource requests array.
5772                         nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5773                                 ultraPrivacyResults[5]});
5774
5775                         // The resource request has been allowed by UltraPrivacy.  `return null` loads the requested resource.
5776                         return null;
5777                     }
5778                 }
5779
5780                 // Check EasyList if it is enabled.
5781                 if (nestedScrollWebView.getEasyListEnabled()) {
5782                     // Check the URL against EasyList.
5783                     String[] easyListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyList);
5784
5785                     // Process the EasyList results.
5786                     if (easyListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) {  // The resource request matched EasyList's blacklist.
5787                         // Add the result to the resource requests.
5788                         nestedScrollWebView.addResourceRequest(new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]});
5789
5790                         // Increment the blocked requests counters.
5791                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5792                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASYLIST);
5793
5794                         // Update the titles of the blocklist menu items if the WebView is currently displayed.
5795                         if (webViewDisplayed) {
5796                             // Updating the UI must be run from the UI thread.
5797                             activity.runOnUiThread(() -> {
5798                                 // Update the menu item titles.
5799                                 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5800
5801                                 // Update the options menu if it has been populated.
5802                                 if (optionsMenu != null) {
5803                                     optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5804                                     optionsEasyListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASYLIST) + " - " + getString(R.string.easylist));
5805                                 }
5806                             });
5807                         }
5808
5809                         // The resource request was blocked.  Return an empty web resource response.
5810                         return emptyWebResourceResponse;
5811                     } else if (easyListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) {  // The resource request matched EasyList's whitelist.
5812                         // Update the whitelist result string array tracker.
5813                         whitelistResultStringArray = new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]};
5814                     }
5815                 }
5816
5817                 // Check EasyPrivacy if it is enabled.
5818                 if (nestedScrollWebView.getEasyPrivacyEnabled()) {
5819                     // Check the URL against EasyPrivacy.
5820                     String[] easyPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyPrivacy);
5821
5822                     // Process the EasyPrivacy results.
5823                     if (easyPrivacyResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) {  // The resource request matched EasyPrivacy's blacklist.
5824                         // Add the result to the resource requests.
5825                         nestedScrollWebView.addResourceRequest(new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4],
5826                                 easyPrivacyResults[5]});
5827
5828                         // Increment the blocked requests counters.
5829                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5830                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASYPRIVACY);
5831
5832                         // Update the titles of the blocklist menu items if the WebView is currently displayed.
5833                         if (webViewDisplayed) {
5834                             // Updating the UI must be run from the UI thread.
5835                             activity.runOnUiThread(() -> {
5836                                 // Update the menu item titles.
5837                                 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5838
5839                                 // Update the options menu if it has been populated.
5840                                 if (optionsMenu != null) {
5841                                     optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5842                                     optionsEasyPrivacyMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASYPRIVACY) + " - " + getString(R.string.easyprivacy));
5843                                 }
5844                             });
5845                         }
5846
5847                         // The resource request was blocked.  Return an empty web resource response.
5848                         return emptyWebResourceResponse;
5849                     } else if (easyPrivacyResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) {  // The resource request matched EasyPrivacy's whitelist.
5850                         // Update the whitelist result string array tracker.
5851                         whitelistResultStringArray = new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5]};
5852                     }
5853                 }
5854
5855                 // Check Fanboy’s Annoyance List if it is enabled.
5856                 if (nestedScrollWebView.getFanboysAnnoyanceListEnabled()) {
5857                     // Check the URL against Fanboy's Annoyance List.
5858                     String[] fanboysAnnoyanceListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList);
5859
5860                     // Process the Fanboy's Annoyance List results.
5861                     if (fanboysAnnoyanceListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) {  // The resource request matched Fanboy's Annoyance List's blacklist.
5862                         // Add the result to the resource requests.
5863                         nestedScrollWebView.addResourceRequest(new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5864                                 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]});
5865
5866                         // Increment the blocked requests counters.
5867                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5868                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST);
5869
5870                         // Update the titles of the blocklist menu items if the WebView is currently displayed.
5871                         if (webViewDisplayed) {
5872                             // Updating the UI must be run from the UI thread.
5873                             activity.runOnUiThread(() -> {
5874                                 // Update the menu item titles.
5875                                 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5876
5877                                 // Update the options menu if it has been populated.
5878                                 if (optionsMenu != null) {
5879                                     optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5880                                     optionsFanboysAnnoyanceListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " +
5881                                             getString(R.string.fanboys_annoyance_list));
5882                                 }
5883                             });
5884                         }
5885
5886                         // The resource request was blocked.  Return an empty web resource response.
5887                         return emptyWebResourceResponse;
5888                     } else if (fanboysAnnoyanceListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)){  // The resource request matched Fanboy's Annoyance List's whitelist.
5889                         // Update the whitelist result string array tracker.
5890                         whitelistResultStringArray = new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5891                                 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]};
5892                     }
5893                 } else if (nestedScrollWebView.getFanboysSocialBlockingListEnabled()) {  // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
5894                     // Check the URL against Fanboy's Annoyance List.
5895                     String[] fanboysSocialListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysSocialList);
5896
5897                     // Process the Fanboy's Social Blocking List results.
5898                     if (fanboysSocialListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) {  // The resource request matched Fanboy's Social Blocking List's blacklist.
5899                         // Add the result to the resource requests.
5900                         nestedScrollWebView.addResourceRequest(new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5901                                 fanboysSocialListResults[4], fanboysSocialListResults[5]});
5902
5903                         // Increment the blocked requests counters.
5904                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5905                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST);
5906
5907                         // Update the titles of the blocklist menu items if the WebView is currently displayed.
5908                         if (webViewDisplayed) {
5909                             // Updating the UI must be run from the UI thread.
5910                             activity.runOnUiThread(() -> {
5911                                 // Update the menu item titles.
5912                                 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5913
5914                                 // Update the options menu if it has been populated.
5915                                 if (optionsMenu != null) {
5916                                     optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5917                                     optionsFanboysSocialBlockingListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " +
5918                                             getString(R.string.fanboys_social_blocking_list));
5919                                 }
5920                             });
5921                         }
5922
5923                         // The resource request was blocked.  Return an empty web resource response.
5924                         return emptyWebResourceResponse;
5925                     } else if (fanboysSocialListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) {  // The resource request matched Fanboy's Social Blocking List's whitelist.
5926                         // Update the whitelist result string array tracker.
5927                         whitelistResultStringArray = new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5928                                 fanboysSocialListResults[4], fanboysSocialListResults[5]};
5929                     }
5930                 }
5931
5932                 // Add the request to the log because it hasn't been processed by any of the previous checks.
5933                 if (whitelistResultStringArray != null) {  // The request was processed by a whitelist.
5934                     nestedScrollWebView.addResourceRequest(whitelistResultStringArray);
5935                 } else {  // The request didn't match any blocklist entry.  Log it as a default request.
5936                     nestedScrollWebView.addResourceRequest(new String[]{BlocklistHelper.REQUEST_DEFAULT, url});
5937                 }
5938
5939                 // The resource request has not been blocked.  `return null` loads the requested resource.
5940                 return null;
5941             }
5942
5943             // Handle HTTP authentication requests.
5944             @Override
5945             public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
5946                 // Store the handler.
5947                 nestedScrollWebView.setHttpAuthHandler(handler);
5948
5949                 // Instantiate an HTTP authentication dialog.
5950                 DialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm, nestedScrollWebView.getWebViewFragmentId());
5951
5952                 // Show the HTTP authentication dialog.
5953                 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
5954             }
5955
5956             @Override
5957             public void onPageStarted(WebView view, String url, Bitmap favicon) {
5958                 // Get the app bar layout height.  This can't be done in `applyAppSettings()` because the app bar is not yet populated there.
5959                 // 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.
5960                 if (appBarLayout.getHeight() > 0) appBarHeight = appBarLayout.getHeight();
5961
5962                 // Set the padding and layout settings according to the position of the app bar.
5963                 if (bottomAppBar) {  // The app bar is on the bottom.
5964                     // Adjust the UI.
5965                     if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) {  // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
5966                         // Reset the WebView padding to fill the available space.
5967                         swipeRefreshLayout.setPadding(0, 0, 0, 0);
5968                     } else {  // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
5969                         // Move the WebView above the app bar layout.
5970                         swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight);
5971                     }
5972                 } else {  // The app bar is on the top.
5973                     // 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.
5974                     if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) {
5975                         // No padding is needed because it will automatically be placed below the app bar layout due to the scrolling layout behavior.
5976                         swipeRefreshLayout.setPadding(0, 0, 0, 0);
5977
5978                         // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5979                         swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10, defaultProgressViewEndOffset);
5980                     } else {
5981                         // The swipe refresh layout must be manually moved below the app bar layout.
5982                         swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0);
5983
5984                         // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5985                         swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight);
5986                     }
5987                 }
5988
5989                 // Reset the list of resource requests.
5990                 nestedScrollWebView.clearResourceRequests();
5991
5992                 // Reset the requests counters.
5993                 nestedScrollWebView.resetRequestsCounters();
5994
5995                 // Get the current page position.
5996                 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5997
5998                 // Update the URL text bar if the page is currently selected and the URL edit text is not currently being edited.
5999                 if ((tabLayout.getSelectedTabPosition() == currentPagePosition) && !urlEditText.hasFocus()) {
6000                     // Display the formatted URL text.
6001                     urlEditText.setText(url);
6002
6003                     // Apply text highlighting to the URL text box.
6004                     highlightUrlText();
6005
6006                     // Hide the keyboard.
6007                     inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
6008                 }
6009
6010                 // Reset the list of host IP addresses.
6011                 nestedScrollWebView.setCurrentIpAddresses("");
6012
6013                 // Get a URI for the current URL.
6014                 Uri currentUri = Uri.parse(url);
6015
6016                 // Get the IP addresses for the host.
6017                 new GetHostIpAddresses(activity, getSupportFragmentManager(), nestedScrollWebView).execute(currentUri.getHost());
6018
6019                 // Replace Refresh with Stop if the options menu has been created.  (The first WebView typically begins loading before the menu items are instantiated.)
6020                 if (optionsMenu != null) {
6021                     // Set the title.
6022                     optionsRefreshMenuItem.setTitle(R.string.stop);
6023
6024                     // Get the app bar and theme preferences.
6025                     boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false);
6026
6027                     // 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.
6028                     if (displayAdditionalAppBarIcons) {
6029                         optionsRefreshMenuItem.setIcon(R.drawable.close_blue);
6030                     }
6031                 }
6032             }
6033
6034             @Override
6035             public void onPageFinished(WebView view, String url) {
6036                 // Flush any cookies to persistent storage.  The cookie manager has become very lazy about flushing cookies in recent versions.
6037                 if (nestedScrollWebView.getAcceptCookies()) {
6038                     CookieManager.getInstance().flush();
6039                 }
6040
6041                 // Update the Refresh menu item if the options menu has been created.
6042                 if (optionsMenu != null) {
6043                     // Reset the Refresh title.
6044                     optionsRefreshMenuItem.setTitle(R.string.refresh);
6045
6046                     // Get the app bar and theme preferences.
6047                     boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false);
6048
6049                     // If the icon is displayed in the app bar, reset it according to the theme.
6050                     if (displayAdditionalAppBarIcons) {
6051                         // Set the icon.
6052                         optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled);
6053                     }
6054                 }
6055
6056                 // Clear the cache, history, and logcat if Incognito Mode is enabled.
6057                 if (incognitoModeEnabled) {
6058                     // Clear the cache.  `true` includes disk files.
6059                     nestedScrollWebView.clearCache(true);
6060
6061                     // Clear the back/forward history.
6062                     nestedScrollWebView.clearHistory();
6063
6064                     // Manually delete cache folders.
6065                     try {
6066                         // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
6067                         // which links to `/data/data/com.stoutner.privacybrowser.standard`.
6068                         String privateDataDirectoryString = getApplicationInfo().dataDir;
6069
6070                         // Delete the main cache directory.
6071                         Runtime.getRuntime().exec("rm -rf " + privateDataDirectoryString + "/cache");
6072
6073                         // Delete the secondary `Service Worker` cache directory.
6074                         // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
6075                         Runtime.getRuntime().exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
6076                     } catch (IOException exception) {
6077                         // Do nothing if an error is thrown.
6078                     }
6079
6080                     // Clear the logcat.
6081                     try {
6082                         // Clear the logcat.  `-c` clears the logcat.  `-b all` clears all the buffers (instead of just crash, main, and system).
6083                         Runtime.getRuntime().exec("logcat -b all -c");
6084                     } catch (IOException exception) {
6085                         // Do nothing.
6086                     }
6087                 }
6088
6089                 // Get the current page position.
6090                 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
6091
6092                 // 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.
6093                 String currentUrl = nestedScrollWebView.getUrl();
6094
6095                 // Get the current tab.
6096                 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
6097
6098                 // Update the URL text bar if the page is currently selected and the user is not currently typing in the URL edit text.
6099                 // Crash records show that, in some crazy way, it is possible for the current URL to be blank at this point.
6100                 // Probably some sort of race condition when Privacy Browser is being resumed.
6101                 if ((tabLayout.getSelectedTabPosition() == currentPagePosition) && !urlEditText.hasFocus() && (currentUrl != null)) {
6102                     // Check to see if the URL is `about:blank`.
6103                     if (currentUrl.equals("about:blank")) {  // The WebView is blank.
6104                         // Display the hint in the URL edit text.
6105                         urlEditText.setText("");
6106
6107                         // Request focus for the URL text box.
6108                         urlEditText.requestFocus();
6109
6110                         // Display the keyboard.
6111                         inputMethodManager.showSoftInput(urlEditText, 0);
6112
6113                         // Apply the domain settings.  This clears any settings from the previous domain.
6114                         applyDomainSettings(nestedScrollWebView, "", true, false, false);
6115
6116                         // Only populate the title text view if the tab has been fully created.
6117                         if (tab != null) {
6118                             // Get the custom view from the tab.
6119                             View tabView = tab.getCustomView();
6120
6121                             // Remove the incorrect warning below that the current tab view might be null.
6122                             assert tabView != null;
6123
6124                             // Get the title text view from the tab.
6125                             TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
6126
6127                             // Set the title as the tab text.
6128                             tabTitleTextView.setText(R.string.new_tab);
6129                         }
6130                     } else {  // The WebView has loaded a webpage.
6131                         // Update the URL edit text if it is not currently being edited.
6132                         if (!urlEditText.hasFocus()) {
6133                             // 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.
6134                             String sanitizedUrl = sanitizeUrl(currentUrl);
6135
6136                             // Display the final URL.  Getting the URL from the WebView instead of using the one provided by `onPageFinished()` makes websites like YouTube function correctly.
6137                             urlEditText.setText(sanitizedUrl);
6138
6139                             // Apply text highlighting to the URL.
6140                             highlightUrlText();
6141                         }
6142
6143                         // Only populate the title text view if the tab has been fully created.
6144                         if (tab != null) {
6145                             // Get the custom view from the tab.
6146                             View tabView = tab.getCustomView();
6147
6148                             // Remove the incorrect warning below that the current tab view might be null.
6149                             assert tabView != null;
6150
6151                             // Get the title text view from the tab.
6152                             TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
6153
6154                             // Set the title as the tab text.  Sometimes `onReceivedTitle()` is not called, especially when navigating history.
6155                             tabTitleTextView.setText(nestedScrollWebView.getTitle());
6156                         }
6157                     }
6158                 }
6159             }
6160
6161             // Handle SSL Certificate errors.  Suppress the lint warning that ignoring the error might be dangerous.
6162             @SuppressLint("WebViewClientOnReceivedSslError")
6163             @Override
6164             public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
6165                 // Get the current website SSL certificate.
6166                 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
6167
6168                 // Extract the individual pieces of information from the current website SSL certificate.
6169                 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
6170                 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
6171                 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
6172                 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
6173                 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
6174                 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
6175                 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
6176                 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
6177
6178                 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
6179                 if (nestedScrollWebView.hasPinnedSslCertificate()) {
6180                     // Get the pinned SSL certificate.
6181                     Pair<String[], Date[]> pinnedSslCertificatePair = nestedScrollWebView.getPinnedSslCertificate();
6182
6183                     // Extract the arrays from the array list.
6184                     String[] pinnedSslCertificateStringArray = pinnedSslCertificatePair.getFirst();
6185                     Date[] pinnedSslCertificateDateArray = pinnedSslCertificatePair.getSecond();
6186
6187                     // Check if the current SSL certificate matches the pinned certificate.
6188                     if (currentWebsiteIssuedToCName.equals(pinnedSslCertificateStringArray[0]) && currentWebsiteIssuedToOName.equals(pinnedSslCertificateStringArray[1]) &&
6189                         currentWebsiteIssuedToUName.equals(pinnedSslCertificateStringArray[2]) && currentWebsiteIssuedByCName.equals(pinnedSslCertificateStringArray[3]) &&
6190                         currentWebsiteIssuedByOName.equals(pinnedSslCertificateStringArray[4]) && currentWebsiteIssuedByUName.equals(pinnedSslCertificateStringArray[5]) &&
6191                         currentWebsiteSslStartDate.equals(pinnedSslCertificateDateArray[0]) && currentWebsiteSslEndDate.equals(pinnedSslCertificateDateArray[1])) {
6192
6193                         // An SSL certificate is pinned and matches the current domain certificate.  Proceed to the website without displaying an error.
6194                         handler.proceed();
6195                     }
6196                 } else {  // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
6197                     // Store the SSL error handler.
6198                     nestedScrollWebView.setSslErrorHandler(handler);
6199
6200                     // Instantiate an SSL certificate error alert dialog.
6201                     DialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error, nestedScrollWebView.getWebViewFragmentId());
6202
6203                     // 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.
6204                     try {
6205                         // Show the SSL certificate error dialog.
6206                         sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
6207                     } catch (Exception exception) {
6208                         // Add the dialog to the pending dialog array list.  It will be displayed in `onStart()`.
6209                         pendingDialogsArrayList.add(new PendingDialog(sslCertificateErrorDialogFragment, getString(R.string.ssl_certificate_error)));
6210                     }
6211                 }
6212             }
6213         });
6214
6215         // Check to see if the state is being restored.
6216         if (restoringState) {  // The state is being restored.
6217             // Resume the nested scroll WebView JavaScript timers.
6218             nestedScrollWebView.resumeTimers();
6219         } else if (pageNumber == 0) {  // The first page is being loaded.
6220             // Set this nested scroll WebView as the current WebView.
6221             currentWebView = nestedScrollWebView;
6222
6223             // Initialize the URL to load string.
6224             String urlToLoadString;
6225
6226             // Get the intent that started the app.
6227             Intent launchingIntent = getIntent();
6228
6229             // Reset the intent.  This prevents a duplicate tab from being created on restart.
6230             setIntent(new Intent());
6231
6232             // Get the information from the intent.
6233             String launchingIntentAction = launchingIntent.getAction();
6234             Uri launchingIntentUriData = launchingIntent.getData();
6235             String launchingIntentStringExtra = launchingIntent.getStringExtra(Intent.EXTRA_TEXT);
6236
6237             // Parse the launching intent URL.
6238             if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) {  // The intent contains a search string.
6239                 // Create an encoded URL string.
6240                 String encodedUrlString;
6241
6242                 // Sanitize the search input and convert it to a search.
6243                 try {
6244                     encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
6245                 } catch (UnsupportedEncodingException exception) {
6246                     encodedUrlString = "";
6247                 }
6248
6249                 // Store the web search as the URL to load.
6250                 urlToLoadString = searchURL + encodedUrlString;
6251             } else if (launchingIntentUriData != null) {  // The launching intent contains a URL formatted as a URI.
6252                 // Store the URI as a URL.
6253                 urlToLoadString = launchingIntentUriData.toString();
6254             } else if (launchingIntentStringExtra != null) {  // The launching intent contains text that might be a URL.
6255                 // Store the URL.
6256                 urlToLoadString = launchingIntentStringExtra;
6257             } else if (!url.equals("")) {  // The activity has been restarted.
6258                 // Load the saved URL.
6259                 urlToLoadString = url;
6260             } else {  // The is no URL in the intent.
6261                 // Store the homepage to be loaded.
6262                 urlToLoadString = sharedPreferences.getString("homepage", getString(R.string.homepage_default_value));
6263             }
6264
6265             // Load the website if not waiting for the proxy.
6266             if (waitingForProxy) {  // Store the URL to be loaded in the Nested Scroll WebView.
6267                 nestedScrollWebView.setWaitingForProxyUrlString(urlToLoadString);
6268             } else {  // Load the URL.
6269                 loadUrl(nestedScrollWebView, urlToLoadString);
6270             }
6271
6272             // 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.
6273             // 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.
6274             setIntent(new Intent());
6275         } else {  // This is not the first tab.
6276             // Load the URL.
6277             loadUrl(nestedScrollWebView, url);
6278
6279             // Set the focus and display the keyboard if the URL is blank.
6280             if (url.equals("")) {
6281                 // Request focus for the URL text box.
6282                 urlEditText.requestFocus();
6283
6284                 // Create a display keyboard handler.
6285                 Handler displayKeyboardHandler = new Handler();
6286
6287                 // Create a display keyboard runnable.
6288                 Runnable displayKeyboardRunnable = () -> {
6289                     // Display the keyboard.
6290                     inputMethodManager.showSoftInput(urlEditText, 0);
6291                 };
6292
6293                 // Display the keyboard after 100 milliseconds, which leaves enough time for the tab to transition.
6294                 displayKeyboardHandler.postDelayed(displayKeyboardRunnable, 100);
6295             }
6296         }
6297     }
6298 }