]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/activities/MainWebViewActivity.java
Fix rare crash on applying domain settings. https://redmine.stoutner.com/issues/930
[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                             // Update the status of the swipe refresh layout if the current WebView is not null (crash reports indicate that in some unexpected way it sometimes is null).
3938                             if (currentWebView != null) {
3939                                 // Only enable the swipe refresh layout if the WebView is scrolled to the top.  It is updated every time the scroll changes.
3940                                 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
3941                             }
3942                         } else {  // Swipe to refresh is disabled.
3943                             // Disable the swipe refresh layout.
3944                             swipeRefreshLayout.setEnabled(false);
3945                         }
3946                         break;
3947
3948                     case DomainsDatabaseHelper.ENABLED:
3949                         // Store the swipe to refresh status in the nested scroll WebView.
3950                         nestedScrollWebView.setSwipeToRefresh(true);
3951
3952
3953                         // Update the status of the swipe refresh layout if the current WebView is not null (crash reports indicate that in some unexpected way it sometimes is null).
3954                         if (currentWebView != null) {
3955                             // Only enable the swipe refresh layout if the WebView is scrolled to the top.  It is updated every time the scroll changes.
3956                             swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
3957                         }
3958                         break;
3959
3960                     case DomainsDatabaseHelper.DISABLED:
3961                         // Store the swipe to refresh status in the nested scroll WebView.
3962                         nestedScrollWebView.setSwipeToRefresh(false);
3963
3964                         // Disable swipe to refresh.
3965                         swipeRefreshLayout.setEnabled(false);
3966                         break;
3967                 }
3968
3969                 // Set the WebView theme if device is running API >= 29 and algorithmic darkening is supported.
3970                 if ((Build.VERSION.SDK_INT >= 29) && WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {
3971                     // Set the WebView theme.
3972                     switch (webViewThemeInt) {
3973                         case DomainsDatabaseHelper.SYSTEM_DEFAULT:
3974                             // Set the WebView theme.  A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
3975                             if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) {  // The light theme is selected.
3976                                 // Turn off algorithmic darkening.
3977                                 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), false);
3978                             } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) {  // The dark theme is selected.
3979                                 // Turn on algorithmic darkening.
3980                                 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), true);
3981                             } else {  // The system default theme is selected.
3982                                 // Get the current system theme status.
3983                                 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
3984
3985                                 // Set the algorithmic darkening according to the current system theme status.
3986                                 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES));
3987                             }
3988                             break;
3989
3990                         case DomainsDatabaseHelper.LIGHT_THEME:
3991                             // Turn off algorithmic darkening.
3992                             WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), false);
3993                             break;
3994
3995                         case DomainsDatabaseHelper.DARK_THEME:
3996                             // Turn on algorithmic darkening.
3997                             WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), true);
3998                             break;
3999                     }
4000                 }
4001
4002                 // Set the viewport.
4003                 switch (wideViewportInt) {
4004                     case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4005                         nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
4006                         break;
4007
4008                     case DomainsDatabaseHelper.ENABLED:
4009                         nestedScrollWebView.getSettings().setUseWideViewPort(true);
4010                         break;
4011
4012                     case DomainsDatabaseHelper.DISABLED:
4013                         nestedScrollWebView.getSettings().setUseWideViewPort(false);
4014                         break;
4015                 }
4016
4017                 // Set the loading of webpage images.
4018                 switch (displayWebpageImagesInt) {
4019                     case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4020                         nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4021                         break;
4022
4023                     case DomainsDatabaseHelper.ENABLED:
4024                         nestedScrollWebView.getSettings().setLoadsImagesAutomatically(true);
4025                         break;
4026
4027                     case DomainsDatabaseHelper.DISABLED:
4028                         nestedScrollWebView.getSettings().setLoadsImagesAutomatically(false);
4029                         break;
4030                 }
4031
4032                 // Set a background on the URL relative layout to indicate that custom domain settings are being used.
4033                 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.domain_settings_url_background, null));
4034             } else {  // The new URL does not have custom domain settings.  Load the defaults.
4035                 // Store the values from the shared preferences.
4036                 nestedScrollWebView.getSettings().setJavaScriptEnabled(sharedPreferences.getBoolean(getString(R.string.javascript_key), false));
4037                 nestedScrollWebView.setAcceptCookies(sharedPreferences.getBoolean(getString(R.string.cookies_key), false));
4038                 nestedScrollWebView.getSettings().setDomStorageEnabled(sharedPreferences.getBoolean(getString(R.string.dom_storage_key), false));
4039                 boolean saveFormData = sharedPreferences.getBoolean(getString(R.string.save_form_data_key), false);  // Form data can be removed once the minimum API >= 26.
4040                 nestedScrollWebView.setEasyListEnabled(sharedPreferences.getBoolean(getString(R.string.easylist_key), true));
4041                 nestedScrollWebView.setEasyPrivacyEnabled(sharedPreferences.getBoolean(getString(R.string.easyprivacy_key), true));
4042                 nestedScrollWebView.setFanboysAnnoyanceListEnabled(sharedPreferences.getBoolean(getString(R.string.fanboys_annoyance_list_key), true));
4043                 nestedScrollWebView.setFanboysSocialBlockingListEnabled(sharedPreferences.getBoolean(getString(R.string.fanboys_social_blocking_list_key), true));
4044                 nestedScrollWebView.setUltraListEnabled(sharedPreferences.getBoolean(getString(R.string.ultralist_key), true));
4045                 nestedScrollWebView.setUltraPrivacyEnabled(sharedPreferences.getBoolean(getString(R.string.ultraprivacy_key), true));
4046                 nestedScrollWebView.setBlockAllThirdPartyRequests(sharedPreferences.getBoolean(getString(R.string.block_all_third_party_requests_key), false));
4047
4048                 // Apply the default cookie setting.
4049                 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptCookies());
4050
4051                 // Apply the default font size setting.
4052                 try {
4053                     // Try to set the font size from the value in the app settings.
4054                     nestedScrollWebView.getSettings().setTextZoom(Integer.parseInt(defaultFontSizeString));
4055                 } catch (Exception exception) {
4056                     // If the app settings value is invalid, set the font size to 100%.
4057                     nestedScrollWebView.getSettings().setTextZoom(100);
4058                 }
4059
4060                 // Apply the form data setting if the API < 26.
4061                 if (Build.VERSION.SDK_INT < 26) {
4062                     nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
4063                 }
4064
4065                 // Store the swipe to refresh status in the nested scroll WebView.
4066                 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
4067
4068                 // Update the swipe refresh layout.
4069                 if (defaultSwipeToRefresh) {  // Swipe to refresh is enabled.
4070                     // Update the status of the swipe refresh layout if the current WebView is not null (crash reports indicate that in some unexpected way it sometimes is null).
4071                     if (currentWebView != null) {
4072                         // Only enable the swipe refresh layout if the WebView is scrolled to the top.  It is updated every time the scroll changes.
4073                         swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
4074                     }
4075                 } else {  // Swipe to refresh is disabled.
4076                     // Disable the swipe refresh layout.
4077                     swipeRefreshLayout.setEnabled(false);
4078                 }
4079
4080                 // Reset the pinned variables.
4081                 nestedScrollWebView.setDomainSettingsDatabaseId(-1);
4082
4083                 // Get the array position of the user agent name.
4084                 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4085
4086                 // Set the user agent.
4087                 switch (userAgentArrayPosition) {
4088                     case UNRECOGNIZED_USER_AGENT:  // The default user agent name is not on the canonical list.
4089                         // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4090                         nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
4091                         break;
4092
4093                     case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4094                         // Set the user agent to `""`, which uses the default value.
4095                         nestedScrollWebView.getSettings().setUserAgentString("");
4096                         break;
4097
4098                     case SETTINGS_CUSTOM_USER_AGENT:
4099                         // Set the default custom user agent.
4100                         nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString(getString(R.string.custom_user_agent_key), getString(R.string.custom_user_agent_default_value)));
4101                         break;
4102
4103                     default:
4104                         // Get the user agent string from the user agent data array
4105                         nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4106                 }
4107
4108                 // Set the WebView theme if device is running API >= 29 and algorithmic darkening is supported.
4109                 if ((Build.VERSION.SDK_INT >= 29) && WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {
4110                     // Set the WebView theme.  A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
4111                     if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) {  // the light theme is selected.
4112                         // Turn off algorithmic darkening.
4113                         WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), false);
4114                     } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) {  // The dark theme is selected.
4115                         // Turn on algorithmic darkening.
4116                         WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), true);
4117                     } else {  // The system default theme is selected.
4118                         // Get the current system theme status.
4119                         int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4120
4121                         // Set the algorithmic darkening according to the current system theme status.
4122                         WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), currentThemeStatus == Configuration.UI_MODE_NIGHT_YES);
4123                     }
4124                 }
4125
4126                 // Set the viewport.
4127                 nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
4128
4129                 // Set the loading of webpage images.
4130                 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4131
4132                 // Set a transparent background on the URL relative layout.
4133                 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.color.transparent, null));
4134             }
4135
4136             // Close the domains database helper.
4137             domainsDatabaseHelper.close();
4138
4139             // Update the privacy icons.
4140             updatePrivacyIcons(true);
4141         }
4142
4143         // Reload the website if returning from the Domains activity.
4144         if (reloadWebsite) {
4145             nestedScrollWebView.reload();
4146         }
4147
4148         // 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.
4149         if (loadUrl) {
4150             nestedScrollWebView.loadUrl(url);
4151         }
4152     }
4153
4154     private void applyProxy(boolean reloadWebViews) {
4155         // Set the proxy according to the mode.
4156         proxyHelper.setProxy(getApplicationContext(), appBarLayout, proxyMode);
4157
4158         // Reset the waiting for proxy tracker.
4159         waitingForProxy = false;
4160
4161         // Get the current theme status.
4162         int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4163
4164         // Update the user interface and reload the WebViews if requested.
4165         switch (proxyMode) {
4166             case ProxyHelper.NONE:
4167                 // Initialize a color background typed value.
4168                 TypedValue colorBackgroundTypedValue = new TypedValue();
4169
4170                 // Get the color background from the theme.
4171                 getTheme().resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true);
4172
4173                 // Get the color background int from the typed value.
4174                 int colorBackgroundInt = colorBackgroundTypedValue.data;
4175
4176                 // Set the default app bar layout background.
4177                 appBarLayout.setBackgroundColor(colorBackgroundInt);
4178                 break;
4179
4180             case ProxyHelper.TOR:
4181                 // Set the app bar background to indicate proxying through Orbot is enabled.
4182                 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4183                     appBarLayout.setBackgroundResource(R.color.blue_50);
4184                 } else {
4185                     appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4186                 }
4187
4188                 // Check to see if Orbot is installed.
4189                 try {
4190                     // Get the package manager.
4191                     PackageManager packageManager = getPackageManager();
4192
4193                     // 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.
4194                     packageManager.getPackageInfo("org.torproject.android", 0);
4195
4196                     // Check to see if the proxy is ready.
4197                     if (!orbotStatus.equals(ProxyHelper.ORBOT_STATUS_ON)) {  // Orbot is not ready.
4198                         // Set the waiting for proxy status.
4199                         waitingForProxy = true;
4200
4201                         // Show the waiting for proxy dialog if it isn't already displayed.
4202                         if (getSupportFragmentManager().findFragmentByTag(getString(R.string.waiting_for_proxy_dialog)) == null) {
4203                             // Get a handle for the waiting for proxy alert dialog.
4204                             DialogFragment waitingForProxyDialogFragment = new WaitingForProxyDialog();
4205
4206                             // Try to show the dialog.  Sometimes the window is not yet active if returning from Settings.
4207                             try {
4208                                 // Show the waiting for proxy alert dialog.
4209                                 waitingForProxyDialogFragment.show(getSupportFragmentManager(), getString(R.string.waiting_for_proxy_dialog));
4210                             } catch (Exception waitingForTorException) {
4211                                 // Add the dialog to the pending dialog array list.  It will be displayed in `onStart()`.
4212                                 pendingDialogsArrayList.add(new PendingDialog(waitingForProxyDialogFragment, getString(R.string.waiting_for_proxy_dialog)));
4213                             }
4214                         }
4215                     }
4216                 } catch (PackageManager.NameNotFoundException exception) {  // Orbot is not installed.
4217                     // Show the Orbot not installed dialog if it is not already displayed.
4218                     if (getSupportFragmentManager().findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
4219                         // Get a handle for the Orbot not installed alert dialog.
4220                         DialogFragment orbotNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode);
4221
4222                         // Try to show the dialog.  Sometimes the window is not yet active if returning from Settings.
4223                         try {
4224                             // Display the Orbot not installed alert dialog.
4225                             orbotNotInstalledDialogFragment.show(getSupportFragmentManager(), getString(R.string.proxy_not_installed_dialog));
4226                         } catch (Exception orbotNotInstalledException) {
4227                             // Add the dialog to the pending dialog array list.  It will be displayed in `onStart()`.
4228                             pendingDialogsArrayList.add(new PendingDialog(orbotNotInstalledDialogFragment, getString(R.string.proxy_not_installed_dialog)));
4229                         }
4230                     }
4231                 }
4232                 break;
4233
4234             case ProxyHelper.I2P:
4235                 // Set the app bar background to indicate proxying through Orbot is enabled.
4236                 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4237                     appBarLayout.setBackgroundResource(R.color.blue_50);
4238                 } else {
4239                     appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4240                 }
4241                 // Get the package manager.
4242                 PackageManager packageManager = getPackageManager();
4243
4244                 // Check to see if I2P is installed.
4245                 try {
4246                     // 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.
4247                     packageManager.getPackageInfo("net.i2p.android.router", 0);
4248                 } catch (PackageManager.NameNotFoundException fdroidException) {  // The F-Droid flavor is not installed.
4249                     try {
4250                         // 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.
4251                         packageManager.getPackageInfo("net.i2p.android", 0);
4252                     } catch (PackageManager.NameNotFoundException googlePlayException) {  // The Google Play flavor is not installed.
4253                         // Sow the I2P not installed dialog if it is not already displayed.
4254                         if (getSupportFragmentManager().findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
4255                             // Get a handle for the waiting for proxy alert dialog.
4256                             DialogFragment i2pNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode);
4257
4258                             // Try to show the dialog.  Sometimes the window is not yet active if returning from Settings.
4259                             try {
4260                                 // Display the I2P not installed alert dialog.
4261                                 i2pNotInstalledDialogFragment.show(getSupportFragmentManager(), getString(R.string.proxy_not_installed_dialog));
4262                             } catch (Exception i2pNotInstalledException) {
4263                                 // Add the dialog to the pending dialog array list.  It will be displayed in `onStart()`.
4264                                 pendingDialogsArrayList.add(new PendingDialog(i2pNotInstalledDialogFragment, getString(R.string.proxy_not_installed_dialog)));
4265                             }
4266                         }
4267                     }
4268                 }
4269                 break;
4270
4271             case ProxyHelper.CUSTOM:
4272                 // Set the app bar background to indicate proxying through Orbot is enabled.
4273                 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {
4274                     appBarLayout.setBackgroundResource(R.color.blue_50);
4275                 } else {
4276                     appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4277                 }
4278                 break;
4279         }
4280
4281         // Reload the WebViews if requested and not waiting for the proxy.
4282         if (reloadWebViews && !waitingForProxy) {
4283             // Reload the WebViews.
4284             for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4285                 // Get the WebView tab fragment.
4286                 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4287
4288                 // Get the fragment view.
4289                 View fragmentView = webViewTabFragment.getView();
4290
4291                 // Only reload the WebViews if they exist.
4292                 if (fragmentView != null) {
4293                     // Get the nested scroll WebView from the tab fragment.
4294                     NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4295
4296                     // Reload the WebView.
4297                     nestedScrollWebView.reload();
4298                 }
4299             }
4300         }
4301     }
4302
4303     private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
4304         // Only update the privacy icons if the options menu and the current WebView have already been populated.
4305         if ((optionsMenu != null) && (currentWebView != null)) {
4306             // Update the privacy icon.
4307             if (currentWebView.getSettings().getJavaScriptEnabled()) {  // JavaScript is enabled.
4308                 optionsPrivacyMenuItem.setIcon(R.drawable.javascript_enabled);
4309             } else if (currentWebView.getAcceptCookies()) {  // JavaScript is disabled but cookies are enabled.
4310                 optionsPrivacyMenuItem.setIcon(R.drawable.warning);
4311             } else {  // All the dangerous features are disabled.
4312                 optionsPrivacyMenuItem.setIcon(R.drawable.privacy_mode);
4313             }
4314
4315             // Update the cookies icon.
4316             if (currentWebView.getAcceptCookies()) {
4317                 optionsCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
4318             } else {
4319                 optionsCookiesMenuItem.setIcon(R.drawable.cookies_disabled);
4320             }
4321
4322             // Update the refresh icon.
4323             if (optionsRefreshMenuItem.getTitle() == getString(R.string.refresh)) {  // The refresh icon is displayed.
4324                 // Set the icon.  Once the minimum API is >= 26, the blue and black icons can be combined with a tint list.
4325                 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled);
4326             } else {  // The stop icon is displayed.
4327                 // Set the icon.  Once the minimum API is >= 26, the blue and black icons can be combined with a tint list.
4328                 optionsRefreshMenuItem.setIcon(R.drawable.close_blue);
4329             }
4330
4331             // `invalidateOptionsMenu()` calls `onPrepareOptionsMenu()` and redraws the icons in the app bar.
4332             if (runInvalidateOptionsMenu) {
4333                 invalidateOptionsMenu();
4334             }
4335         }
4336     }
4337
4338     private void highlightUrlText() {
4339         // Only highlight the URL text if the box is not currently selected.
4340         if (!urlEditText.hasFocus()) {
4341             // Get the URL string.
4342             String urlString = urlEditText.getText().toString();
4343
4344             // Highlight the URL according to the protocol.
4345             if (urlString.startsWith("file://") || urlString.startsWith("content://")) {  // This is a file or content URL.
4346                 // De-emphasize everything before the file name.
4347                 urlEditText.getText().setSpan(initialGrayColorSpan, 0, urlString.lastIndexOf("/") + 1,Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4348             } else {  // This is a web URL.
4349                 // Get the index of the `/` immediately after the domain name.
4350                 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
4351
4352                 // Create a base URL string.
4353                 String baseUrl;
4354
4355                 // Get the base URL.
4356                 if (endOfDomainName > 0) {  // There is at least one character after the base URL.
4357                     // Get the base URL.
4358                     baseUrl = urlString.substring(0, endOfDomainName);
4359                 } else {  // There are no characters after the base URL.
4360                     // Set the base URL to be the entire URL string.
4361                     baseUrl = urlString;
4362                 }
4363
4364                 // Get the index of the last `.` in the domain.
4365                 int lastDotIndex = baseUrl.lastIndexOf(".");
4366
4367                 // Get the index of the penultimate `.` in the domain.
4368                 int penultimateDotIndex = baseUrl.lastIndexOf(".", lastDotIndex - 1);
4369
4370                 // Markup the beginning of the URL.
4371                 if (urlString.startsWith("http://")) {  // Highlight the protocol of connections that are not encrypted.
4372                     urlEditText.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4373
4374                     // De-emphasize subdomains.
4375                     if (penultimateDotIndex > 0) {  // There is more than one subdomain in the domain name.
4376                         urlEditText.getText().setSpan(initialGrayColorSpan, 7, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4377                     }
4378                 } else if (urlString.startsWith("https://")) {  // De-emphasize the protocol of connections that are encrypted.
4379                     if (penultimateDotIndex > 0) {  // There is more than one subdomain in the domain name.
4380                         // De-emphasize the protocol and the additional subdomains.
4381                         urlEditText.getText().setSpan(initialGrayColorSpan, 0, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4382                     } else {  // There is only one subdomain in the domain name.
4383                         // De-emphasize only the protocol.
4384                         urlEditText.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4385                     }
4386                 }
4387
4388                 // De-emphasize the text after the domain name.
4389                 if (endOfDomainName > 0) {
4390                     urlEditText.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4391                 }
4392             }
4393         }
4394     }
4395
4396     private void loadBookmarksFolder() {
4397         // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
4398         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
4399
4400         // Populate the bookmarks cursor adapter.
4401         bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
4402             @Override
4403             public View newView(Context context, Cursor cursor, ViewGroup parent) {
4404                 // Inflate the individual item layout.
4405                 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
4406             }
4407
4408             @Override
4409             public void bindView(View view, Context context, Cursor cursor) {
4410                 // Get handles for the views.
4411                 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
4412                 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
4413
4414                 // Get the favorite icon byte array from the cursor.
4415                 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.FAVORITE_ICON));
4416
4417                 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
4418                 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
4419
4420                 // Display the bitmap in `bookmarkFavoriteIcon`.
4421                 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4422
4423                 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4424                 String bookmarkNameString = cursor.getString(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME));
4425                 bookmarkNameTextView.setText(bookmarkNameString);
4426
4427                 // Make the font bold for folders.
4428                 if (cursor.getInt(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4429                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4430                 } else {  // Reset the font to default for normal bookmarks.
4431                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4432                 }
4433             }
4434         };
4435
4436         // Get a handle for the bookmarks list view.
4437         ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
4438
4439         // Populate the list view with the adapter.
4440         bookmarksListView.setAdapter(bookmarksCursorAdapter);
4441
4442         // Get a handle for the bookmarks title text view.
4443         TextView bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
4444
4445         // Set the bookmarks drawer title.
4446         if (currentBookmarksFolder.isEmpty()) {
4447             bookmarksTitleTextView.setText(R.string.bookmarks);
4448         } else {
4449             bookmarksTitleTextView.setText(currentBookmarksFolder);
4450         }
4451     }
4452
4453     private void openWithApp(String url) {
4454         // Create an open with app intent with `ACTION_VIEW`.
4455         Intent openWithAppIntent = new Intent(Intent.ACTION_VIEW);
4456
4457         // Set the URI but not the MIME type.  This should open all available apps.
4458         openWithAppIntent.setData(Uri.parse(url));
4459
4460         // Flag the intent to open in a new task.
4461         openWithAppIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4462
4463         // Try the intent.
4464         try {
4465             // Show the chooser.
4466             startActivity(openWithAppIntent);
4467         } catch (ActivityNotFoundException exception) {  // There are no apps available to open the URL.
4468             // Show a snackbar with the error.
4469             Snackbar.make(currentWebView, getString(R.string.error) + "  " + exception, Snackbar.LENGTH_INDEFINITE).show();
4470         }
4471     }
4472
4473     private void openWithBrowser(String url) {
4474         // Create an open with browser intent with `ACTION_VIEW`.
4475         Intent openWithBrowserIntent = new Intent(Intent.ACTION_VIEW);
4476
4477         // Set the URI and the MIME type.  `"text/html"` should load browser options.
4478         openWithBrowserIntent.setDataAndType(Uri.parse(url), "text/html");
4479
4480         // Flag the intent to open in a new task.
4481         openWithBrowserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4482
4483         // Try the intent.
4484         try {
4485             // Show the chooser.
4486             startActivity(openWithBrowserIntent);
4487         } catch (ActivityNotFoundException exception) {  // There are no browsers available to open the URL.
4488             // Show a snackbar with the error.
4489             Snackbar.make(currentWebView, getString(R.string.error) + "  " + exception, Snackbar.LENGTH_INDEFINITE).show();
4490         }
4491     }
4492
4493     private String sanitizeUrl(String url) {
4494         // Sanitize tracking queries.
4495         if (sanitizeTrackingQueries)
4496             url = sanitizeUrlHelper.sanitizeTrackingQueries(url);
4497
4498         // Sanitize AMP redirects.
4499         if (sanitizeAmpRedirects)
4500             url = sanitizeUrlHelper.sanitizeAmpRedirects(url);
4501
4502         // Return the sanitized URL.
4503         return url;
4504     }
4505
4506     public void finishedPopulatingBlocklists(ArrayList<ArrayList<List<String[]>>> combinedBlocklists) {
4507         // Store the blocklists.
4508         easyList = combinedBlocklists.get(0);
4509         easyPrivacy = combinedBlocklists.get(1);
4510         fanboysAnnoyanceList = combinedBlocklists.get(2);
4511         fanboysSocialList = combinedBlocklists.get(3);
4512         ultraList = combinedBlocklists.get(4);
4513         ultraPrivacy = combinedBlocklists.get(5);
4514
4515         // Check to see if the activity has been restarted with a saved state.
4516         if ((savedStateArrayList == null) || (savedStateArrayList.size() == 0)) {  // The activity has not been restarted or it was restarted on start to force the night theme.
4517             // Add the first tab.
4518             addNewTab("", true);
4519         } else {  // The activity has been restarted.
4520             // Restore each tab.  Once the minimum API >= 24, a `forEach()` command can be used.
4521             for (int i = 0; i < savedStateArrayList.size(); i++) {
4522                 // Add a new tab.
4523                 tabLayout.addTab(tabLayout.newTab());
4524
4525                 // Get the new tab.
4526                 TabLayout.Tab newTab = tabLayout.getTabAt(i);
4527
4528                 // Remove the lint warning below that the current tab might be null.
4529                 assert newTab != null;
4530
4531                 // Set a custom view on the new tab.
4532                 newTab.setCustomView(R.layout.tab_custom_view);
4533
4534                 // Add the new page.
4535                 webViewPagerAdapter.restorePage(savedStateArrayList.get(i), savedNestedScrollWebViewStateArrayList.get(i));
4536             }
4537
4538             // Reset the saved state variables.
4539             savedStateArrayList = null;
4540             savedNestedScrollWebViewStateArrayList = null;
4541
4542             // Restore the selected tab position.
4543             if (savedTabPosition == 0) {  // The first tab is selected.
4544                 // Set the first page as the current WebView.
4545                 setCurrentWebView(0);
4546             } else {  // the first tab is not selected.
4547                 // Move to the selected tab.
4548                 webViewPager.setCurrentItem(savedTabPosition);
4549             }
4550
4551             // Get the intent that started the app.
4552             Intent intent = getIntent();
4553
4554             // Reset the intent.  This prevents a duplicate tab from being created on restart.
4555             setIntent(new Intent());
4556
4557             // Get the information from the intent.
4558             String intentAction = intent.getAction();
4559             Uri intentUriData = intent.getData();
4560             String intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT);
4561
4562             // Determine if this is a web search.
4563             boolean isWebSearch = ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH));
4564
4565             // 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.
4566             if (intentUriData != null || intentStringExtra != null || isWebSearch) {
4567                 // Get the shared preferences.
4568                 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4569
4570                 // Create a URL string.
4571                 String url;
4572
4573                 // If the intent action is a web search, perform the search.
4574                 if (isWebSearch) {  // The intent is a web search.
4575                     // Create an encoded URL string.
4576                     String encodedUrlString;
4577
4578                     // Sanitize the search input and convert it to a search.
4579                     try {
4580                         encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
4581                     } catch (UnsupportedEncodingException exception) {
4582                         encodedUrlString = "";
4583                     }
4584
4585                     // Add the base search URL.
4586                     url = searchURL + encodedUrlString;
4587                 } else if (intentUriData != null) {  // The intent contains a URL formatted as a URI.
4588                     // Set the intent data as the URL.
4589                     url = intentUriData.toString();
4590                 } else {  // The intent contains a string, which might be a URL.
4591                     // Set the intent string as the URL.
4592                     url = intentStringExtra;
4593                 }
4594
4595                 // Add a new tab if specified in the preferences.
4596                 if (sharedPreferences.getBoolean(getString(R.string.open_intents_in_new_tab_key), true)) {  // Load the URL in a new tab.
4597                     // Set the loading new intent flag.
4598                     loadingNewIntent = true;
4599
4600                     // Add a new tab.
4601                     addNewTab(url, true);
4602                 } else {  // Load the URL in the current tab.
4603                     // Make it so.
4604                     loadUrl(currentWebView, url);
4605                 }
4606             }
4607         }
4608     }
4609
4610     public void addTab(View view) {
4611         // Add a new tab with a blank URL.
4612         addNewTab("", true);
4613     }
4614
4615     private void addNewTab(String url, boolean moveToTab) {
4616         // Clear the focus from the URL edit text, so that it will be populated with the information from the new tab.
4617         urlEditText.clearFocus();
4618
4619         // Get the new page number.  The page numbers are 0 indexed, so the new page number will match the current count.
4620         int newTabNumber = tabLayout.getTabCount();
4621
4622         // Add a new tab.
4623         tabLayout.addTab(tabLayout.newTab());
4624
4625         // Get the new tab.
4626         TabLayout.Tab newTab = tabLayout.getTabAt(newTabNumber);
4627
4628         // Remove the lint warning below that the current tab might be null.
4629         assert newTab != null;
4630
4631         // Set a custom view on the new tab.
4632         newTab.setCustomView(R.layout.tab_custom_view);
4633
4634         // Add the new WebView page.
4635         webViewPagerAdapter.addPage(newTabNumber, webViewPager, url, moveToTab);
4636
4637         // Show the app bar if it is at the bottom of the screen and the new tab is taking focus.
4638         if (bottomAppBar && moveToTab && (appBarLayout.getTranslationY() != 0)) {
4639             // Animate the bottom app bar onto the screen.
4640             objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0);
4641
4642             // Make it so.
4643             objectAnimator.start();
4644         }
4645     }
4646
4647     public void closeTab(View view) {
4648         // Run the command according to the number of tabs.
4649         if (tabLayout.getTabCount() > 1) {  // There is more than one tab open.
4650             // Close the current tab.
4651             closeCurrentTab();
4652         } else {  // There is only one tab open.
4653             clearAndExit();
4654         }
4655     }
4656
4657     private void closeCurrentTab() {
4658         // Get the current tab number.
4659         int currentTabNumber = tabLayout.getSelectedTabPosition();
4660
4661         // Delete the current tab.
4662         tabLayout.removeTabAt(currentTabNumber);
4663
4664         // 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,
4665         // meaning that the current WebView must be reset.  Otherwise it will happen automatically as the selected tab number changes.
4666         if (webViewPagerAdapter.deletePage(currentTabNumber, webViewPager)) {
4667             setCurrentWebView(currentTabNumber);
4668         }
4669     }
4670
4671     private void exitFullScreenVideo() {
4672         // Re-enable the screen timeout.
4673         fullScreenVideoFrameLayout.setKeepScreenOn(false);
4674
4675         // Unset the full screen video flag.
4676         displayingFullScreenVideo = false;
4677
4678         // Remove all the views from the full screen video frame layout.
4679         fullScreenVideoFrameLayout.removeAllViews();
4680
4681         // Hide the full screen video frame layout.
4682         fullScreenVideoFrameLayout.setVisibility(View.GONE);
4683
4684         // Enable the sliding drawers.
4685         drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
4686
4687         // Show the coordinator layout.
4688         coordinatorLayout.setVisibility(View.VISIBLE);
4689
4690         // Apply the appropriate full screen mode flags.
4691         if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {  // Privacy Browser is currently in full screen browsing mode.
4692             // Hide the app bar if specified.
4693             if (hideAppBar) {
4694                 // Hide the tab linear layout.
4695                 tabsLinearLayout.setVisibility(View.GONE);
4696
4697                 // Hide the action bar.
4698                 actionBar.hide();
4699             }
4700
4701             /* Hide the system bars.
4702              * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4703              * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4704              * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4705              * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4706              */
4707             rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
4708                     View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
4709         } else {  // Switch to normal viewing mode.
4710             // Remove the `SYSTEM_UI` flags from the root frame layout.
4711             rootFrameLayout.setSystemUiVisibility(0);
4712         }
4713     }
4714
4715     private void clearAndExit() {
4716         // Get a handle for the shared preferences.
4717         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4718
4719         // Close the bookmarks cursor and database.
4720         bookmarksCursor.close();
4721         bookmarksDatabaseHelper.close();
4722
4723         // Get the status of the clear everything preference.
4724         boolean clearEverything = sharedPreferences.getBoolean(getString(R.string.clear_everything_key), true);
4725
4726         // Get a handle for the runtime.
4727         Runtime runtime = Runtime.getRuntime();
4728
4729         // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
4730         // which links to `/data/data/com.stoutner.privacybrowser.standard`.
4731         String privateDataDirectoryString = getApplicationInfo().dataDir;
4732
4733         // Clear cookies.
4734         if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_cookies_key), true)) {
4735             // Request the cookies be deleted.
4736             CookieManager.getInstance().removeAllCookies(null);
4737
4738             // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4739             try {
4740                 // Two commands must be used because `Runtime.exec()` does not like `*`.
4741                 Process deleteCookiesProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
4742                 Process deleteCookiesJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
4743
4744                 // Wait until the processes have finished.
4745                 deleteCookiesProcess.waitFor();
4746                 deleteCookiesJournalProcess.waitFor();
4747             } catch (Exception exception) {
4748                 // Do nothing if an error is thrown.
4749             }
4750         }
4751
4752         // Clear DOM storage.
4753         if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_dom_storage_key), true)) {
4754             // Ask `WebStorage` to clear the DOM storage.
4755             WebStorage webStorage = WebStorage.getInstance();
4756             webStorage.deleteAllData();
4757
4758             // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4759             try {
4760                 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4761                 Process deleteLocalStorageProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
4762
4763                 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
4764                 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
4765                 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
4766                 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
4767                 Process deleteDatabaseProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
4768
4769                 // Wait until the processes have finished.
4770                 deleteLocalStorageProcess.waitFor();
4771                 deleteIndexProcess.waitFor();
4772                 deleteQuotaManagerProcess.waitFor();
4773                 deleteQuotaManagerJournalProcess.waitFor();
4774                 deleteDatabaseProcess.waitFor();
4775             } catch (Exception exception) {
4776                 // Do nothing if an error is thrown.
4777             }
4778         }
4779
4780         // Clear form data if the API < 26.
4781         if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_form_data_key), true))) {
4782             WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
4783             webViewDatabase.clearFormData();
4784
4785             // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4786             try {
4787                 // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
4788                 Process deleteWebDataProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
4789                 Process deleteWebDataJournalProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
4790
4791                 // Wait until the processes have finished.
4792                 deleteWebDataProcess.waitFor();
4793                 deleteWebDataJournalProcess.waitFor();
4794             } catch (Exception exception) {
4795                 // Do nothing if an error is thrown.
4796             }
4797         }
4798
4799         // Clear the logcat.
4800         if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_logcat_key), true)) {
4801             try {
4802                 // Clear the logcat.  `-c` clears the logcat.  `-b all` clears all the buffers (instead of just crash, main, and system).
4803                 Process process = Runtime.getRuntime().exec("logcat -b all -c");
4804
4805                 // Wait for the process to finish.
4806                 process.waitFor();
4807             } catch (IOException|InterruptedException exception) {
4808                 // Do nothing.
4809             }
4810         }
4811
4812         // Clear the cache.
4813         if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_cache_key), true)) {
4814             // Clear the cache from each WebView.
4815             for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4816                 // Get the WebView tab fragment.
4817                 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4818
4819                 // Get the WebView fragment view.
4820                 View webViewFragmentView = webViewTabFragment.getView();
4821
4822                 // Only clear the cache if the WebView exists.
4823                 if (webViewFragmentView != null) {
4824                     // Get the nested scroll WebView from the tab fragment.
4825                     NestedScrollWebView nestedScrollWebView = webViewFragmentView.findViewById(R.id.nestedscroll_webview);
4826
4827                     // Clear the cache for this WebView.
4828                     nestedScrollWebView.clearCache(true);
4829                 }
4830             }
4831
4832             // Manually delete the cache directories.
4833             try {
4834                 // Delete the main cache directory.
4835                 Process deleteCacheProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/cache");
4836
4837                 // Delete the secondary `Service Worker` cache directory.
4838                 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4839                 Process deleteServiceWorkerProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Default/Service Worker/"});
4840
4841                 // Wait until the processes have finished.
4842                 deleteCacheProcess.waitFor();
4843                 deleteServiceWorkerProcess.waitFor();
4844             } catch (Exception exception) {
4845                 // Do nothing if an error is thrown.
4846             }
4847         }
4848
4849         // Wipe out each WebView.
4850         for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4851             // Get the WebView tab fragment.
4852             WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4853
4854             // Get the WebView frame layout.
4855             FrameLayout webViewFrameLayout = (FrameLayout) webViewTabFragment.getView();
4856
4857             // Only wipe out the WebView if it exists.
4858             if (webViewFrameLayout != null) {
4859                 // Get the nested scroll WebView from the tab fragment.
4860                 NestedScrollWebView nestedScrollWebView = webViewFrameLayout.findViewById(R.id.nestedscroll_webview);
4861
4862                 // Clear SSL certificate preferences for this WebView.
4863                 nestedScrollWebView.clearSslPreferences();
4864
4865                 // Clear the back/forward history for this WebView.
4866                 nestedScrollWebView.clearHistory();
4867
4868                 // Remove all the views from the frame layout.
4869                 webViewFrameLayout.removeAllViews();
4870
4871                 // Destroy the internal state of the WebView.
4872                 nestedScrollWebView.destroy();
4873             }
4874         }
4875
4876         // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
4877         // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
4878         if (clearEverything) {
4879             try {
4880                 // Delete the folder.
4881                 Process deleteAppWebviewProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
4882
4883                 // Wait until the process has finished.
4884                 deleteAppWebviewProcess.waitFor();
4885             } catch (Exception exception) {
4886                 // Do nothing if an error is thrown.
4887             }
4888         }
4889
4890         // Close Privacy Browser.  `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
4891         finishAndRemoveTask();
4892
4893         // Remove the terminated program from RAM.  The status code is `0`.
4894         System.exit(0);
4895     }
4896
4897     public void bookmarksBack(View view) {
4898         if (currentBookmarksFolder.isEmpty()) {  // The home folder is displayed.
4899             // close the bookmarks drawer.
4900             drawerLayout.closeDrawer(GravityCompat.END);
4901         } else {  // A subfolder is displayed.
4902             // Place the former parent folder in `currentFolder`.
4903             currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolderName(currentBookmarksFolder);
4904
4905             // Load the new folder.
4906             loadBookmarksFolder();
4907         }
4908     }
4909
4910     private void setCurrentWebView(int pageNumber) {
4911         // Stop the swipe to refresh indicator if it is running
4912         swipeRefreshLayout.setRefreshing(false);
4913
4914         // Get the WebView tab fragment.
4915         WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(pageNumber);
4916
4917         // Get the fragment view.
4918         View webViewFragmentView = webViewTabFragment.getView();
4919
4920         // Set the current WebView if the fragment view is not null.
4921         if (webViewFragmentView != null) {  // The fragment has been populated.
4922             // Store the current WebView.
4923             currentWebView = webViewFragmentView.findViewById(R.id.nestedscroll_webview);
4924
4925             // Update the status of swipe to refresh.
4926             if (currentWebView.getSwipeToRefresh()) {  // Swipe to refresh is enabled.
4927                 // Enable the swipe refresh layout if the WebView is scrolled all the way to the top.  It is updated every time the scroll changes.
4928                 swipeRefreshLayout.setEnabled(currentWebView.getScrollY() == 0);
4929             } else {  // Swipe to refresh is disabled.
4930                 // Disable the swipe refresh layout.
4931                 swipeRefreshLayout.setEnabled(false);
4932             }
4933
4934             // Get a handle for the cookie manager.
4935             CookieManager cookieManager = CookieManager.getInstance();
4936
4937             // Set the cookie status.
4938             cookieManager.setAcceptCookie(currentWebView.getAcceptCookies());
4939
4940             // Update the privacy icons.  `true` redraws the icons in the app bar.
4941             updatePrivacyIcons(true);
4942
4943             // Get a handle for the input method manager.
4944             InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
4945
4946             // Remove the lint warning below that the input method manager might be null.
4947             assert inputMethodManager != null;
4948
4949             // Get the current URL.
4950             String url = currentWebView.getUrl();
4951
4952             // Update the URL edit text if not loading a new intent.  Otherwise, this will be handled by `onPageStarted()` (if called) and `onPageFinished()`.
4953             if (!loadingNewIntent) {  // A new intent is not being loaded.
4954                 if ((url == null) || url.equals("about:blank")) {  // The WebView is blank.
4955                     // Display the hint in the URL edit text.
4956                     urlEditText.setText("");
4957
4958                     // Request focus for the URL text box.
4959                     urlEditText.requestFocus();
4960
4961                     // Display the keyboard.
4962                     inputMethodManager.showSoftInput(urlEditText, 0);
4963                 } else {  // The WebView has a loaded URL.
4964                     // Clear the focus from the URL text box.
4965                     urlEditText.clearFocus();
4966
4967                     // Hide the soft keyboard.
4968                     inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
4969
4970                     // Display the current URL in the URL text box.
4971                     urlEditText.setText(url);
4972
4973                     // Highlight the URL text.
4974                     highlightUrlText();
4975                 }
4976             } else {  // A new intent is being loaded.
4977                 // Reset the loading new intent tracker.
4978                 loadingNewIntent = false;
4979             }
4980
4981             // Set the background to indicate the domain settings status.
4982             if (currentWebView.getDomainSettingsApplied()) {
4983                 // Set a background on the URL relative layout to indicate that custom domain settings are being used.
4984                 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.domain_settings_url_background, null));
4985             } else {
4986                 // Remove any background on the URL relative layout.
4987                 urlRelativeLayout.setBackground(ResourcesCompat.getDrawable(getResources(), R.color.transparent, null));
4988             }
4989         } else {  // The fragment has not been populated.  Try again in 100 milliseconds.
4990             // Create a handler to set the current WebView.
4991             Handler setCurrentWebViewHandler = new Handler();
4992
4993             // Create a runnable to set the current WebView.
4994             Runnable setCurrentWebWebRunnable = () -> {
4995                 // Set the current WebView.
4996                 setCurrentWebView(pageNumber);
4997             };
4998
4999             // Try setting the current WebView again after 100 milliseconds.
5000             setCurrentWebViewHandler.postDelayed(setCurrentWebWebRunnable, 100);
5001         }
5002     }
5003
5004     @SuppressLint("ClickableViewAccessibility")
5005     @Override
5006     public void initializeWebView(@NonNull NestedScrollWebView nestedScrollWebView, int pageNumber, @NonNull ProgressBar progressBar, @NonNull String url, boolean restoringState) {
5007         // Get a handle for the shared preferences.
5008         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
5009
5010         // Get the WebView theme.
5011         String webViewTheme = sharedPreferences.getString(getString(R.string.webview_theme_key), getString(R.string.webview_theme_default_value));
5012
5013         // Get the WebView theme entry values string array.
5014         String[] webViewThemeEntryValuesStringArray = getResources().getStringArray(R.array.webview_theme_entry_values);
5015
5016         // Set the WebView theme if device is running API >= 29 and algorithmic darkening is supported.
5017         if ((Build.VERSION.SDK_INT >= 29) && WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {
5018             // Set the WebView them.  A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
5019             if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) {  // The light theme is selected.
5020                 // Turn off algorithmic darkening.
5021                 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), false);
5022
5023                 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
5024                 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
5025                 nestedScrollWebView.setVisibility(View.VISIBLE);
5026             } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) {  // The dark theme is selected.
5027                 // Turn on algorithmic darkening.
5028                 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), true);
5029             } else {
5030                 // The system default theme is selected.
5031                 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
5032
5033                 // Set the algorithmic darkening according to the current system theme status.
5034                 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {  // The system is in day mode.
5035                     // Turn off algorithmic darkening.
5036                     WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), false);
5037
5038                     // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
5039                     // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
5040                     nestedScrollWebView.setVisibility(View.VISIBLE);
5041                 } else {  // The system is in night mode.
5042                     // Turn on algorithmic darkening.
5043                     WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.getSettings(), true);
5044                 }
5045             }
5046         }
5047
5048         // Get a handle for the activity
5049         Activity activity = this;
5050
5051         // Get a handle for the input method manager.
5052         InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
5053
5054         // Instantiate the blocklist helper.
5055         BlocklistHelper blocklistHelper = new BlocklistHelper();
5056
5057         // Remove the lint warning below that the input method manager might be null.
5058         assert inputMethodManager != null;
5059
5060         // Set the app bar scrolling.
5061         nestedScrollWebView.setNestedScrollingEnabled(scrollAppBar);
5062
5063         // Allow pinch to zoom.
5064         nestedScrollWebView.getSettings().setBuiltInZoomControls(true);
5065
5066         // Hide zoom controls.
5067         nestedScrollWebView.getSettings().setDisplayZoomControls(false);
5068
5069         // Don't allow mixed content (HTTP and HTTPS) on the same website.
5070         nestedScrollWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);
5071
5072         // Set the WebView to load in overview mode (zoomed out to the maximum width).
5073         nestedScrollWebView.getSettings().setLoadWithOverviewMode(true);
5074
5075         // Explicitly disable geolocation.
5076         nestedScrollWebView.getSettings().setGeolocationEnabled(false);
5077
5078         // Allow loading of file:// URLs.  This is necessary for opening MHT web archives, which are copies into a temporary cache location.
5079         nestedScrollWebView.getSettings().setAllowFileAccess(true);
5080
5081         // Create a double-tap gesture detector to toggle full-screen mode.
5082         GestureDetector doubleTapGestureDetector = new GestureDetector(getApplicationContext(), new GestureDetector.SimpleOnGestureListener() {
5083             // Override `onDoubleTap()`.  All other events are handled using the default settings.
5084             @Override
5085             public boolean onDoubleTap(MotionEvent event) {
5086                 if (fullScreenBrowsingModeEnabled) {  // Only process the double-tap if full screen browsing mode is enabled.
5087                     // Toggle the full screen browsing mode tracker.
5088                     inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
5089
5090                     // Toggle the full screen browsing mode.
5091                     if (inFullScreenBrowsingMode) {  // Switch to full screen mode.
5092                         // Hide the app bar if specified.
5093                         if (hideAppBar) {  // The app bar is hidden.
5094                             // Close the find on page bar if it is visible.
5095                             closeFindOnPage(null);
5096
5097                             // Hide the tab linear layout.
5098                             tabsLinearLayout.setVisibility(View.GONE);
5099
5100                             // Hide the action bar.
5101                             actionBar.hide();
5102
5103                             // Set layout and scrolling parameters according to the position of the app bar.
5104                             if (bottomAppBar) {  // The app bar is at the bottom.
5105                                 // Reset the WebView padding to fill the available space.
5106                                 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5107                             } else {  // The app bar is at the top.
5108                                 // Check to see if the app bar is normally scrolled.
5109                                 if (scrollAppBar) {  // The app bar is scrolled when it is displayed.
5110                                     // Get the swipe refresh layout parameters.
5111                                     CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
5112
5113                                     // Remove the off-screen scrolling layout.
5114                                     swipeRefreshLayoutParams.setBehavior(null);
5115                                 } else {  // The app bar is not scrolled when it is displayed.
5116                                     // Remove the padding from the top of the swipe refresh layout.
5117                                     swipeRefreshLayout.setPadding(0, 0, 0, 0);
5118
5119                                     // The swipe refresh circle must be moved above the now removed status bar location.
5120                                     swipeRefreshLayout.setProgressViewOffset(false, -200, defaultProgressViewEndOffset);
5121                                 }
5122                             }
5123                         } else {  // The app bar is not hidden.
5124                             // Adjust the UI for the bottom app bar.
5125                             if (bottomAppBar) {
5126                                 // Adjust the UI according to the scrolling of the app bar.
5127                                 if (scrollAppBar) {
5128                                     // Reset the WebView padding to fill the available space.
5129                                     swipeRefreshLayout.setPadding(0, 0, 0, 0);
5130                                 } else {
5131                                     // Move the WebView above the app bar layout.
5132                                     swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight);
5133                                 }
5134                             }
5135                         }
5136
5137                         /* Hide the system bars.
5138                          * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5139                          * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5140                          * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5141                          * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5142                          */
5143                         rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5144                                 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5145                     } else {  // Switch to normal viewing mode.
5146                         // Show the app bar if it was hidden.
5147                         if (hideAppBar) {
5148                             // Show the tab linear layout.
5149                             tabsLinearLayout.setVisibility(View.VISIBLE);
5150
5151                             // Show the action bar.
5152                             actionBar.show();
5153                         }
5154
5155                         // Set layout and scrolling parameters according to the position of the app bar.
5156                         if (bottomAppBar) {  // The app bar is at the bottom.
5157                             // Adjust the UI.
5158                             if (scrollAppBar) {
5159                                 // Reset the WebView padding to fill the available space.
5160                                 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5161                             } else {
5162                                 // Move the WebView above the app bar layout.
5163                                 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight);
5164                             }
5165                         } else {  // The app bar is at the top.
5166                             // Check to see if the app bar is normally scrolled.
5167                             if (scrollAppBar) {  // The app bar is scrolled when it is displayed.
5168                                 // Get the swipe refresh layout parameters.
5169                                 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
5170
5171                                 // Add the off-screen scrolling layout.
5172                                 swipeRefreshLayoutParams.setBehavior(new AppBarLayout.ScrollingViewBehavior());
5173                             } else {  // The app bar is not scrolled when it is displayed.
5174                                 // The swipe refresh layout must be manually moved below the app bar layout.
5175                                 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0);
5176
5177                                 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5178                                 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight);
5179                             }
5180                         }
5181
5182                         // Remove the `SYSTEM_UI` flags from the root frame layout.
5183                         rootFrameLayout.setSystemUiVisibility(0);
5184                     }
5185
5186                     // Consume the double-tap.
5187                     return true;
5188                 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
5189                     return false;
5190                 }
5191             }
5192
5193             @Override
5194             public boolean onFling(MotionEvent motionEvent1, MotionEvent motionEvent2, float velocityX, float velocityY) {
5195                 // Scroll the bottom app bar if enabled.
5196                 if (bottomAppBar && scrollAppBar && !objectAnimator.isRunning()) {
5197                     // Calculate the Y change.
5198                     float motionY = motionEvent2.getY() - motionEvent1.getY();
5199
5200                     // Scroll the app bar if the change is greater than 50 pixels.
5201                     if (motionY > 50) {
5202                         // Animate the bottom app bar onto the screen.
5203                         objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0);
5204                     } else if (motionY < -50) {
5205                         // Animate the bottom app bar off the screen.
5206                         objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", appBarLayout.getHeight());
5207                     }
5208
5209                     // Make it so.
5210                     objectAnimator.start();
5211                 }
5212
5213                 // Do not consume the event.
5214                 return false;
5215             }
5216         });
5217
5218         // Pass all touch events on the WebView through the double-tap gesture detector.
5219         nestedScrollWebView.setOnTouchListener((View view, MotionEvent event) -> {
5220             // Call `performClick()` on the view, which is required for accessibility.
5221             view.performClick();
5222
5223             // Send the event to the gesture detector.
5224             return doubleTapGestureDetector.onTouchEvent(event);
5225         });
5226
5227         // Register the WebView for a context menu.  This is used to see link targets and download images.
5228         registerForContextMenu(nestedScrollWebView);
5229
5230         // Allow the downloading of files.
5231         nestedScrollWebView.setDownloadListener((String downloadUrl, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
5232             // Check the download preference.
5233             if (downloadWithExternalApp) {  // Download with an external app.
5234                 downloadUrlWithExternalApp(downloadUrl);
5235             } else {  // Handle the download inside of Privacy Browser.
5236                 // Define a formatted file size string.
5237                 String formattedFileSizeString;
5238
5239                 // Process the content length if it contains data.
5240                 if (contentLength > 0) {  // The content length is greater than 0.
5241                     // Format the content length as a string.
5242                     formattedFileSizeString = NumberFormat.getInstance().format(contentLength) + " " + getString(R.string.bytes);
5243                 } else {  // The content length is not greater than 0.
5244                     // Set the formatted file size string to be `unknown size`.
5245                     formattedFileSizeString = getString(R.string.unknown_size);
5246                 }
5247
5248                 // Get the file name from the content disposition.
5249                 String fileNameString = PrepareSaveDialog.getFileNameFromHeaders(this, contentDisposition, mimetype, downloadUrl);
5250
5251                 // Instantiate the save dialog.
5252                 DialogFragment saveDialogFragment = SaveDialog.saveUrl(downloadUrl, formattedFileSizeString, fileNameString, userAgent,
5253                         nestedScrollWebView.getAcceptCookies());
5254
5255                 // 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.
5256                 try {
5257                     // Show the save dialog.  It must be named `save_dialog` so that the file picker can update the file name.
5258                     saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
5259                 } catch (Exception exception) {  // The dialog could not be shown.
5260                     // Add the dialog to the pending dialog array list.  It will be displayed in `onStart()`.
5261                     pendingDialogsArrayList.add(new PendingDialog(saveDialogFragment, getString(R.string.save_dialog)));
5262                 }
5263             }
5264         });
5265
5266         // Update the find on page count.
5267         nestedScrollWebView.setFindListener(new WebView.FindListener() {
5268             // Get a handle for `findOnPageCountTextView`.
5269             final TextView findOnPageCountTextView = findViewById(R.id.find_on_page_count_textview);
5270
5271             @Override
5272             public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
5273                 if ((isDoneCounting) && (numberOfMatches == 0)) {  // There are no matches.
5274                     // Set `findOnPageCountTextView` to `0/0`.
5275                     findOnPageCountTextView.setText(R.string.zero_of_zero);
5276                 } else if (isDoneCounting) {  // There are matches.
5277                     // `activeMatchOrdinal` is zero-based.
5278                     int activeMatch = activeMatchOrdinal + 1;
5279
5280                     // Build the match string.
5281                     String matchString = activeMatch + "/" + numberOfMatches;
5282
5283                     // Set `findOnPageCountTextView`.
5284                     findOnPageCountTextView.setText(matchString);
5285                 }
5286             }
5287         });
5288
5289         // Process scroll changes.
5290         nestedScrollWebView.setOnScrollChangeListener((view, scrollX, scrollY, oldScrollX, oldScrollY) -> {
5291             // Set the swipe to refresh status.
5292             if (nestedScrollWebView.getSwipeToRefresh()) {
5293                 // Only enable swipe to refresh if the WebView is scrolled to the top.
5294                 swipeRefreshLayout.setEnabled(nestedScrollWebView.getScrollY() == 0);
5295             } else {
5296                 // Disable swipe to refresh.
5297                 swipeRefreshLayout.setEnabled(false);
5298             }
5299
5300             // Reinforce the system UI visibility flags if in full screen browsing mode.
5301             // This hides the status and navigation bars, which are displayed if other elements are shown, like dialog boxes, the options menu, or the keyboard.
5302             if (inFullScreenBrowsingMode) {
5303                 /* Hide the system bars.
5304                  * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5305                  * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5306                  * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5307                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5308                  */
5309                 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5310                         View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5311             }
5312         });
5313
5314         // Set the web chrome client.
5315         nestedScrollWebView.setWebChromeClient(new WebChromeClient() {
5316             // Update the progress bar when a page is loading.
5317             @Override
5318             public void onProgressChanged(WebView view, int progress) {
5319                 // Update the progress bar.
5320                 progressBar.setProgress(progress);
5321
5322                 // Set the visibility of the progress bar.
5323                 if (progress < 100) {
5324                     // Show the progress bar.
5325                     progressBar.setVisibility(View.VISIBLE);
5326                 } else {
5327                     // Hide the progress bar.
5328                     progressBar.setVisibility(View.GONE);
5329
5330                     //Stop the swipe to refresh indicator if it is running
5331                     swipeRefreshLayout.setRefreshing(false);
5332
5333                     // 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.
5334                     nestedScrollWebView.setVisibility(View.VISIBLE);
5335                 }
5336             }
5337
5338             // Set the favorite icon when it changes.
5339             @Override
5340             public void onReceivedIcon(WebView view, Bitmap icon) {
5341                 // Only update the favorite icon if the website has finished loading.
5342                 if (progressBar.getVisibility() == View.GONE) {
5343                     // Store the new favorite icon.
5344                     nestedScrollWebView.setFavoriteOrDefaultIcon(icon);
5345
5346                     // Get the current page position.
5347                     int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5348
5349                     // Get the current tab.
5350                     TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
5351
5352                     // Check to see if the tab has been populated.
5353                     if (tab != null) {
5354                         // Get the custom view from the tab.
5355                         View tabView = tab.getCustomView();
5356
5357                         // Check to see if the custom tab view has been populated.
5358                         if (tabView != null) {
5359                             // Get the favorite icon image view from the tab.
5360                             ImageView tabFavoriteIconImageView = tabView.findViewById(R.id.favorite_icon_imageview);
5361
5362                             // Display the favorite icon in the tab.
5363                             tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
5364                         }
5365                     }
5366                 }
5367             }
5368
5369             // Save a copy of the title when it changes.
5370             @Override
5371             public void onReceivedTitle(WebView view, String title) {
5372                 // Get the current page position.
5373                 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5374
5375                 // Get the current tab.
5376                 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
5377
5378                 // Only populate the title text view if the tab has been fully created.
5379                 if (tab != null) {
5380                     // Get the custom view from the tab.
5381                     View tabView = tab.getCustomView();
5382
5383                     // Only populate the title text view if the tab view has been fully populated.
5384                     if (tabView != null) {
5385                         // Get the title text view from the tab.
5386                         TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
5387
5388                         // Set the title according to the URL.
5389                         if (title.equals("about:blank")) {
5390                             // Set the title to indicate a new tab.
5391                             tabTitleTextView.setText(R.string.new_tab);
5392                         } else {
5393                             // Set the title as the tab text.
5394                             tabTitleTextView.setText(title);
5395                         }
5396                     }
5397                 }
5398             }
5399
5400             // Enter full screen video.
5401             @Override
5402             public void onShowCustomView(View video, CustomViewCallback callback) {
5403                 // Set the full screen video flag.
5404                 displayingFullScreenVideo = true;
5405
5406                 // Hide the keyboard.
5407                 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
5408
5409                 // Hide the coordinator layout.
5410                 coordinatorLayout.setVisibility(View.GONE);
5411
5412                 /* Hide the system bars.
5413                  * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5414                  * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5415                  * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5416                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5417                  */
5418                 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5419                         View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5420
5421                 // Disable the sliding drawers.
5422                 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
5423
5424                 // Add the video view to the full screen video frame layout.
5425                 fullScreenVideoFrameLayout.addView(video);
5426
5427                 // Show the full screen video frame layout.
5428                 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
5429
5430                 // Disable the screen timeout while the video is playing.  YouTube does this automatically, but not all other videos do.
5431                 fullScreenVideoFrameLayout.setKeepScreenOn(true);
5432             }
5433
5434             // Exit full screen video.
5435             @Override
5436             public void onHideCustomView() {
5437                 // Exit the full screen video.
5438                 exitFullScreenVideo();
5439             }
5440
5441             // Upload files.
5442             @Override
5443             public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
5444                 // Store the file path callback.
5445                 fileChooserCallback = filePathCallback;
5446
5447                 // Create an intent to open a chooser based on the file chooser parameters.
5448                 Intent fileChooserIntent = fileChooserParams.createIntent();
5449
5450                 // Get a handle for the package manager.
5451                 PackageManager packageManager = getPackageManager();
5452
5453                 // Check to see if the file chooser intent resolves to an installed package.
5454                 if (fileChooserIntent.resolveActivity(packageManager) != null) {  // The file chooser intent is fine.
5455                     // Start the file chooser intent.
5456                     startActivityForResult(fileChooserIntent, BROWSE_FILE_UPLOAD_REQUEST_CODE);
5457                 } else {  // The file chooser intent will cause a crash.
5458                     // Create a generic intent to open a chooser.
5459                     Intent genericFileChooserIntent = new Intent(Intent.ACTION_GET_CONTENT);
5460
5461                     // Request an openable file.
5462                     genericFileChooserIntent.addCategory(Intent.CATEGORY_OPENABLE);
5463
5464                     // Set the file type to everything.
5465                     genericFileChooserIntent.setType("*/*");
5466
5467                     // Start the generic file chooser intent.
5468                     startActivityForResult(genericFileChooserIntent, BROWSE_FILE_UPLOAD_REQUEST_CODE);
5469                 }
5470                 return true;
5471             }
5472         });
5473
5474         nestedScrollWebView.setWebViewClient(new WebViewClient() {
5475             // `shouldOverrideUrlLoading` makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
5476             // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
5477             @Override
5478             public boolean shouldOverrideUrlLoading(WebView view, String url) {
5479                 // Sanitize the url.
5480                 url = sanitizeUrl(url);
5481
5482                 // Handle the URL according to the type.
5483                 if (url.startsWith("http")) {  // Load the URL in Privacy Browser.
5484                     // Load the URL.  By using `loadUrl()`, instead of `loadUrlFromBase()`, the Referer header will never be sent.
5485                     loadUrl(nestedScrollWebView, url);
5486
5487                     // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
5488                     // Custom headers cannot be added if false is returned and the WebView handles the loading of the URL.
5489                     return true;
5490                 } else if (url.startsWith("mailto:")) {  // Load the email address in an external email program.
5491                     // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
5492                     Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
5493
5494                     // Parse the url and set it as the data for the intent.
5495                     emailIntent.setData(Uri.parse(url));
5496
5497                     // Open the email program in a new task instead of as part of Privacy Browser.
5498                     emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5499
5500                     try {
5501                         // Make it so.
5502                         startActivity(emailIntent);
5503                     } catch (ActivityNotFoundException exception) {
5504                         // Display a snackbar.
5505                         Snackbar.make(currentWebView, getString(R.string.error) + "  " + exception, Snackbar.LENGTH_INDEFINITE).show();
5506                     }
5507
5508
5509                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5510                     return true;
5511                 } else if (url.startsWith("tel:")) {  // Load the phone number in the dialer.
5512                     // Open the dialer and load the phone number, but wait for the user to place the call.
5513                     Intent dialIntent = new Intent(Intent.ACTION_DIAL);
5514
5515                     // Add the phone number to the intent.
5516                     dialIntent.setData(Uri.parse(url));
5517
5518                     // Open the dialer in a new task instead of as part of Privacy Browser.
5519                     dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5520
5521                     try {
5522                         // Make it so.
5523                         startActivity(dialIntent);
5524                     } catch (ActivityNotFoundException exception) {
5525                         // Display a snackbar.
5526                         Snackbar.make(currentWebView, getString(R.string.error) + "  " + exception, Snackbar.LENGTH_INDEFINITE).show();
5527                     }
5528
5529                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5530                     return true;
5531                 } else {  // Load a system chooser to select an app that can handle the URL.
5532                     // Open an app that can handle the URL.
5533                     Intent genericIntent = new Intent(Intent.ACTION_VIEW);
5534
5535                     // Add the URL to the intent.
5536                     genericIntent.setData(Uri.parse(url));
5537
5538                     // List all apps that can handle the URL instead of just opening the first one.
5539                     genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
5540
5541                     // Open the app in a new task instead of as part of Privacy Browser.
5542                     genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5543
5544                     // Start the app or display a snackbar if no app is available to handle the URL.
5545                     try {
5546                         startActivity(genericIntent);
5547                     } catch (ActivityNotFoundException exception) {
5548                         Snackbar.make(nestedScrollWebView, getString(R.string.unrecognized_url) + "  " + url, Snackbar.LENGTH_SHORT).show();
5549                     }
5550
5551                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5552                     return true;
5553                 }
5554             }
5555
5556             // Check requests against the block lists.  The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
5557             @Override
5558             public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest webResourceRequest) {
5559                 // Get the URL.
5560                 String url = webResourceRequest.getUrl().toString();
5561
5562                 // Check to see if the resource request is for the main URL.
5563                 if (url.equals(nestedScrollWebView.getCurrentUrl())) {
5564                     // `return null` loads the resource request, which should never be blocked if it is the main URL.
5565                     return null;
5566                 }
5567
5568                 // 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.
5569                 while (ultraPrivacy == null) {
5570                     // The wait must be synchronized, which only lets one thread run on it at a time, or `java.lang.IllegalMonitorStateException` is thrown.
5571                     synchronized (this) {
5572                         try {
5573                             // Check to see if the blocklists have been populated after 100 ms.
5574                             wait(100);
5575                         } catch (InterruptedException exception) {
5576                             // Do nothing.
5577                         }
5578                     }
5579                 }
5580
5581                 // Create an empty web resource response to be used if the resource request is blocked.
5582                 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
5583
5584                 // Reset the whitelist results tracker.
5585                 String[] whitelistResultStringArray = null;
5586
5587                 // Initialize the third party request tracker.
5588                 boolean isThirdPartyRequest = false;
5589
5590                 // Get the current URL.  `.getUrl()` throws an error because operations on the WebView cannot be made from this thread.
5591                 String currentBaseDomain = nestedScrollWebView.getCurrentDomainName();
5592
5593                 // Store a copy of the current domain for use in later requests.
5594                 String currentDomain = currentBaseDomain;
5595
5596                 // Get the request host name.
5597                 String requestBaseDomain = webResourceRequest.getUrl().getHost();
5598
5599                 // Only check for third-party requests if the current base domain is not empty and the request domain is not null.
5600                 if (!currentBaseDomain.isEmpty() && (requestBaseDomain != null)) {
5601                     // Determine the current base domain.
5602                     while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) {  // There is at least one subdomain.
5603                         // Remove the first subdomain.
5604                         currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
5605                     }
5606
5607                     // Determine the request base domain.
5608                     while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) {  // There is at least one subdomain.
5609                         // Remove the first subdomain.
5610                         requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
5611                     }
5612
5613                     // Update the third party request tracker.
5614                     isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
5615                 }
5616
5617                 // Get the current WebView page position.
5618                 int webViewPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5619
5620                 // Determine if the WebView is currently displayed.
5621                 boolean webViewDisplayed = (webViewPagePosition == tabLayout.getSelectedTabPosition());
5622
5623                 // Block third-party requests if enabled.
5624                 if (isThirdPartyRequest && nestedScrollWebView.getBlockAllThirdPartyRequests()) {
5625                     // Add the result to the resource requests.
5626                     nestedScrollWebView.addResourceRequest(new String[]{BlocklistHelper.REQUEST_THIRD_PARTY, url});
5627
5628                     // Increment the blocked requests counters.
5629                     nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5630                     nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS);
5631
5632                     // Update the titles of the blocklist menu items if the WebView is currently displayed.
5633                     if (webViewDisplayed) {
5634                         // Updating the UI must be run from the UI thread.
5635                         activity.runOnUiThread(() -> {
5636                             // Update the menu item titles.
5637                             navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5638
5639                             // Update the options menu if it has been populated.
5640                             if (optionsMenu != null) {
5641                                 optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5642                                 optionsBlockAllThirdPartyRequestsMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " +
5643                                         getString(R.string.block_all_third_party_requests));
5644                             }
5645                         });
5646                     }
5647
5648                     // Return an empty web resource response.
5649                     return emptyWebResourceResponse;
5650                 }
5651
5652                 // Check UltraList if it is enabled.
5653                 if (nestedScrollWebView.getUltraListEnabled()) {
5654                     // Check the URL against UltraList.
5655                     String[] ultraListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraList);
5656
5657                     // Process the UltraList results.
5658                     if (ultraListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) {  // The resource request matched UltraList's blacklist.
5659                         // Add the result to the resource requests.
5660                         nestedScrollWebView.addResourceRequest(new String[] {ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]});
5661
5662                         // Increment the blocked requests counters.
5663                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5664                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRALIST);
5665
5666                         // Update the titles of the blocklist menu items if the WebView is currently displayed.
5667                         if (webViewDisplayed) {
5668                             // Updating the UI must be run from the UI thread.
5669                             activity.runOnUiThread(() -> {
5670                                 // Update the menu item titles.
5671                                 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5672
5673                                 // Update the options menu if it has been populated.
5674                                 if (optionsMenu != null) {
5675                                     optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5676                                     optionsUltraListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRALIST) + " - " + getString(R.string.ultralist));
5677                                 }
5678                             });
5679                         }
5680
5681                         // The resource request was blocked.  Return an empty web resource response.
5682                         return emptyWebResourceResponse;
5683                     } else if (ultraListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) {  // The resource request matched UltraList's whitelist.
5684                         // Add a whitelist entry to the resource requests array.
5685                         nestedScrollWebView.addResourceRequest(new String[] {ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]});
5686
5687                         // The resource request has been allowed by UltraPrivacy.  `return null` loads the requested resource.
5688                         return null;
5689                     }
5690                 }
5691
5692                 // Check UltraPrivacy if it is enabled.
5693                 if (nestedScrollWebView.getUltraPrivacyEnabled()) {
5694                     // Check the URL against UltraPrivacy.
5695                     String[] ultraPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraPrivacy);
5696
5697                     // Process the UltraPrivacy results.
5698                     if (ultraPrivacyResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) {  // The resource request matched UltraPrivacy's blacklist.
5699                         // Add the result to the resource requests.
5700                         nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5701                                 ultraPrivacyResults[5]});
5702
5703                         // Increment the blocked requests counters.
5704                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5705                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRAPRIVACY);
5706
5707                         // Update the titles of the blocklist menu items if the WebView is currently displayed.
5708                         if (webViewDisplayed) {
5709                             // Updating the UI must be run from the UI thread.
5710                             activity.runOnUiThread(() -> {
5711                                 // Update the menu item titles.
5712                                 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5713
5714                                 // Update the options menu if it has been populated.
5715                                 if (optionsMenu != null) {
5716                                     optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5717                                     optionsUltraPrivacyMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRAPRIVACY) + " - " + getString(R.string.ultraprivacy));
5718                                 }
5719                             });
5720                         }
5721
5722                         // The resource request was blocked.  Return an empty web resource response.
5723                         return emptyWebResourceResponse;
5724                     } else if (ultraPrivacyResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) {  // The resource request matched UltraPrivacy's whitelist.
5725                         // Add a whitelist entry to the resource requests array.
5726                         nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5727                                 ultraPrivacyResults[5]});
5728
5729                         // The resource request has been allowed by UltraPrivacy.  `return null` loads the requested resource.
5730                         return null;
5731                     }
5732                 }
5733
5734                 // Check EasyList if it is enabled.
5735                 if (nestedScrollWebView.getEasyListEnabled()) {
5736                     // Check the URL against EasyList.
5737                     String[] easyListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyList);
5738
5739                     // Process the EasyList results.
5740                     if (easyListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) {  // The resource request matched EasyList's blacklist.
5741                         // Add the result to the resource requests.
5742                         nestedScrollWebView.addResourceRequest(new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]});
5743
5744                         // Increment the blocked requests counters.
5745                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5746                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASYLIST);
5747
5748                         // Update the titles of the blocklist menu items if the WebView is currently displayed.
5749                         if (webViewDisplayed) {
5750                             // Updating the UI must be run from the UI thread.
5751                             activity.runOnUiThread(() -> {
5752                                 // Update the menu item titles.
5753                                 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5754
5755                                 // Update the options menu if it has been populated.
5756                                 if (optionsMenu != null) {
5757                                     optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5758                                     optionsEasyListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASYLIST) + " - " + getString(R.string.easylist));
5759                                 }
5760                             });
5761                         }
5762
5763                         // The resource request was blocked.  Return an empty web resource response.
5764                         return emptyWebResourceResponse;
5765                     } else if (easyListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) {  // The resource request matched EasyList's whitelist.
5766                         // Update the whitelist result string array tracker.
5767                         whitelistResultStringArray = new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]};
5768                     }
5769                 }
5770
5771                 // Check EasyPrivacy if it is enabled.
5772                 if (nestedScrollWebView.getEasyPrivacyEnabled()) {
5773                     // Check the URL against EasyPrivacy.
5774                     String[] easyPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyPrivacy);
5775
5776                     // Process the EasyPrivacy results.
5777                     if (easyPrivacyResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) {  // The resource request matched EasyPrivacy's blacklist.
5778                         // Add the result to the resource requests.
5779                         nestedScrollWebView.addResourceRequest(new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4],
5780                                 easyPrivacyResults[5]});
5781
5782                         // Increment the blocked requests counters.
5783                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5784                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASYPRIVACY);
5785
5786                         // Update the titles of the blocklist menu items if the WebView is currently displayed.
5787                         if (webViewDisplayed) {
5788                             // Updating the UI must be run from the UI thread.
5789                             activity.runOnUiThread(() -> {
5790                                 // Update the menu item titles.
5791                                 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5792
5793                                 // Update the options menu if it has been populated.
5794                                 if (optionsMenu != null) {
5795                                     optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5796                                     optionsEasyPrivacyMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASYPRIVACY) + " - " + getString(R.string.easyprivacy));
5797                                 }
5798                             });
5799                         }
5800
5801                         // The resource request was blocked.  Return an empty web resource response.
5802                         return emptyWebResourceResponse;
5803                     } else if (easyPrivacyResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) {  // The resource request matched EasyPrivacy's whitelist.
5804                         // Update the whitelist result string array tracker.
5805                         whitelistResultStringArray = new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5]};
5806                     }
5807                 }
5808
5809                 // Check Fanboy’s Annoyance List if it is enabled.
5810                 if (nestedScrollWebView.getFanboysAnnoyanceListEnabled()) {
5811                     // Check the URL against Fanboy's Annoyance List.
5812                     String[] fanboysAnnoyanceListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList);
5813
5814                     // Process the Fanboy's Annoyance List results.
5815                     if (fanboysAnnoyanceListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) {  // The resource request matched Fanboy's Annoyance List's blacklist.
5816                         // Add the result to the resource requests.
5817                         nestedScrollWebView.addResourceRequest(new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5818                                 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]});
5819
5820                         // Increment the blocked requests counters.
5821                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5822                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST);
5823
5824                         // Update the titles of the blocklist menu items if the WebView is currently displayed.
5825                         if (webViewDisplayed) {
5826                             // Updating the UI must be run from the UI thread.
5827                             activity.runOnUiThread(() -> {
5828                                 // Update the menu item titles.
5829                                 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5830
5831                                 // Update the options menu if it has been populated.
5832                                 if (optionsMenu != null) {
5833                                     optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5834                                     optionsFanboysAnnoyanceListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " +
5835                                             getString(R.string.fanboys_annoyance_list));
5836                                 }
5837                             });
5838                         }
5839
5840                         // The resource request was blocked.  Return an empty web resource response.
5841                         return emptyWebResourceResponse;
5842                     } else if (fanboysAnnoyanceListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)){  // The resource request matched Fanboy's Annoyance List's whitelist.
5843                         // Update the whitelist result string array tracker.
5844                         whitelistResultStringArray = new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5845                                 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]};
5846                     }
5847                 } else if (nestedScrollWebView.getFanboysSocialBlockingListEnabled()) {  // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
5848                     // Check the URL against Fanboy's Annoyance List.
5849                     String[] fanboysSocialListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysSocialList);
5850
5851                     // Process the Fanboy's Social Blocking List results.
5852                     if (fanboysSocialListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) {  // The resource request matched Fanboy's Social Blocking List's blacklist.
5853                         // Add the result to the resource requests.
5854                         nestedScrollWebView.addResourceRequest(new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5855                                 fanboysSocialListResults[4], fanboysSocialListResults[5]});
5856
5857                         // Increment the blocked requests counters.
5858                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5859                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST);
5860
5861                         // Update the titles of the blocklist menu items if the WebView is currently displayed.
5862                         if (webViewDisplayed) {
5863                             // Updating the UI must be run from the UI thread.
5864                             activity.runOnUiThread(() -> {
5865                                 // Update the menu item titles.
5866                                 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5867
5868                                 // Update the options menu if it has been populated.
5869                                 if (optionsMenu != null) {
5870                                     optionsBlocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5871                                     optionsFanboysSocialBlockingListMenuItem.setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " +
5872                                             getString(R.string.fanboys_social_blocking_list));
5873                                 }
5874                             });
5875                         }
5876
5877                         // The resource request was blocked.  Return an empty web resource response.
5878                         return emptyWebResourceResponse;
5879                     } else if (fanboysSocialListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) {  // The resource request matched Fanboy's Social Blocking List's whitelist.
5880                         // Update the whitelist result string array tracker.
5881                         whitelistResultStringArray = new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5882                                 fanboysSocialListResults[4], fanboysSocialListResults[5]};
5883                     }
5884                 }
5885
5886                 // Add the request to the log because it hasn't been processed by any of the previous checks.
5887                 if (whitelistResultStringArray != null) {  // The request was processed by a whitelist.
5888                     nestedScrollWebView.addResourceRequest(whitelistResultStringArray);
5889                 } else {  // The request didn't match any blocklist entry.  Log it as a default request.
5890                     nestedScrollWebView.addResourceRequest(new String[]{BlocklistHelper.REQUEST_DEFAULT, url});
5891                 }
5892
5893                 // The resource request has not been blocked.  `return null` loads the requested resource.
5894                 return null;
5895             }
5896
5897             // Handle HTTP authentication requests.
5898             @Override
5899             public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
5900                 // Store the handler.
5901                 nestedScrollWebView.setHttpAuthHandler(handler);
5902
5903                 // Instantiate an HTTP authentication dialog.
5904                 DialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm, nestedScrollWebView.getWebViewFragmentId());
5905
5906                 // Show the HTTP authentication dialog.
5907                 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
5908             }
5909
5910             @Override
5911             public void onPageStarted(WebView view, String url, Bitmap favicon) {
5912                 // Get the app bar layout height.  This can't be done in `applyAppSettings()` because the app bar is not yet populated there.
5913                 // 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.
5914                 if (appBarLayout.getHeight() > 0) appBarHeight = appBarLayout.getHeight();
5915
5916                 // Set the padding and layout settings according to the position of the app bar.
5917                 if (bottomAppBar) {  // The app bar is on the bottom.
5918                     // Adjust the UI.
5919                     if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) {  // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
5920                         // Reset the WebView padding to fill the available space.
5921                         swipeRefreshLayout.setPadding(0, 0, 0, 0);
5922                     } else {  // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
5923                         // Move the WebView above the app bar layout.
5924                         swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight);
5925                     }
5926                 } else {  // The app bar is on the top.
5927                     // 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.
5928                     if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) {
5929                         // No padding is needed because it will automatically be placed below the app bar layout due to the scrolling layout behavior.
5930                         swipeRefreshLayout.setPadding(0, 0, 0, 0);
5931
5932                         // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5933                         swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10, defaultProgressViewEndOffset);
5934                     } else {
5935                         // The swipe refresh layout must be manually moved below the app bar layout.
5936                         swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0);
5937
5938                         // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5939                         swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight);
5940                     }
5941                 }
5942
5943                 // Reset the list of resource requests.
5944                 nestedScrollWebView.clearResourceRequests();
5945
5946                 // Reset the requests counters.
5947                 nestedScrollWebView.resetRequestsCounters();
5948
5949                 // Get the current page position.
5950                 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5951
5952                 // Update the URL text bar if the page is currently selected and the URL edit text is not currently being edited.
5953                 if ((tabLayout.getSelectedTabPosition() == currentPagePosition) && !urlEditText.hasFocus()) {
5954                     // Display the formatted URL text.
5955                     urlEditText.setText(url);
5956
5957                     // Apply text highlighting to the URL text box.
5958                     highlightUrlText();
5959
5960                     // Hide the keyboard.
5961                     inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
5962                 }
5963
5964                 // Reset the list of host IP addresses.
5965                 nestedScrollWebView.setCurrentIpAddresses("");
5966
5967                 // Get a URI for the current URL.
5968                 Uri currentUri = Uri.parse(url);
5969
5970                 // Get the IP addresses for the host.
5971                 new GetHostIpAddresses(activity, getSupportFragmentManager(), nestedScrollWebView).execute(currentUri.getHost());
5972
5973                 // Replace Refresh with Stop if the options menu has been created.  (The first WebView typically begins loading before the menu items are instantiated.)
5974                 if (optionsMenu != null) {
5975                     // Set the title.
5976                     optionsRefreshMenuItem.setTitle(R.string.stop);
5977
5978                     // Set the icon if it is displayed in the AppBar.
5979                     if (displayAdditionalAppBarIcons)
5980                         optionsRefreshMenuItem.setIcon(R.drawable.close_blue);
5981                 }
5982             }
5983
5984             @Override
5985             public void onPageFinished(WebView view, String url) {
5986                 // Flush any cookies to persistent storage.  The cookie manager has become very lazy about flushing cookies in recent versions.
5987                 if (nestedScrollWebView.getAcceptCookies()) {
5988                     CookieManager.getInstance().flush();
5989                 }
5990
5991                 // Update the Refresh menu item if the options menu has been created.
5992                 if (optionsMenu != null) {
5993                     // Reset the Refresh title.
5994                     optionsRefreshMenuItem.setTitle(R.string.refresh);
5995
5996                     // Reset the icon if it is displayed in the app bar.
5997                     if (displayAdditionalAppBarIcons)
5998                         optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled);
5999                 }
6000
6001                  // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
6002                 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
6003                 String privateDataDirectoryString = getApplicationInfo().dataDir;
6004
6005                 // Clear the cache, history, and logcat if Incognito Mode is enabled.
6006                 if (incognitoModeEnabled) {
6007                     // Clear the cache.  `true` includes disk files.
6008                     nestedScrollWebView.clearCache(true);
6009
6010                     // Clear the back/forward history.
6011                     nestedScrollWebView.clearHistory();
6012
6013                     // Manually delete cache folders.
6014                     try {
6015                         // Delete the main cache directory.
6016                         Runtime.getRuntime().exec("rm -rf " + privateDataDirectoryString + "/cache");
6017                     } catch (IOException exception) {
6018                         // Do nothing if an error is thrown.
6019                     }
6020
6021                     // Clear the logcat.
6022                     try {
6023                         // Clear the logcat.  `-c` clears the logcat.  `-b all` clears all the buffers (instead of just crash, main, and system).
6024                         Runtime.getRuntime().exec("logcat -b all -c");
6025                     } catch (IOException exception) {
6026                         // Do nothing.
6027                     }
6028                 }
6029
6030                 // Clear the `Service Worker` directory.
6031                 try {
6032                     // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
6033                     Runtime.getRuntime().exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Default/Service Worker/"});
6034                 } catch (IOException exception) {
6035                     // Do nothing.
6036                 }
6037
6038                 // Get the current page position.
6039                 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
6040
6041                 // 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.
6042                 String currentUrl = nestedScrollWebView.getUrl();
6043
6044                 // Get the current tab.
6045                 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
6046
6047                 // Update the URL text bar if the page is currently selected and the user is not currently typing in the URL edit text.
6048                 // Crash records show that, in some crazy way, it is possible for the current URL to be blank at this point.
6049                 // Probably some sort of race condition when Privacy Browser is being resumed.
6050                 if ((tabLayout.getSelectedTabPosition() == currentPagePosition) && !urlEditText.hasFocus() && (currentUrl != null)) {
6051                     // Check to see if the URL is `about:blank`.
6052                     if (currentUrl.equals("about:blank")) {  // The WebView is blank.
6053                         // Display the hint in the URL edit text.
6054                         urlEditText.setText("");
6055
6056                         // Request focus for the URL text box.
6057                         urlEditText.requestFocus();
6058
6059                         // Display the keyboard.
6060                         inputMethodManager.showSoftInput(urlEditText, 0);
6061
6062                         // Apply the domain settings.  This clears any settings from the previous domain.
6063                         applyDomainSettings(nestedScrollWebView, "", true, false, false);
6064
6065                         // Only populate the title text view if the tab has been fully created.
6066                         if (tab != null) {
6067                             // Get the custom view from the tab.
6068                             View tabView = tab.getCustomView();
6069
6070                             // Remove the incorrect warning below that the current tab view might be null.
6071                             assert tabView != null;
6072
6073                             // Get the title text view from the tab.
6074                             TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
6075
6076                             // Set the title as the tab text.
6077                             tabTitleTextView.setText(R.string.new_tab);
6078                         }
6079                     } else {  // The WebView has loaded a webpage.
6080                         // Update the URL edit text if it is not currently being edited.
6081                         if (!urlEditText.hasFocus()) {
6082                             // 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.
6083                             String sanitizedUrl = sanitizeUrl(currentUrl);
6084
6085                             // Display the final URL.  Getting the URL from the WebView instead of using the one provided by `onPageFinished()` makes websites like YouTube function correctly.
6086                             urlEditText.setText(sanitizedUrl);
6087
6088                             // Apply text highlighting to the URL.
6089                             highlightUrlText();
6090                         }
6091
6092                         // Only populate the title text view if the tab has been fully created.
6093                         if (tab != null) {
6094                             // Get the custom view from the tab.
6095                             View tabView = tab.getCustomView();
6096
6097                             // Remove the incorrect warning below that the current tab view might be null.
6098                             assert tabView != null;
6099
6100                             // Get the title text view from the tab.
6101                             TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
6102
6103                             // Set the title as the tab text.  Sometimes `onReceivedTitle()` is not called, especially when navigating history.
6104                             tabTitleTextView.setText(nestedScrollWebView.getTitle());
6105                         }
6106                     }
6107                 }
6108             }
6109
6110             // Handle SSL Certificate errors.  Suppress the lint warning that ignoring the error might be dangerous.
6111             @SuppressLint("WebViewClientOnReceivedSslError")
6112             @Override
6113             public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
6114                 // Get the current website SSL certificate.
6115                 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
6116
6117                 // Extract the individual pieces of information from the current website SSL certificate.
6118                 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
6119                 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
6120                 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
6121                 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
6122                 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
6123                 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
6124                 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
6125                 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
6126
6127                 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
6128                 if (nestedScrollWebView.hasPinnedSslCertificate()) {
6129                     // Get the pinned SSL certificate.
6130                     Pair<String[], Date[]> pinnedSslCertificatePair = nestedScrollWebView.getPinnedSslCertificate();
6131
6132                     // Extract the arrays from the array list.
6133                     String[] pinnedSslCertificateStringArray = pinnedSslCertificatePair.getFirst();
6134                     Date[] pinnedSslCertificateDateArray = pinnedSslCertificatePair.getSecond();
6135
6136                     // Check if the current SSL certificate matches the pinned certificate.
6137                     if (currentWebsiteIssuedToCName.equals(pinnedSslCertificateStringArray[0]) && currentWebsiteIssuedToOName.equals(pinnedSslCertificateStringArray[1]) &&
6138                         currentWebsiteIssuedToUName.equals(pinnedSslCertificateStringArray[2]) && currentWebsiteIssuedByCName.equals(pinnedSslCertificateStringArray[3]) &&
6139                         currentWebsiteIssuedByOName.equals(pinnedSslCertificateStringArray[4]) && currentWebsiteIssuedByUName.equals(pinnedSslCertificateStringArray[5]) &&
6140                         currentWebsiteSslStartDate.equals(pinnedSslCertificateDateArray[0]) && currentWebsiteSslEndDate.equals(pinnedSslCertificateDateArray[1])) {
6141
6142                         // An SSL certificate is pinned and matches the current domain certificate.  Proceed to the website without displaying an error.
6143                         handler.proceed();
6144                     }
6145                 } else {  // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
6146                     // Store the SSL error handler.
6147                     nestedScrollWebView.setSslErrorHandler(handler);
6148
6149                     // Instantiate an SSL certificate error alert dialog.
6150                     DialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error, nestedScrollWebView.getWebViewFragmentId());
6151
6152                     // 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.
6153                     try {
6154                         // Show the SSL certificate error dialog.
6155                         sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
6156                     } catch (Exception exception) {
6157                         // Add the dialog to the pending dialog array list.  It will be displayed in `onStart()`.
6158                         pendingDialogsArrayList.add(new PendingDialog(sslCertificateErrorDialogFragment, getString(R.string.ssl_certificate_error)));
6159                     }
6160                 }
6161             }
6162         });
6163
6164         // Check to see if the state is being restored.
6165         if (restoringState) {  // The state is being restored.
6166             // Resume the nested scroll WebView JavaScript timers.
6167             nestedScrollWebView.resumeTimers();
6168         } else if (pageNumber == 0) {  // The first page is being loaded.
6169             // Set this nested scroll WebView as the current WebView.
6170             currentWebView = nestedScrollWebView;
6171
6172             // Initialize the URL to load string.
6173             String urlToLoadString;
6174
6175             // Get the intent that started the app.
6176             Intent launchingIntent = getIntent();
6177
6178             // Reset the intent.  This prevents a duplicate tab from being created on restart.
6179             setIntent(new Intent());
6180
6181             // Get the information from the intent.
6182             String launchingIntentAction = launchingIntent.getAction();
6183             Uri launchingIntentUriData = launchingIntent.getData();
6184             String launchingIntentStringExtra = launchingIntent.getStringExtra(Intent.EXTRA_TEXT);
6185
6186             // Parse the launching intent URL.
6187             if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) {  // The intent contains a search string.
6188                 // Create an encoded URL string.
6189                 String encodedUrlString;
6190
6191                 // Sanitize the search input and convert it to a search.
6192                 try {
6193                     encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
6194                 } catch (UnsupportedEncodingException exception) {
6195                     encodedUrlString = "";
6196                 }
6197
6198                 // Store the web search as the URL to load.
6199                 urlToLoadString = searchURL + encodedUrlString;
6200             } else if (launchingIntentUriData != null) {  // The launching intent contains a URL formatted as a URI.
6201                 // Store the URI as a URL.
6202                 urlToLoadString = launchingIntentUriData.toString();
6203             } else if (launchingIntentStringExtra != null) {  // The launching intent contains text that might be a URL.
6204                 // Store the URL.
6205                 urlToLoadString = launchingIntentStringExtra;
6206             } else if (!url.equals("")) {  // The activity has been restarted.
6207                 // Load the saved URL.
6208                 urlToLoadString = url;
6209             } else {  // The is no URL in the intent.
6210                 // Store the homepage to be loaded.
6211                 urlToLoadString = sharedPreferences.getString("homepage", getString(R.string.homepage_default_value));
6212             }
6213
6214             // Load the website if not waiting for the proxy.
6215             if (waitingForProxy) {  // Store the URL to be loaded in the Nested Scroll WebView.
6216                 nestedScrollWebView.setWaitingForProxyUrlString(urlToLoadString);
6217             } else {  // Load the URL.
6218                 loadUrl(nestedScrollWebView, urlToLoadString);
6219             }
6220
6221             // 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.
6222             // 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.
6223             setIntent(new Intent());
6224         } else {  // This is not the first tab.
6225             // Load the URL.
6226             loadUrl(nestedScrollWebView, url);
6227
6228             // Set the focus and display the keyboard if the URL is blank.
6229             if (url.equals("")) {
6230                 // Request focus for the URL text box.
6231                 urlEditText.requestFocus();
6232
6233                 // Create a display keyboard handler.
6234                 Handler displayKeyboardHandler = new Handler();
6235
6236                 // Create a display keyboard runnable.
6237                 Runnable displayKeyboardRunnable = () -> {
6238                     // Display the keyboard.
6239                     inputMethodManager.showSoftInput(urlEditText, 0);
6240                 };
6241
6242                 // Display the keyboard after 100 milliseconds, which leaves enough time for the tab to transition.
6243                 displayKeyboardHandler.postDelayed(displayKeyboardRunnable, 100);
6244             }
6245         }
6246     }
6247 }