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