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