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