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