]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/activities/MainWebViewActivity.java
Add an open option on download completion. https://redmine.stoutner.com/issues/533
[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         //Only process the results if they exist (this method is triggered when a dialog is presented the first time for an app, but no grant results are included).
3121         if (grantResults.length > 0) {
3122             switch (requestCode) {
3123                 case PERMISSION_OPEN_REQUEST_CODE:
3124                     // Check to see if the storage permission was granted.  If the dialog was canceled the grant results will be empty.
3125                     if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {  // The storage permission was granted.
3126                         // Load the file.
3127                         currentWebView.loadUrl("file://" + openFilePath);
3128                     } else {  // The storage permission was not granted.
3129                         // Display an error snackbar.
3130                         Snackbar.make(currentWebView, getString(R.string.cannot_use_location), Snackbar.LENGTH_LONG).show();
3131                     }
3132
3133                     // Reset the open file path.
3134                     openFilePath = "";
3135                     break;
3136
3137                 case PERMISSION_SAVE_URL_REQUEST_CODE:
3138                     // Check to see if the storage permission was granted.  If the dialog was canceled the grant results will be empty.
3139                     if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {  // The storage permission was granted.
3140                         // Save the raw URL.
3141                         new SaveUrl(this, this, saveWebpageFilePath, currentWebView.getSettings().getUserAgentString(), currentWebView.getAcceptFirstPartyCookies()).execute(saveWebpageUrl);
3142                     } else {  // The storage permission was not granted.
3143                         // Display an error snackbar.
3144                         Snackbar.make(currentWebView, getString(R.string.cannot_use_location), Snackbar.LENGTH_LONG).show();
3145                     }
3146
3147                     // Reset the save strings.
3148                     saveWebpageUrl = "";
3149                     saveWebpageFilePath = "";
3150                     break;
3151
3152                 case PERMISSION_SAVE_AS_ARCHIVE_REQUEST_CODE:
3153                     // Check to see if the storage permission was granted.  If the dialog was canceled the grant results will be empty.
3154                     if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {  // The storage permission was granted.
3155                         // Save the webpage archive.
3156                         currentWebView.saveWebArchive(saveWebpageFilePath);
3157                     } else {  // The storage permission was not granted.
3158                         // Display an error snackbar.
3159                         Snackbar.make(currentWebView, getString(R.string.cannot_use_location), Snackbar.LENGTH_LONG).show();
3160                     }
3161
3162                     // Reset the save webpage file path.
3163                     saveWebpageFilePath = "";
3164                     break;
3165
3166                 case PERMISSION_SAVE_AS_IMAGE_REQUEST_CODE:
3167                     // Check to see if the storage permission was granted.  If the dialog was canceled the grant results will be empty.
3168                     if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {  // The storage permission was granted.
3169                         // Save the webpage image.
3170                         new SaveWebpageImage(this, currentWebView).execute(saveWebpageFilePath);
3171                     } else {  // The storage permission was not granted.
3172                         // Display an error snackbar.
3173                         Snackbar.make(currentWebView, getString(R.string.cannot_use_location), Snackbar.LENGTH_LONG).show();
3174                     }
3175
3176                     // Reset the save webpage file path.
3177                     saveWebpageFilePath = "";
3178                     break;
3179             }
3180         }
3181     }
3182
3183     private void applyAppSettings() {
3184         // 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.
3185         if (webViewDefaultUserAgent == null) {
3186             initializeApp();
3187         }
3188
3189         // Get a handle for the shared preferences.
3190         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3191
3192         // Store the values from the shared preferences in variables.
3193         incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3194         boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3195         sanitizeGoogleAnalytics = sharedPreferences.getBoolean("google_analytics", true);
3196         sanitizeFacebookClickIds = sharedPreferences.getBoolean("facebook_click_ids", true);
3197         sanitizeTwitterAmpRedirects = sharedPreferences.getBoolean("twitter_amp_redirects", true);
3198         proxyMode = sharedPreferences.getString("proxy", getString(R.string.proxy_default_value));
3199         fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3200         hideAppBar = sharedPreferences.getBoolean("hide_app_bar", true);
3201         scrollAppBar = sharedPreferences.getBoolean("scroll_app_bar", true);
3202
3203         // Get the search string.
3204         String searchString = sharedPreferences.getString("search", getString(R.string.search_default_value));
3205
3206         // Set the search string.
3207         if (searchString.equals("Custom URL")) {  // A custom search string is used.
3208             searchURL = sharedPreferences.getString("search_custom_url", getString(R.string.search_custom_url_default_value));
3209         } else {  // A custom search string is not used.
3210             searchURL = searchString;
3211         }
3212
3213         // Get handles for the views that need to be modified.
3214         FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
3215         AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
3216         ActionBar actionBar = getSupportActionBar();
3217         Toolbar toolbar = findViewById(R.id.toolbar);
3218         LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
3219         LinearLayout tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
3220         SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
3221
3222         // Remove the incorrect lint warning below that the action bar might be null.
3223         assert actionBar != null;
3224
3225         // Apply the proxy.
3226         applyProxy(false);
3227
3228         // Set Do Not Track status.
3229         if (doNotTrackEnabled) {
3230             customHeaders.put("DNT", "1");
3231         } else {
3232             customHeaders.remove("DNT");
3233         }
3234
3235         // Get the current layout parameters.  Using coordinator layout parameters allows the `setBehavior()` command and using app bar layout parameters allows the `setScrollFlags()` command.
3236         CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
3237         AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) toolbar.getLayoutParams();
3238         AppBarLayout.LayoutParams findOnPageLayoutParams = (AppBarLayout.LayoutParams) findOnPageLinearLayout.getLayoutParams();
3239         AppBarLayout.LayoutParams tabsLayoutParams = (AppBarLayout.LayoutParams) tabsLinearLayout.getLayoutParams();
3240
3241         // Add the scrolling behavior to the layout parameters.
3242         if (scrollAppBar) {
3243             // Enable scrolling of the app bar.
3244             swipeRefreshLayoutParams.setBehavior(new AppBarLayout.ScrollingViewBehavior());
3245             toolbarLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3246             findOnPageLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3247             tabsLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3248         } else {
3249             // Disable scrolling of the app bar.
3250             swipeRefreshLayoutParams.setBehavior(null);
3251             toolbarLayoutParams.setScrollFlags(0);
3252             findOnPageLayoutParams.setScrollFlags(0);
3253             tabsLayoutParams.setScrollFlags(0);
3254
3255             // Expand the app bar if it is currently collapsed.
3256             appBarLayout.setExpanded(true);
3257         }
3258
3259         // Apply the modified layout parameters.
3260         swipeRefreshLayout.setLayoutParams(swipeRefreshLayoutParams);
3261         toolbar.setLayoutParams(toolbarLayoutParams);
3262         findOnPageLinearLayout.setLayoutParams(findOnPageLayoutParams);
3263         tabsLinearLayout.setLayoutParams(tabsLayoutParams);
3264
3265         // Set the app bar scrolling for each WebView.
3266         for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3267             // Get the WebView tab fragment.
3268             WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3269
3270             // Get the fragment view.
3271             View fragmentView = webViewTabFragment.getView();
3272
3273             // Only modify the WebViews if they exist.
3274             if (fragmentView != null) {
3275                 // Get the nested scroll WebView from the tab fragment.
3276                 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3277
3278                 // Set the app bar scrolling.
3279                 nestedScrollWebView.setNestedScrollingEnabled(scrollAppBar);
3280             }
3281         }
3282
3283         // Update the full screen browsing mode settings.
3284         if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {  // Privacy Browser is currently in full screen browsing mode.
3285             // Update the visibility of the app bar, which might have changed in the settings.
3286             if (hideAppBar) {
3287                 // Hide the tab linear layout.
3288                 tabsLinearLayout.setVisibility(View.GONE);
3289
3290                 // Hide the action bar.
3291                 actionBar.hide();
3292             } else {
3293                 // Show the tab linear layout.
3294                 tabsLinearLayout.setVisibility(View.VISIBLE);
3295
3296                 // Show the action bar.
3297                 actionBar.show();
3298             }
3299
3300             // Hide the banner ad in the free flavor.
3301             if (BuildConfig.FLAVOR.contentEquals("free")) {
3302                 AdHelper.hideAd(findViewById(R.id.adview));
3303             }
3304
3305             // Remove the translucent status flag.  This is necessary so the root frame layout can fill the entire screen.
3306             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3307
3308             /* Hide the system bars.
3309              * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3310              * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
3311              * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3312              * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3313              */
3314             rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
3315                     View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3316         } else {  // Privacy Browser is not in full screen browsing mode.
3317             // 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.
3318             inFullScreenBrowsingMode = false;
3319
3320             // Show the tab linear layout.
3321             tabsLinearLayout.setVisibility(View.VISIBLE);
3322
3323             // Show the action bar.
3324             actionBar.show();
3325
3326             // Show the banner ad in the free flavor.
3327             if (BuildConfig.FLAVOR.contentEquals("free")) {
3328                 // Initialize the ads.  If this isn't the first run, `loadAd()` will be automatically called instead.
3329                 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getSupportFragmentManager(), getString(R.string.google_app_id), getString(R.string.ad_unit_id));
3330             }
3331
3332             // Remove the `SYSTEM_UI` flags from the root frame layout.
3333             rootFrameLayout.setSystemUiVisibility(0);
3334
3335             // Add the translucent status flag.
3336             getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3337         }
3338     }
3339
3340     private void initializeApp() {
3341         // Get a handle for the shared preferences.
3342         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3343
3344         // Get the theme preference.
3345         boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
3346
3347         // Get a handle for the input method.
3348         InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
3349
3350         // Remove the lint warning below that the input method manager might be null.
3351         assert inputMethodManager != null;
3352
3353         // Initialize the foreground color spans for highlighting the URLs.  We have to use the deprecated `getColor()` until API >= 23.
3354         redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
3355         initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
3356         finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
3357
3358         // Get handles for the URL views.
3359         EditText urlEditText = findViewById(R.id.url_edittext);
3360
3361         // Remove the formatting from the URL edit text when the user is editing the text.
3362         urlEditText.setOnFocusChangeListener((View v, boolean hasFocus) -> {
3363             if (hasFocus) {  // The user is editing the URL text box.
3364                 // Remove the highlighting.
3365                 urlEditText.getText().removeSpan(redColorSpan);
3366                 urlEditText.getText().removeSpan(initialGrayColorSpan);
3367                 urlEditText.getText().removeSpan(finalGrayColorSpan);
3368             } else {  // The user has stopped editing the URL text box.
3369                 // Move to the beginning of the string.
3370                 urlEditText.setSelection(0);
3371
3372                 // Reapply the highlighting.
3373                 highlightUrlText();
3374             }
3375         });
3376
3377         // Set the go button on the keyboard to load the URL in `urlTextBox`.
3378         urlEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
3379             // If the event is a key-down event on the `enter` button, load the URL.
3380             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
3381                 // Load the URL into the mainWebView and consume the event.
3382                 loadUrlFromTextBox();
3383
3384                 // If the enter key was pressed, consume the event.
3385                 return true;
3386             } else {
3387                 // If any other key was pressed, do not consume the event.
3388                 return false;
3389             }
3390         });
3391
3392         // Create an Orbot status broadcast receiver.
3393         orbotStatusBroadcastReceiver = new BroadcastReceiver() {
3394             @Override
3395             public void onReceive(Context context, Intent intent) {
3396                 // Store the content of the status message in `orbotStatus`.
3397                 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
3398
3399                 // If Privacy Browser is waiting on the proxy, load the website now that Orbot is connected.
3400                 if ((orbotStatus != null) && orbotStatus.equals("ON") && waitingForProxy) {
3401                     // Reset the waiting for proxy status.
3402                     waitingForProxy = false;
3403
3404                     // Get a handle for the waiting for proxy dialog.
3405                     DialogFragment waitingForProxyDialogFragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.waiting_for_proxy_dialog));
3406
3407                     // Dismiss the waiting for proxy dialog if it is displayed.
3408                     if (waitingForProxyDialogFragment != null) {
3409                         waitingForProxyDialogFragment.dismiss();
3410                     }
3411
3412                     // Reload existing URLs and load any URLs that are waiting for the proxy.
3413                     for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3414                         // Get the WebView tab fragment.
3415                         WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3416
3417                         // Get the fragment view.
3418                         View fragmentView = webViewTabFragment.getView();
3419
3420                         // Only process the WebViews if they exist.
3421                         if (fragmentView != null) {
3422                             // Get the nested scroll WebView from the tab fragment.
3423                             NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3424
3425                             // Get the waiting for proxy URL string.
3426                             String waitingForProxyUrlString = nestedScrollWebView.getWaitingForProxyUrlString();
3427
3428                             // Load the pending URL if it exists.
3429                             if (!waitingForProxyUrlString.isEmpty()) {  // A URL is waiting to be loaded.
3430                                 // Load the URL.
3431                                 loadUrl(nestedScrollWebView, waitingForProxyUrlString);
3432
3433                                 // Reset the waiting for proxy URL string.
3434                                 nestedScrollWebView.resetWaitingForProxyUrlString();
3435                             } else {  // No URL is waiting to be loaded.
3436                                 // Reload the existing URL.
3437                                 nestedScrollWebView.reload();
3438                             }
3439                         }
3440                     }
3441                 }
3442             }
3443         };
3444
3445         // Register the Orbot status broadcast receiver on `this` context.
3446         this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
3447
3448         // Get handles for views that need to be modified.
3449         DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
3450         NavigationView navigationView = findViewById(R.id.navigationview);
3451         TabLayout tabLayout = findViewById(R.id.tablayout);
3452         SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
3453         ViewPager webViewPager = findViewById(R.id.webviewpager);
3454         ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
3455         FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
3456         FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
3457         FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
3458         EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
3459
3460         // Listen for touches on the navigation menu.
3461         navigationView.setNavigationItemSelectedListener(this);
3462
3463         // Get handles for the navigation menu and the back and forward menu items.  The menu is 0 based.
3464         Menu navigationMenu = navigationView.getMenu();
3465         MenuItem navigationBackMenuItem = navigationMenu.getItem(2);
3466         MenuItem navigationForwardMenuItem = navigationMenu.getItem(3);
3467         MenuItem navigationHistoryMenuItem = navigationMenu.getItem(4);
3468         MenuItem navigationRequestsMenuItem = navigationMenu.getItem(6);
3469
3470         // Update the web view pager every time a tab is modified.
3471         webViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
3472             @Override
3473             public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
3474                 // Do nothing.
3475             }
3476
3477             @Override
3478             public void onPageSelected(int position) {
3479                 // Close the find on page bar if it is open.
3480                 closeFindOnPage(null);
3481
3482                 // Set the current WebView.
3483                 setCurrentWebView(position);
3484
3485                 // 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.
3486                 if (tabLayout.getSelectedTabPosition() != position) {
3487                     // Create a handler to select the tab.
3488                     Handler selectTabHandler = new Handler();
3489
3490                     // Create a runnable to select the tab.
3491                     Runnable selectTabRunnable = () -> {
3492                         // Get a handle for the tab.
3493                         TabLayout.Tab tab = tabLayout.getTabAt(position);
3494
3495                         // Assert that the tab is not null.
3496                         assert tab != null;
3497
3498                         // Select the tab.
3499                         tab.select();
3500                     };
3501
3502                     // Select the tab layout after 150 milliseconds, which leaves enough time for a new tab to be inflated.
3503                     selectTabHandler.postDelayed(selectTabRunnable, 150);
3504                 }
3505             }
3506
3507             @Override
3508             public void onPageScrollStateChanged(int state) {
3509                 // Do nothing.
3510             }
3511         });
3512
3513         // Display the View SSL Certificate dialog when the currently selected tab is reselected.
3514         tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
3515             @Override
3516             public void onTabSelected(TabLayout.Tab tab) {
3517                 // Select the same page in the view pager.
3518                 webViewPager.setCurrentItem(tab.getPosition());
3519             }
3520
3521             @Override
3522             public void onTabUnselected(TabLayout.Tab tab) {
3523                 // Do nothing.
3524             }
3525
3526             @Override
3527             public void onTabReselected(TabLayout.Tab tab) {
3528                 // Instantiate the View SSL Certificate dialog.
3529                 DialogFragment viewSslCertificateDialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView.getWebViewFragmentId());
3530
3531                 // Display the View SSL Certificate dialog.
3532                 viewSslCertificateDialogFragment.show(getSupportFragmentManager(), getString(R.string.view_ssl_certificate));
3533             }
3534         });
3535
3536         // 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.
3537         // The deprecated `getResources().getDrawable()` must be used until the minimum API >= 21 and and `getResources().getColor()` must be used until the minimum API >= 23.
3538         if (darkTheme) {
3539             launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
3540             createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
3541             createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
3542             bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
3543         } else {
3544             launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
3545             createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
3546             createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
3547             bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
3548         }
3549
3550         // Set the launch bookmarks activity FAB to launch the bookmarks activity.
3551         launchBookmarksActivityFab.setOnClickListener(v -> {
3552             // Get a copy of the favorite icon bitmap.
3553             Bitmap favoriteIconBitmap = currentWebView.getFavoriteOrDefaultIcon();
3554
3555             // Create a favorite icon byte array output stream.
3556             ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3557
3558             // Convert the favorite icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
3559             favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
3560
3561             // Convert the favorite icon byte array stream to a byte array.
3562             byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
3563
3564             // Create an intent to launch the bookmarks activity.
3565             Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
3566
3567             // Add the extra information to the intent.
3568             bookmarksIntent.putExtra("current_url", currentWebView.getUrl());
3569             bookmarksIntent.putExtra("current_title", currentWebView.getTitle());
3570             bookmarksIntent.putExtra("current_folder", currentBookmarksFolder);
3571             bookmarksIntent.putExtra("favorite_icon_byte_array", favoriteIconByteArray);
3572
3573             // Make it so.
3574             startActivity(bookmarksIntent);
3575         });
3576
3577         // Set the create new bookmark folder FAB to display an alert dialog.
3578         createBookmarkFolderFab.setOnClickListener(v -> {
3579             // Create a create bookmark folder dialog.
3580             DialogFragment createBookmarkFolderDialog = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView.getFavoriteOrDefaultIcon());
3581
3582             // Show the create bookmark folder dialog.
3583             createBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.create_folder));
3584         });
3585
3586         // Set the create new bookmark FAB to display an alert dialog.
3587         createBookmarkFab.setOnClickListener(view -> {
3588             // Instantiate the create bookmark dialog.
3589             DialogFragment createBookmarkDialog = CreateBookmarkDialog.createBookmark(currentWebView.getUrl(), currentWebView.getTitle(), currentWebView.getFavoriteOrDefaultIcon());
3590
3591             // Display the create bookmark dialog.
3592             createBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.create_bookmark));
3593         });
3594
3595         // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
3596         findOnPageEditText.addTextChangedListener(new TextWatcher() {
3597             @Override
3598             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
3599                 // Do nothing.
3600             }
3601
3602             @Override
3603             public void onTextChanged(CharSequence s, int start, int before, int count) {
3604                 // Do nothing.
3605             }
3606
3607             @Override
3608             public void afterTextChanged(Editable s) {
3609                 // 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.
3610                 if (currentWebView != null) {
3611                     currentWebView.findAllAsync(findOnPageEditText.getText().toString());
3612                 }
3613             }
3614         });
3615
3616         // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
3617         findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
3618             if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {  // The `enter` key was pressed.
3619                 // Hide the soft keyboard.
3620                 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3621
3622                 // Consume the event.
3623                 return true;
3624             } else {  // A different key was pressed.
3625                 // Do not consume the event.
3626                 return false;
3627             }
3628         });
3629
3630         // Implement swipe to refresh.
3631         swipeRefreshLayout.setOnRefreshListener(() -> currentWebView.reload());
3632
3633         // Store the default progress view offsets for use later in `initializeWebView()`.
3634         defaultProgressViewStartOffset = swipeRefreshLayout.getProgressViewStartOffset();
3635         defaultProgressViewEndOffset = swipeRefreshLayout.getProgressViewEndOffset();
3636
3637         // Set the swipe to refresh color according to the theme.
3638         if (darkTheme) {
3639             swipeRefreshLayout.setColorSchemeResources(R.color.blue_800);
3640             swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.gray_850);
3641         } else {
3642             swipeRefreshLayout.setColorSchemeResources(R.color.blue_500);
3643         }
3644
3645         // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
3646         drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
3647         drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
3648
3649         // Initialize the bookmarks database helper.  The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
3650         bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
3651
3652         // Initialize `currentBookmarksFolder`.  `""` is the home folder in the database.
3653         currentBookmarksFolder = "";
3654
3655         // Load the home folder, which is `""` in the database.
3656         loadBookmarksFolder();
3657
3658         bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
3659             // Convert the id from long to int to match the format of the bookmarks database.
3660             int databaseId = (int) id;
3661
3662             // Get the bookmark cursor for this ID.
3663             Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseId);
3664
3665             // Move the bookmark cursor to the first row.
3666             bookmarkCursor.moveToFirst();
3667
3668             // Act upon the bookmark according to the type.
3669             if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {  // The selected bookmark is a folder.
3670                 // Store the new folder name in `currentBookmarksFolder`.
3671                 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3672
3673                 // Load the new folder.
3674                 loadBookmarksFolder();
3675             } else {  // The selected bookmark is not a folder.
3676                 // Load the bookmark URL.
3677                 loadUrl(currentWebView, bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
3678
3679                 // Close the bookmarks drawer.
3680                 drawerLayout.closeDrawer(GravityCompat.END);
3681             }
3682
3683             // Close the `Cursor`.
3684             bookmarkCursor.close();
3685         });
3686
3687         bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
3688             // Convert the database ID from `long` to `int`.
3689             int databaseId = (int) id;
3690
3691             // Find out if the selected bookmark is a folder.
3692             boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
3693
3694             if (isFolder) {
3695                 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
3696                 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3697
3698                 // Instantiate the edit folder bookmark dialog.
3699                 DialogFragment editBookmarkFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
3700
3701                 // Show the edit folder bookmark dialog.
3702                 editBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.edit_folder));
3703             } else {
3704                 // Get the bookmark cursor for this ID.
3705                 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseId);
3706
3707                 // Move the bookmark cursor to the first row.
3708                 bookmarkCursor.moveToFirst();
3709
3710                 // Load the bookmark in a new tab but do not switch to the tab or close the drawer.
3711                 addNewTab(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)), false);
3712             }
3713
3714             // Consume the event.
3715             return true;
3716         });
3717
3718         // Get the status bar pixel size.
3719         int statusBarResourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
3720         int statusBarPixelSize = getResources().getDimensionPixelSize(statusBarResourceId);
3721
3722         // Get the resource density.
3723         float screenDensity = getResources().getDisplayMetrics().density;
3724
3725         // Calculate the drawer header padding.  This is used to move the text in the drawer headers below any cutouts.
3726         drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
3727         drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
3728         drawerHeaderPaddingBottom = (int) (8 * screenDensity);
3729
3730         // The drawer listener is used to update the navigation menu.
3731         drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
3732             @Override
3733             public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
3734             }
3735
3736             @Override
3737             public void onDrawerOpened(@NonNull View drawerView) {
3738             }
3739
3740             @Override
3741             public void onDrawerClosed(@NonNull View drawerView) {
3742             }
3743
3744             @Override
3745             public void onDrawerStateChanged(int newState) {
3746                 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) {  // A drawer is opening or closing.
3747                     // Get handles for the drawer headers.
3748                     TextView navigationHeaderTextView = findViewById(R.id.navigationText);
3749                     TextView bookmarksHeaderTextView = findViewById(R.id.bookmarks_title_textview);
3750
3751                     // 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.
3752                     if (navigationHeaderTextView != null) {
3753                         navigationHeaderTextView.setPadding(drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingTop, drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingBottom);
3754                     }
3755
3756                     // 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.
3757                     if (bookmarksHeaderTextView != null) {
3758                         bookmarksHeaderTextView.setPadding(drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingTop, drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingBottom);
3759                     }
3760
3761                     // Update the navigation menu items if the WebView is not null.
3762                     if (currentWebView != null) {
3763                         navigationBackMenuItem.setEnabled(currentWebView.canGoBack());
3764                         navigationForwardMenuItem.setEnabled(currentWebView.canGoForward());
3765                         navigationHistoryMenuItem.setEnabled((currentWebView.canGoBack() || currentWebView.canGoForward()));
3766                         navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
3767
3768                         // Hide the keyboard (if displayed).
3769                         inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3770                     }
3771
3772                     // 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.
3773                     urlEditText.clearFocus();
3774                     currentWebView.clearFocus();
3775                 }
3776             }
3777         });
3778
3779         // 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).
3780         customHeaders.put("X-Requested-With", "");
3781
3782         // Inflate a bare WebView to get the default user agent.  It is not used to render content on the screen.
3783         @SuppressLint("InflateParams") View webViewLayout = getLayoutInflater().inflate(R.layout.bare_webview, null, false);
3784
3785         // Get a handle for the WebView.
3786         WebView bareWebView = webViewLayout.findViewById(R.id.bare_webview);
3787
3788         // Store the default user agent.
3789         webViewDefaultUserAgent = bareWebView.getSettings().getUserAgentString();
3790
3791         // Destroy the bare WebView.
3792         bareWebView.destroy();
3793     }
3794
3795     @Override
3796     public void navigateHistory(String url, int steps) {
3797         // Apply the domain settings.
3798         applyDomainSettings(currentWebView, url, false, false);
3799
3800         // Load the history entry.
3801         currentWebView.goBackOrForward(steps);
3802     }
3803
3804     @Override
3805     public void pinnedErrorGoBack() {
3806         // Get the current web back forward list.
3807         WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
3808
3809         // Get the previous entry URL.
3810         String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
3811
3812         // Apply the domain settings.
3813         applyDomainSettings(currentWebView, previousUrl, false, false);
3814
3815         // Go back.
3816         currentWebView.goBack();
3817     }
3818
3819     // `reloadWebsite` is used if returning from the Domains activity.  Otherwise JavaScript might not function correctly if it is newly enabled.
3820     @SuppressLint("SetJavaScriptEnabled")
3821     private boolean applyDomainSettings(NestedScrollWebView nestedScrollWebView, String url, boolean resetTab, boolean reloadWebsite) {
3822         // Store a copy of the current user agent to track changes for the return boolean.
3823         String initialUserAgent = nestedScrollWebView.getSettings().getUserAgentString();
3824
3825         // Store the current URL.
3826         nestedScrollWebView.setCurrentUrl(url);
3827
3828         // Parse the URL into a URI.
3829         Uri uri = Uri.parse(url);
3830
3831         // Extract the domain from `uri`.
3832         String newHostName = uri.getHost();
3833
3834         // Strings don't like to be null.
3835         if (newHostName == null) {
3836             newHostName = "";
3837         }
3838
3839         // 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.
3840         if (!nestedScrollWebView.getCurrentDomainName().equals(newHostName) || newHostName.equals("")) {
3841             // Set the new host name as the current domain name.
3842             nestedScrollWebView.setCurrentDomainName(newHostName);
3843
3844             // Reset the ignoring of pinned domain information.
3845             nestedScrollWebView.setIgnorePinnedDomainInformation(false);
3846
3847             // Clear any pinned SSL certificate or IP addresses.
3848             nestedScrollWebView.clearPinnedSslCertificate();
3849             nestedScrollWebView.clearPinnedIpAddresses();
3850
3851             // Reset the favorite icon if specified.
3852             if (resetTab) {
3853                 // Initialize the favorite icon.
3854                 nestedScrollWebView.initializeFavoriteIcon();
3855
3856                 // Get the current page position.
3857                 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
3858
3859                 // Get a handle for the tab layout.
3860                 TabLayout tabLayout = findViewById(R.id.tablayout);
3861
3862                 // Get the corresponding tab.
3863                 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
3864
3865                 // Update the tab if it isn't null, which sometimes happens when restarting from the background.
3866                 if (tab != null) {
3867                     // Get the tab custom view.
3868                     View tabCustomView = tab.getCustomView();
3869
3870                     // Remove the warning below that the tab custom view might be null.
3871                     assert tabCustomView != null;
3872
3873                     // Get the tab views.
3874                     ImageView tabFavoriteIconImageView = tabCustomView.findViewById(R.id.favorite_icon_imageview);
3875                     TextView tabTitleTextView = tabCustomView.findViewById(R.id.title_textview);
3876
3877                     // Set the default favorite icon as the favorite icon for this tab.
3878                     tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nestedScrollWebView.getFavoriteOrDefaultIcon(), 64, 64, true));
3879
3880                     // Set the loading title text.
3881                     tabTitleTextView.setText(R.string.loading);
3882                 }
3883             }
3884
3885             // Initialize the database handler.  The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3886             DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3887
3888             // Get a full cursor from `domainsDatabaseHelper`.
3889             Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3890
3891             // Initialize `domainSettingsSet`.
3892             Set<String> domainSettingsSet = new HashSet<>();
3893
3894             // Get the domain name column index.
3895             int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3896
3897             // Populate `domainSettingsSet`.
3898             for (int i = 0; i < domainNameCursor.getCount(); i++) {
3899                 // Move `domainsCursor` to the current row.
3900                 domainNameCursor.moveToPosition(i);
3901
3902                 // Store the domain name in `domainSettingsSet`.
3903                 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3904             }
3905
3906             // Close `domainNameCursor.
3907             domainNameCursor.close();
3908
3909             // Initialize the domain name in database variable.
3910             String domainNameInDatabase = null;
3911
3912             // Check the hostname against the domain settings set.
3913             if (domainSettingsSet.contains(newHostName)) {  // The hostname is contained in the domain settings set.
3914                 // Record the domain name in the database.
3915                 domainNameInDatabase = newHostName;
3916
3917                 // Set the domain settings applied tracker to true.
3918                 nestedScrollWebView.setDomainSettingsApplied(true);
3919             } else {  // The hostname is not contained in the domain settings set.
3920                 // Set the domain settings applied tracker to false.
3921                 nestedScrollWebView.setDomainSettingsApplied(false);
3922             }
3923
3924             // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3925             while (!nestedScrollWebView.getDomainSettingsApplied() && newHostName.contains(".")) {  // Stop checking if domain settings are already applied or there are no more `.` in the host name.
3926                 if (domainSettingsSet.contains("*." + newHostName)) {  // Check the host name prepended by `*.`.
3927                     // Set the domain settings applied tracker to true.
3928                     nestedScrollWebView.setDomainSettingsApplied(true);
3929
3930                     // Store the applied domain names as it appears in the database.
3931                     domainNameInDatabase = "*." + newHostName;
3932                 }
3933
3934                 // Strip out the lowest subdomain of of the host name.
3935                 newHostName = newHostName.substring(newHostName.indexOf(".") + 1);
3936             }
3937
3938
3939             // Get a handle for the shared preferences.
3940             SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3941
3942             // Store the general preference information.
3943             String defaultFontSizeString = sharedPreferences.getString("font_size", getString(R.string.font_size_default_value));
3944             String defaultUserAgentName = sharedPreferences.getString("user_agent", getString(R.string.user_agent_default_value));
3945             boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
3946             boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
3947             boolean wideViewport = sharedPreferences.getBoolean("wide_viewport", true);
3948             boolean displayWebpageImages = sharedPreferences.getBoolean("display_webpage_images", true);
3949
3950             // Get a handle for the cookie manager.
3951             CookieManager cookieManager = CookieManager.getInstance();
3952
3953             // Get handles for the views.
3954             RelativeLayout urlRelativeLayout = findViewById(R.id.url_relativelayout);
3955             SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
3956
3957             // Initialize the user agent array adapter and string array.
3958             ArrayAdapter<CharSequence> userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item);
3959             String[] userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
3960
3961             if (nestedScrollWebView.getDomainSettingsApplied()) {  // The url has custom domain settings.
3962                 // Get a cursor for the current host and move it to the first position.
3963                 Cursor currentDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3964                 currentDomainSettingsCursor.moveToFirst();
3965
3966                 // Get the settings from the cursor.
3967                 nestedScrollWebView.setDomainSettingsDatabaseId(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3968                 nestedScrollWebView.setDomainSettingsJavaScriptEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3969                 nestedScrollWebView.setAcceptFirstPartyCookies(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3970                 boolean domainThirdPartyCookiesEnabled = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3971                 nestedScrollWebView.getSettings().setDomStorageEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3972                 // Form data can be removed once the minimum API >= 26.
3973                 boolean saveFormData = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3974                 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASYLIST,
3975                         currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3976                 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASYPRIVACY,
3977                         currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3978                 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST,
3979                         currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3980                 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST,
3981                         currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3982                 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRALIST, currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ULTRALIST)) == 1);
3983                 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRAPRIVACY,
3984                         currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1);
3985                 nestedScrollWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS,
3986                         currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
3987                 String userAgentName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3988                 int fontSize = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3989                 int swipeToRefreshInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
3990                 int nightModeInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
3991                 int wideViewportInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.WIDE_VIEWPORT));
3992                 int displayWebpageImagesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3993                 boolean pinnedSslCertificate = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3994                 String pinnedSslIssuedToCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3995                 String pinnedSslIssuedToOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3996                 String pinnedSslIssuedToUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3997                 String pinnedSslIssuedByCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3998                 String pinnedSslIssuedByOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3999                 String pinnedSslIssuedByUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
4000                 boolean pinnedIpAddresses = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_IP_ADDRESSES)) == 1);
4001                 String pinnedHostIpAddresses = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.IP_ADDRESSES));
4002
4003                 // Create the pinned SSL date variables.
4004                 Date pinnedSslStartDate;
4005                 Date pinnedSslEndDate;
4006
4007                 // 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.
4008                 if (currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
4009                     pinnedSslStartDate = null;
4010                 } else {
4011                     pinnedSslStartDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
4012                 }
4013
4014                 // 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.
4015                 if (currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
4016                     pinnedSslEndDate = null;
4017                 } else {
4018                     pinnedSslEndDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
4019                 }
4020
4021                 // If there is a pinned SSL certificate, store it in the WebView.
4022                 if (pinnedSslCertificate) {
4023                     nestedScrollWebView.setPinnedSslCertificate(pinnedSslIssuedToCName, pinnedSslIssuedToOName, pinnedSslIssuedToUName, pinnedSslIssuedByCName, pinnedSslIssuedByOName, pinnedSslIssuedByUName,
4024                             pinnedSslStartDate, pinnedSslEndDate);
4025                 }
4026
4027                 // If there is a pinned IP address, store it in the WebView.
4028                 if (pinnedIpAddresses) {
4029                     nestedScrollWebView.setPinnedIpAddresses(pinnedHostIpAddresses);
4030                 }
4031
4032                 // Set night mode according to the night mode int.
4033                 switch (nightModeInt) {
4034                     case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4035                         // Set night mode according to the current default.
4036                         nestedScrollWebView.setNightMode(sharedPreferences.getBoolean("night_mode", false));
4037                         break;
4038
4039                     case DomainsDatabaseHelper.ENABLED:
4040                         // Enable night mode.
4041                         nestedScrollWebView.setNightMode(true);
4042                         break;
4043
4044                     case DomainsDatabaseHelper.DISABLED:
4045                         // Disable night mode.
4046                         nestedScrollWebView.setNightMode(false);
4047                         break;
4048                 }
4049
4050                 // Enable JavaScript if night mode is enabled.
4051                 if (nestedScrollWebView.getNightMode()) {
4052                     // Enable JavaScript.
4053                     nestedScrollWebView.getSettings().setJavaScriptEnabled(true);
4054                 } else {
4055                     // Set JavaScript according to the domain settings.
4056                     nestedScrollWebView.getSettings().setJavaScriptEnabled(nestedScrollWebView.getDomainSettingsJavaScriptEnabled());
4057                 }
4058
4059                 // Close the current host domain settings cursor.
4060                 currentDomainSettingsCursor.close();
4061
4062                 // Apply the domain settings.
4063                 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptFirstPartyCookies());
4064
4065                 // Set third-party cookies status if API >= 21.
4066                 if (Build.VERSION.SDK_INT >= 21) {
4067                     cookieManager.setAcceptThirdPartyCookies(nestedScrollWebView, domainThirdPartyCookiesEnabled);
4068                 }
4069
4070                 // Apply the form data setting if the API < 26.
4071                 if (Build.VERSION.SDK_INT < 26) {
4072                     nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
4073                 }
4074
4075                 // Apply the font size.
4076                 try {  // Try the specified font size to see if it is valid.
4077                     if (fontSize == 0) {  // Apply the default font size.
4078                             // Try to set the font size from the value in the app settings.
4079                             nestedScrollWebView.getSettings().setTextZoom(Integer.parseInt(defaultFontSizeString));
4080                     } else {  // Apply the font size from domain settings.
4081                         nestedScrollWebView.getSettings().setTextZoom(fontSize);
4082                     }
4083                 } catch (Exception exception) {  // The specified font size is invalid
4084                     // Set the font size to be 100%
4085                     nestedScrollWebView.getSettings().setTextZoom(100);
4086                 }
4087
4088                 // Set the user agent.
4089                 if (userAgentName.equals(getString(R.string.system_default_user_agent))) {  // Use the system default user agent.
4090                     // Get the array position of the default user agent name.
4091                     int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4092
4093                     // Set the user agent according to the system default.
4094                     switch (defaultUserAgentArrayPosition) {
4095                         case UNRECOGNIZED_USER_AGENT:  // The default user agent name is not on the canonical list.
4096                             // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4097                             nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
4098                             break;
4099
4100                         case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4101                             // Set the user agent to `""`, which uses the default value.
4102                             nestedScrollWebView.getSettings().setUserAgentString("");
4103                             break;
4104
4105                         case SETTINGS_CUSTOM_USER_AGENT:
4106                             // Set the default custom user agent.
4107                             nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
4108                             break;
4109
4110                         default:
4111                             // Get the user agent string from the user agent data array
4112                             nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
4113                     }
4114                 } else {  // Set the user agent according to the stored name.
4115                     // Get the array position of the user agent name.
4116                     int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
4117
4118                     switch (userAgentArrayPosition) {
4119                         case UNRECOGNIZED_USER_AGENT:  // The user agent name contains a custom user agent.
4120                             nestedScrollWebView.getSettings().setUserAgentString(userAgentName);
4121                             break;
4122
4123                         case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4124                             // Set the user agent to `""`, which uses the default value.
4125                             nestedScrollWebView.getSettings().setUserAgentString("");
4126                             break;
4127
4128                         default:
4129                             // Get the user agent string from the user agent data array.
4130                             nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4131                     }
4132                 }
4133
4134                 // Set swipe to refresh.
4135                 switch (swipeToRefreshInt) {
4136                     case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4137                         // Store the swipe to refresh status in the nested scroll WebView.
4138                         nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
4139
4140                         // 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.
4141                         swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
4142                         break;
4143
4144                     case DomainsDatabaseHelper.ENABLED:
4145                         // Store the swipe to refresh status in the nested scroll WebView.
4146                         nestedScrollWebView.setSwipeToRefresh(true);
4147
4148                         // Enable swipe to refresh.  This can be removed once the minimum API >= 23 because it is continuously set by an on scroll change listener.
4149                         swipeRefreshLayout.setEnabled(true);
4150                         break;
4151
4152                     case DomainsDatabaseHelper.DISABLED:
4153                         // Store the swipe to refresh status in the nested scroll WebView.
4154                         nestedScrollWebView.setSwipeToRefresh(false);
4155
4156                         // Disable swipe to refresh.  This can be removed once the minimum API >= 23 because it is continuously set by an on scroll change listener.
4157                         swipeRefreshLayout.setEnabled(false);
4158                 }
4159
4160                 // Set the viewport.
4161                 switch (wideViewportInt) {
4162                     case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4163                         nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
4164                         break;
4165
4166                     case DomainsDatabaseHelper.ENABLED:
4167                         nestedScrollWebView.getSettings().setUseWideViewPort(true);
4168                         break;
4169
4170                     case DomainsDatabaseHelper.DISABLED:
4171                         nestedScrollWebView.getSettings().setUseWideViewPort(false);
4172                         break;
4173                 }
4174
4175                 // Set the loading of webpage images.
4176                 switch (displayWebpageImagesInt) {
4177                     case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4178                         nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4179                         break;
4180
4181                     case DomainsDatabaseHelper.ENABLED:
4182                         nestedScrollWebView.getSettings().setLoadsImagesAutomatically(true);
4183                         break;
4184
4185                     case DomainsDatabaseHelper.DISABLED:
4186                         nestedScrollWebView.getSettings().setLoadsImagesAutomatically(false);
4187                         break;
4188                 }
4189
4190                 // 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.
4191                 if (darkTheme) {
4192                     urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
4193                 } else {
4194                     urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
4195                 }
4196             } else {  // The new URL does not have custom domain settings.  Load the defaults.
4197                 // Store the values from the shared preferences.
4198                 boolean defaultJavaScriptEnabled = sharedPreferences.getBoolean("javascript", false);
4199                 nestedScrollWebView.setAcceptFirstPartyCookies(sharedPreferences.getBoolean("first_party_cookies", false));
4200                 boolean defaultThirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies", false);
4201                 nestedScrollWebView.getSettings().setDomStorageEnabled(sharedPreferences.getBoolean("dom_storage", false));
4202                 boolean saveFormData = sharedPreferences.getBoolean("save_form_data", false);  // Form data can be removed once the minimum API >= 26.
4203                 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASYLIST, sharedPreferences.getBoolean("easylist", true));
4204                 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASYPRIVACY, sharedPreferences.getBoolean("easyprivacy", true));
4205                 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, sharedPreferences.getBoolean("fanboys_annoyance_list", true));
4206                 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, sharedPreferences.getBoolean("fanboys_social_blocking_list", true));
4207                 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRALIST, sharedPreferences.getBoolean("ultralist", true));
4208                 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRAPRIVACY, sharedPreferences.getBoolean("ultraprivacy", true));
4209                 nestedScrollWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, sharedPreferences.getBoolean("block_all_third_party_requests", false));
4210                 nestedScrollWebView.setNightMode(sharedPreferences.getBoolean("night_mode", false));
4211
4212                 // Enable JavaScript if night mode is enabled.
4213                 if (nestedScrollWebView.getNightMode()) {
4214                     // Enable JavaScript.
4215                     nestedScrollWebView.getSettings().setJavaScriptEnabled(true);
4216                 } else {
4217                     // Set JavaScript according to the domain settings.
4218                     nestedScrollWebView.getSettings().setJavaScriptEnabled(defaultJavaScriptEnabled);
4219                 }
4220
4221                 // Apply the default first-party cookie setting.
4222                 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptFirstPartyCookies());
4223
4224                 // Apply the default font size setting.
4225                 try {
4226                     // Try to set the font size from the value in the app settings.
4227                     nestedScrollWebView.getSettings().setTextZoom(Integer.parseInt(defaultFontSizeString));
4228                 } catch (Exception exception) {
4229                     // If the app settings value is invalid, set the font size to 100%.
4230                     nestedScrollWebView.getSettings().setTextZoom(100);
4231                 }
4232
4233                 // Apply the form data setting if the API < 26.
4234                 if (Build.VERSION.SDK_INT < 26) {
4235                     nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
4236                 }
4237
4238                 // Store the swipe to refresh status in the nested scroll WebView.
4239                 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
4240
4241                 // Apply swipe to refresh according to the default.
4242                 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
4243
4244                 // Reset the pinned variables.
4245                 nestedScrollWebView.setDomainSettingsDatabaseId(-1);
4246
4247                 // Set third-party cookies status if API >= 21.
4248                 if (Build.VERSION.SDK_INT >= 21) {
4249                     cookieManager.setAcceptThirdPartyCookies(nestedScrollWebView, defaultThirdPartyCookiesEnabled);
4250                 }
4251
4252                 // Get the array position of the user agent name.
4253                 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4254
4255                 // Set the user agent.
4256                 switch (userAgentArrayPosition) {
4257                     case UNRECOGNIZED_USER_AGENT:  // The default user agent name is not on the canonical list.
4258                         // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4259                         nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
4260                         break;
4261
4262                     case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4263                         // Set the user agent to `""`, which uses the default value.
4264                         nestedScrollWebView.getSettings().setUserAgentString("");
4265                         break;
4266
4267                     case SETTINGS_CUSTOM_USER_AGENT:
4268                         // Set the default custom user agent.
4269                         nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
4270                         break;
4271
4272                     default:
4273                         // Get the user agent string from the user agent data array
4274                         nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4275                 }
4276
4277                 // Set the viewport.
4278                 nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
4279
4280                 // Set the loading of webpage images.
4281                 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4282
4283                 // Set a transparent background on URL edit text.  The deprecated `getResources().getDrawable()` must be used until the minimum API >= 21.
4284                 urlRelativeLayout.setBackground(getResources().getDrawable(R.color.transparent));
4285             }
4286
4287             // Close the domains database helper.
4288             domainsDatabaseHelper.close();
4289
4290             // Update the privacy icons.
4291             updatePrivacyIcons(true);
4292         }
4293
4294         // Reload the website if returning from the Domains activity.
4295         if (reloadWebsite) {
4296             nestedScrollWebView.reload();
4297         }
4298
4299         // Return the user agent changed status.
4300         return !nestedScrollWebView.getSettings().getUserAgentString().equals(initialUserAgent);
4301     }
4302
4303     private void applyProxy(boolean reloadWebViews) {
4304         // Get a handle for the shared preferences.
4305         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4306
4307         // Get the theme preferences.
4308         boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
4309
4310         // Get a handle for the app bar layout.
4311         AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
4312
4313         // Set the proxy according to the mode.  `this` refers to the current activity where an alert dialog might be displayed.
4314         ProxyHelper.setProxy(getApplicationContext(), appBarLayout, proxyMode);
4315
4316         // Reset the waiting for proxy tracker.
4317         waitingForProxy = false;
4318
4319         // Update the user interface and reload the WebViews if requested.
4320         switch (proxyMode) {
4321             case ProxyHelper.NONE:
4322                 // Set the default app bar layout background.
4323                 if (darkTheme) {
4324                     appBarLayout.setBackgroundResource(R.color.gray_900);
4325                 } else {
4326                     appBarLayout.setBackgroundResource(R.color.gray_100);
4327                 }
4328                 break;
4329
4330             case ProxyHelper.TOR:
4331                 // Set the app bar background to indicate proxying through Orbot is enabled.
4332                 if (darkTheme) {
4333                     appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4334                 } else {
4335                     appBarLayout.setBackgroundResource(R.color.blue_50);
4336                 }
4337
4338                 // Check to see if Orbot is installed.
4339                 try {
4340                     // Get the package manager.
4341                     PackageManager packageManager = getPackageManager();
4342
4343                     // 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.
4344                     packageManager.getPackageInfo("org.torproject.android", 0);
4345
4346                     // Check to see if the proxy is ready.
4347                     if (!orbotStatus.equals("ON")) {  // Orbot is not ready.
4348                         // Set the waiting for proxy status.
4349                         waitingForProxy = true;
4350
4351                         // Show the waiting for proxy dialog if it isn't already displayed.
4352                         if (getSupportFragmentManager().findFragmentByTag(getString(R.string.waiting_for_proxy_dialog)) == null) {
4353                             // Get a handle for the waiting for proxy alert dialog.
4354                             DialogFragment waitingForProxyDialogFragment = new WaitingForProxyDialog();
4355
4356                             // Display the waiting for proxy alert dialog.
4357                             waitingForProxyDialogFragment.show(getSupportFragmentManager(), getString(R.string.waiting_for_proxy_dialog));
4358                         }
4359                     }
4360                 } catch (PackageManager.NameNotFoundException exception) {  // Orbot is not installed.
4361                     // Show the Orbot not installed dialog if it is not already displayed.
4362                     if (getSupportFragmentManager().findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
4363                         // Get a handle for the Orbot not installed alert dialog.
4364                         DialogFragment orbotNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode);
4365
4366                         // Display the Orbot not installed alert dialog.
4367                         orbotNotInstalledDialogFragment.show(getSupportFragmentManager(), getString(R.string.proxy_not_installed_dialog));
4368                     }
4369                 }
4370                 break;
4371
4372             case ProxyHelper.I2P:
4373                 // Set the app bar background to indicate proxying through Orbot is enabled.
4374                 if (darkTheme) {
4375                     appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4376                 } else {
4377                     appBarLayout.setBackgroundResource(R.color.blue_50);
4378                 }
4379
4380                 // Check to see if I2P is installed.
4381                 try {
4382                     // Get the package manager.
4383                     PackageManager packageManager = getPackageManager();
4384
4385                     // 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.
4386                     packageManager.getPackageInfo("org.torproject.android", 0);
4387                 } catch (PackageManager.NameNotFoundException exception) {  // I2P is not installed.
4388                     // Sow the I2P not installed dialog if it is not already displayed.
4389                     if (getSupportFragmentManager().findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
4390                         // Get a handle for the waiting for proxy alert dialog.
4391                         DialogFragment i2pNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode);
4392
4393                         // Display the I2P not installed alert dialog.
4394                         i2pNotInstalledDialogFragment.show(getSupportFragmentManager(), getString(R.string.proxy_not_installed_dialog));
4395                     }
4396                 }
4397                 break;
4398
4399             case ProxyHelper.CUSTOM:
4400                 // Set the app bar background to indicate proxying through Orbot is enabled.
4401                 if (darkTheme) {
4402                     appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4403                 } else {
4404                     appBarLayout.setBackgroundResource(R.color.blue_50);
4405                 }
4406                 break;
4407         }
4408
4409         // Reload the WebViews if requested and not waiting for the proxy.
4410         if (reloadWebViews && !waitingForProxy) {
4411             // Reload the WebViews.
4412             for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4413                 // Get the WebView tab fragment.
4414                 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4415
4416                 // Get the fragment view.
4417                 View fragmentView = webViewTabFragment.getView();
4418
4419                 // Only reload the WebViews if they exist.
4420                 if (fragmentView != null) {
4421                     // Get the nested scroll WebView from the tab fragment.
4422                     NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4423
4424                     // Reload the WebView.
4425                     nestedScrollWebView.reload();
4426                 }
4427             }
4428         }
4429     }
4430
4431     private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
4432         // Only update the privacy icons if the options menu and the current WebView have already been populated.
4433         if ((optionsMenu != null) && (currentWebView != null)) {
4434             // Get a handle for the shared preferences.
4435             SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4436
4437             // Get the theme and screenshot preferences.
4438             boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
4439
4440             // Get handles for the menu items.
4441             MenuItem privacyMenuItem = optionsMenu.findItem(R.id.toggle_javascript);
4442             MenuItem firstPartyCookiesMenuItem = optionsMenu.findItem(R.id.toggle_first_party_cookies);
4443             MenuItem domStorageMenuItem = optionsMenu.findItem(R.id.toggle_dom_storage);
4444             MenuItem refreshMenuItem = optionsMenu.findItem(R.id.refresh);
4445
4446             // Update the privacy icon.
4447             if (currentWebView.getSettings().getJavaScriptEnabled()) {  // JavaScript is enabled.
4448                 privacyMenuItem.setIcon(R.drawable.javascript_enabled);
4449             } else if (currentWebView.getAcceptFirstPartyCookies()) {  // JavaScript is disabled but cookies are enabled.
4450                 privacyMenuItem.setIcon(R.drawable.warning);
4451             } else {  // All the dangerous features are disabled.
4452                 privacyMenuItem.setIcon(R.drawable.privacy_mode);
4453             }
4454
4455             // Update the first-party cookies icon.
4456             if (currentWebView.getAcceptFirstPartyCookies()) {  // First-party cookies are enabled.
4457                 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
4458             } else {  // First-party cookies are disabled.
4459                 if (darkTheme) {
4460                     firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_dark);
4461                 } else {
4462                     firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_light);
4463                 }
4464             }
4465
4466             // Update the DOM storage icon.
4467             if (currentWebView.getSettings().getJavaScriptEnabled() && currentWebView.getSettings().getDomStorageEnabled()) {  // Both JavaScript and DOM storage are enabled.
4468                 domStorageMenuItem.setIcon(R.drawable.dom_storage_enabled);
4469             } else if (currentWebView.getSettings().getJavaScriptEnabled()) {  // JavaScript is enabled but DOM storage is disabled.
4470                 if (darkTheme) {
4471                     domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
4472                 } else {
4473                     domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
4474                 }
4475             } else {  // JavaScript is disabled, so DOM storage is ghosted.
4476                 if (darkTheme) {
4477                     domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
4478                 } else {
4479                     domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
4480                 }
4481             }
4482
4483             // Update the refresh icon.
4484             if (darkTheme) {
4485                 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
4486             } else {
4487                 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
4488             }
4489
4490             // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
4491             if (runInvalidateOptionsMenu) {
4492                 invalidateOptionsMenu();
4493             }
4494         }
4495     }
4496
4497     private void highlightUrlText() {
4498         // Get a handle for the URL edit text.
4499         EditText urlEditText = findViewById(R.id.url_edittext);
4500
4501         // Only highlight the URL text if the box is not currently selected.
4502         if (!urlEditText.hasFocus()) {
4503             // Get the URL string.
4504             String urlString = urlEditText.getText().toString();
4505
4506             // Highlight the URL according to the protocol.
4507             if (urlString.startsWith("file://") || urlString.startsWith("content://")) {  // This is a file or content URL.
4508                 // De-emphasize everything before the file name.
4509                 urlEditText.getText().setSpan(initialGrayColorSpan, 0, urlString.lastIndexOf("/") + 1,Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4510             } else {  // This is a web URL.
4511                 // Get the index of the `/` immediately after the domain name.
4512                 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
4513
4514                 // Create a base URL string.
4515                 String baseUrl;
4516
4517                 // Get the base URL.
4518                 if (endOfDomainName > 0) {  // There is at least one character after the base URL.
4519                     // Get the base URL.
4520                     baseUrl = urlString.substring(0, endOfDomainName);
4521                 } else {  // There are no characters after the base URL.
4522                     // Set the base URL to be the entire URL string.
4523                     baseUrl = urlString;
4524                 }
4525
4526                 // Get the index of the last `.` in the domain.
4527                 int lastDotIndex = baseUrl.lastIndexOf(".");
4528
4529                 // Get the index of the penultimate `.` in the domain.
4530                 int penultimateDotIndex = baseUrl.lastIndexOf(".", lastDotIndex - 1);
4531
4532                 // Markup the beginning of the URL.
4533                 if (urlString.startsWith("http://")) {  // Highlight the protocol of connections that are not encrypted.
4534                     urlEditText.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4535
4536                     // De-emphasize subdomains.
4537                     if (penultimateDotIndex > 0) {  // There is more than one subdomain in the domain name.
4538                         urlEditText.getText().setSpan(initialGrayColorSpan, 7, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4539                     }
4540                 } else if (urlString.startsWith("https://")) {  // De-emphasize the protocol of connections that are encrypted.
4541                     if (penultimateDotIndex > 0) {  // There is more than one subdomain in the domain name.
4542                         // De-emphasize the protocol and the additional subdomains.
4543                         urlEditText.getText().setSpan(initialGrayColorSpan, 0, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4544                     } else {  // There is only one subdomain in the domain name.
4545                         // De-emphasize only the protocol.
4546                         urlEditText.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4547                     }
4548                 }
4549
4550                 // De-emphasize the text after the domain name.
4551                 if (endOfDomainName > 0) {
4552                     urlEditText.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4553                 }
4554             }
4555         }
4556     }
4557
4558     private void loadBookmarksFolder() {
4559         // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
4560         bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
4561
4562         // Populate the bookmarks cursor adapter.  `this` specifies the `Context`.  `false` disables `autoRequery`.
4563         bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
4564             @Override
4565             public View newView(Context context, Cursor cursor, ViewGroup parent) {
4566                 // Inflate the individual item layout.  `false` does not attach it to the root.
4567                 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
4568             }
4569
4570             @Override
4571             public void bindView(View view, Context context, Cursor cursor) {
4572                 // Get handles for the views.
4573                 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
4574                 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
4575
4576                 // Get the favorite icon byte array from the cursor.
4577                 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
4578
4579                 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
4580                 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
4581
4582                 // Display the bitmap in `bookmarkFavoriteIcon`.
4583                 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4584
4585                 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4586                 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
4587                 bookmarkNameTextView.setText(bookmarkNameString);
4588
4589                 // Make the font bold for folders.
4590                 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4591                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4592                 } else {  // Reset the font to default for normal bookmarks.
4593                     bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4594                 }
4595             }
4596         };
4597
4598         // Get a handle for the bookmarks list view.
4599         ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
4600
4601         // Populate the list view with the adapter.
4602         bookmarksListView.setAdapter(bookmarksCursorAdapter);
4603
4604         // Get a handle for the bookmarks title text view.
4605         TextView bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
4606
4607         // Set the bookmarks drawer title.
4608         if (currentBookmarksFolder.isEmpty()) {
4609             bookmarksTitleTextView.setText(R.string.bookmarks);
4610         } else {
4611             bookmarksTitleTextView.setText(currentBookmarksFolder);
4612         }
4613     }
4614
4615     private void openWithApp(String url) {
4616         // Create an open with app intent with `ACTION_VIEW`.
4617         Intent openWithAppIntent = new Intent(Intent.ACTION_VIEW);
4618
4619         // Set the URI but not the MIME type.  This should open all available apps.
4620         openWithAppIntent.setData(Uri.parse(url));
4621
4622         // Flag the intent to open in a new task.
4623         openWithAppIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4624
4625         // Try the intent.
4626         try {
4627             // Show the chooser.
4628             startActivity(openWithAppIntent);
4629         } catch (ActivityNotFoundException exception) {  // There are no apps available to open the URL.
4630             // Show a snackbar with the error.
4631             Snackbar.make(currentWebView, getString(R.string.error) + "  " + exception, Snackbar.LENGTH_INDEFINITE).show();
4632         }
4633     }
4634
4635     private void openWithBrowser(String url) {
4636         // Create an open with browser intent with `ACTION_VIEW`.
4637         Intent openWithBrowserIntent = new Intent(Intent.ACTION_VIEW);
4638
4639         // Set the URI and the MIME type.  `"text/html"` should load browser options.
4640         openWithBrowserIntent.setDataAndType(Uri.parse(url), "text/html");
4641
4642         // Flag the intent to open in a new task.
4643         openWithBrowserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4644
4645         // Try the intent.
4646         try {
4647             // Show the chooser.
4648             startActivity(openWithBrowserIntent);
4649         } catch (ActivityNotFoundException exception) {  // There are no browsers available to open the URL.
4650             // Show a snackbar with the error.
4651             Snackbar.make(currentWebView, getString(R.string.error) + "  " + exception, Snackbar.LENGTH_INDEFINITE).show();
4652         }
4653     }
4654
4655     private String sanitizeUrl(String url) {
4656         // Sanitize Google Analytics.
4657         if (sanitizeGoogleAnalytics) {
4658             // Remove `?utm_`.
4659             if (url.contains("?utm_")) {
4660                 url = url.substring(0, url.indexOf("?utm_"));
4661             }
4662
4663             // Remove `&utm_`.
4664             if (url.contains("&utm_")) {
4665                 url = url.substring(0, url.indexOf("&utm_"));
4666             }
4667         }
4668
4669         // Sanitize Facebook Click IDs.
4670         if (sanitizeFacebookClickIds) {
4671             // Remove `?fbclid=`.
4672             if (url.contains("?fbclid=")) {
4673                 url = url.substring(0, url.indexOf("?fbclid="));
4674             }
4675
4676             // Remove `&fbclid=`.
4677             if (url.contains("&fbclid=")) {
4678                 url = url.substring(0, url.indexOf("&fbclid="));
4679             }
4680
4681             // Remove `?fbadid=`.
4682             if (url.contains("?fbadid=")) {
4683                 url = url.substring(0, url.indexOf("?fbadid="));
4684             }
4685
4686             // Remove `&fbadid=`.
4687             if (url.contains("&fbadid=")) {
4688                 url = url.substring(0, url.indexOf("&fbadid="));
4689             }
4690         }
4691
4692         // Sanitize Twitter AMP redirects.
4693         if (sanitizeTwitterAmpRedirects) {
4694             // Remove `?amp=1`.
4695             if (url.contains("?amp=1")) {
4696                 url = url.substring(0, url.indexOf("?amp=1"));
4697             }
4698         }
4699
4700         // Return the sanitized URL.
4701         return url;
4702     }
4703
4704     public void finishedPopulatingBlocklists(ArrayList<ArrayList<List<String[]>>> combinedBlocklists) {
4705         // Store the blocklists.
4706         easyList = combinedBlocklists.get(0);
4707         easyPrivacy = combinedBlocklists.get(1);
4708         fanboysAnnoyanceList = combinedBlocklists.get(2);
4709         fanboysSocialList = combinedBlocklists.get(3);
4710         ultraList = combinedBlocklists.get(4);
4711         ultraPrivacy = combinedBlocklists.get(5);
4712
4713         // Add the first tab.
4714         addNewTab("", true);
4715     }
4716
4717     public void addTab(View view) {
4718         // Add a new tab with a blank URL.
4719         addNewTab("", true);
4720     }
4721
4722     private void addNewTab(String url, boolean moveToTab) {
4723         // Sanitize the URL.
4724         url = sanitizeUrl(url);
4725
4726         // Get a handle for the tab layout and the view pager.
4727         TabLayout tabLayout = findViewById(R.id.tablayout);
4728         ViewPager webViewPager = findViewById(R.id.webviewpager);
4729
4730         // Get the new page number.  The page numbers are 0 indexed, so the new page number will match the current count.
4731         int newTabNumber = tabLayout.getTabCount();
4732
4733         // Add a new tab.
4734         tabLayout.addTab(tabLayout.newTab());
4735
4736         // Get the new tab.
4737         TabLayout.Tab newTab = tabLayout.getTabAt(newTabNumber);
4738
4739         // Remove the lint warning below that the current tab might be null.
4740         assert newTab != null;
4741
4742         // Set a custom view on the new tab.
4743         newTab.setCustomView(R.layout.tab_custom_view);
4744
4745         // Add the new WebView page.
4746         webViewPagerAdapter.addPage(newTabNumber, webViewPager, url, moveToTab);
4747     }
4748
4749     public void closeTab(View view) {
4750         // Get a handle for the tab layout.
4751         TabLayout tabLayout = findViewById(R.id.tablayout);
4752
4753         // Run the command according to the number of tabs.
4754         if (tabLayout.getTabCount() > 1) {  // There is more than one tab open.
4755             // Close the current tab.
4756             closeCurrentTab();
4757         } else {  // There is only one tab open.
4758             clearAndExit();
4759         }
4760     }
4761
4762     private void closeCurrentTab() {
4763         // Get handles for the views.
4764         AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
4765         TabLayout tabLayout = findViewById(R.id.tablayout);
4766         ViewPager webViewPager = findViewById(R.id.webviewpager);
4767
4768         // Get the current tab number.
4769         int currentTabNumber = tabLayout.getSelectedTabPosition();
4770
4771         // Delete the current tab.
4772         tabLayout.removeTabAt(currentTabNumber);
4773
4774         // 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.
4775         if (webViewPagerAdapter.deletePage(currentTabNumber, webViewPager)) {
4776             setCurrentWebView(currentTabNumber);
4777         }
4778
4779         // Expand the app bar if it is currently collapsed.
4780         appBarLayout.setExpanded(true);
4781     }
4782
4783     private void clearAndExit() {
4784         // Get a handle for the shared preferences.
4785         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4786
4787         // Close the bookmarks cursor and database.
4788         bookmarksCursor.close();
4789         bookmarksDatabaseHelper.close();
4790
4791         // Get the status of the clear everything preference.
4792         boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
4793
4794         // Get a handle for the runtime.
4795         Runtime runtime = Runtime.getRuntime();
4796
4797         // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
4798         // which links to `/data/data/com.stoutner.privacybrowser.standard`.
4799         String privateDataDirectoryString = getApplicationInfo().dataDir;
4800
4801         // Clear cookies.
4802         if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
4803             // The command to remove cookies changed slightly in API 21.
4804             if (Build.VERSION.SDK_INT >= 21) {
4805                 CookieManager.getInstance().removeAllCookies(null);
4806             } else {
4807                 CookieManager.getInstance().removeAllCookie();
4808             }
4809
4810             // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4811             try {
4812                 // Two commands must be used because `Runtime.exec()` does not like `*`.
4813                 Process deleteCookiesProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
4814                 Process deleteCookiesJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
4815
4816                 // Wait until the processes have finished.
4817                 deleteCookiesProcess.waitFor();
4818                 deleteCookiesJournalProcess.waitFor();
4819             } catch (Exception exception) {
4820                 // Do nothing if an error is thrown.
4821             }
4822         }
4823
4824         // Clear DOM storage.
4825         if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
4826             // Ask `WebStorage` to clear the DOM storage.
4827             WebStorage webStorage = WebStorage.getInstance();
4828             webStorage.deleteAllData();
4829
4830             // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4831             try {
4832                 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4833                 Process deleteLocalStorageProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
4834
4835                 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
4836                 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
4837                 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
4838                 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
4839                 Process deleteDatabaseProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
4840
4841                 // Wait until the processes have finished.
4842                 deleteLocalStorageProcess.waitFor();
4843                 deleteIndexProcess.waitFor();
4844                 deleteQuotaManagerProcess.waitFor();
4845                 deleteQuotaManagerJournalProcess.waitFor();
4846                 deleteDatabaseProcess.waitFor();
4847             } catch (Exception exception) {
4848                 // Do nothing if an error is thrown.
4849             }
4850         }
4851
4852         // Clear form data if the API < 26.
4853         if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
4854             WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
4855             webViewDatabase.clearFormData();
4856
4857             // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4858             try {
4859                 // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
4860                 Process deleteWebDataProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
4861                 Process deleteWebDataJournalProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
4862
4863                 // Wait until the processes have finished.
4864                 deleteWebDataProcess.waitFor();
4865                 deleteWebDataJournalProcess.waitFor();
4866             } catch (Exception exception) {
4867                 // Do nothing if an error is thrown.
4868             }
4869         }
4870
4871         // Clear the cache.
4872         if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
4873             // Clear the cache from each WebView.
4874             for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4875                 // Get the WebView tab fragment.
4876                 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4877
4878                 // Get the fragment view.
4879                 View fragmentView = webViewTabFragment.getView();
4880
4881                 // Only clear the cache if the WebView exists.
4882                 if (fragmentView != null) {
4883                     // Get the nested scroll WebView from the tab fragment.
4884                     NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4885
4886                     // Clear the cache for this WebView.
4887                     nestedScrollWebView.clearCache(true);
4888                 }
4889             }
4890
4891             // Manually delete the cache directories.
4892             try {
4893                 // Delete the main cache directory.
4894                 Process deleteCacheProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/cache");
4895
4896                 // Delete the secondary `Service Worker` cache directory.
4897                 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4898                 Process deleteServiceWorkerProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
4899
4900                 // Wait until the processes have finished.
4901                 deleteCacheProcess.waitFor();
4902                 deleteServiceWorkerProcess.waitFor();
4903             } catch (Exception exception) {
4904                 // Do nothing if an error is thrown.
4905             }
4906         }
4907
4908         // Wipe out each WebView.
4909         for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4910             // Get the WebView tab fragment.
4911             WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4912
4913             // Get the fragment view.
4914             View fragmentView = webViewTabFragment.getView();
4915
4916             // Only wipe out the WebView if it exists.
4917             if (fragmentView != null) {
4918                 // Get the nested scroll WebView from the tab fragment.
4919                 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4920
4921                 // Clear SSL certificate preferences for this WebView.
4922                 nestedScrollWebView.clearSslPreferences();
4923
4924                 // Clear the back/forward history for this WebView.
4925                 nestedScrollWebView.clearHistory();
4926
4927                 // Destroy the internal state of `mainWebView`.
4928                 nestedScrollWebView.destroy();
4929             }
4930         }
4931
4932         // Clear the custom headers.
4933         customHeaders.clear();
4934
4935         // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
4936         // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
4937         if (clearEverything) {
4938             try {
4939                 // Delete the folder.
4940                 Process deleteAppWebviewProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
4941
4942                 // Wait until the process has finished.
4943                 deleteAppWebviewProcess.waitFor();
4944             } catch (Exception exception) {
4945                 // Do nothing if an error is thrown.
4946             }
4947         }
4948
4949         // Close Privacy Browser.  `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
4950         if (Build.VERSION.SDK_INT >= 21) {
4951             finishAndRemoveTask();
4952         } else {
4953             finish();
4954         }
4955
4956         // Remove the terminated program from RAM.  The status code is `0`.
4957         System.exit(0);
4958     }
4959
4960     private void setCurrentWebView(int pageNumber) {
4961         // Get a handle for the shared preferences.
4962         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4963
4964         // Get the theme preference.
4965         boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
4966
4967         // Get handles for the URL views.
4968         RelativeLayout urlRelativeLayout = findViewById(R.id.url_relativelayout);
4969         EditText urlEditText = findViewById(R.id.url_edittext);
4970         SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
4971
4972         // Stop the swipe to refresh indicator if it is running
4973         swipeRefreshLayout.setRefreshing(false);
4974
4975         // Get the WebView tab fragment.
4976         WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(pageNumber);
4977
4978         // Get the fragment view.
4979         View fragmentView = webViewTabFragment.getView();
4980
4981         // Set the current WebView if the fragment view is not null.
4982         if (fragmentView != null) {  // The fragment has been populated.
4983             // Store the current WebView.
4984             currentWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4985
4986             // Update the status of swipe to refresh.
4987             if (currentWebView.getSwipeToRefresh()) {  // Swipe to refresh is enabled.
4988                 // Enable the swipe refresh layout if the WebView is scrolled all the way to the top.  It is updated every time the scroll changes.
4989                 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
4990             } else {  // Swipe to refresh is disabled.
4991                 // Disable the swipe refresh layout.
4992                 swipeRefreshLayout.setEnabled(false);
4993             }
4994
4995             // Get a handle for the cookie manager.
4996             CookieManager cookieManager = CookieManager.getInstance();
4997
4998             // Set the first-party cookie status.
4999             cookieManager.setAcceptCookie(currentWebView.getAcceptFirstPartyCookies());
5000
5001             // Update the privacy icons.  `true` redraws the icons in the app bar.
5002             updatePrivacyIcons(true);
5003
5004             // Get a handle for the input method manager.
5005             InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
5006
5007             // Remove the lint warning below that the input method manager might be null.
5008             assert inputMethodManager != null;
5009
5010             // Get the current URL.
5011             String url = currentWebView.getUrl();
5012
5013             // Update the URL edit text if not loading a new intent.  Otherwise, this will be handled by `onPageStarted()` (if called) and `onPageFinished()`.
5014             if (!loadingNewIntent) {  // A new intent is not being loaded.
5015                 if ((url == null) || url.equals("about:blank")) {  // The WebView is blank.
5016                     // Display the hint in the URL edit text.
5017                     urlEditText.setText("");
5018
5019                     // Request focus for the URL text box.
5020                     urlEditText.requestFocus();
5021
5022                     // Display the keyboard.
5023                     inputMethodManager.showSoftInput(urlEditText, 0);
5024                 } else {  // The WebView has a loaded URL.
5025                     // Clear the focus from the URL text box.
5026                     urlEditText.clearFocus();
5027
5028                     // Hide the soft keyboard.
5029                     inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
5030
5031                     // Display the current URL in the URL text box.
5032                     urlEditText.setText(url);
5033
5034                     // Highlight the URL text.
5035                     highlightUrlText();
5036                 }
5037             } else {  // A new intent is being loaded.
5038                 // Reset the loading new intent tracker.
5039                 loadingNewIntent = false;
5040             }
5041
5042             // Set the background to indicate the domain settings status.
5043             if (currentWebView.getDomainSettingsApplied()) {
5044                 // 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.
5045                 if (darkTheme) {
5046                     urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
5047                 } else {
5048                     urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
5049                 }
5050             } else {
5051                 urlRelativeLayout.setBackground(getResources().getDrawable(R.color.transparent));
5052             }
5053         } else {  // The fragment has not been populated.  Try again in 100 milliseconds.
5054             // Create a handler to set the current WebView.
5055             Handler setCurrentWebViewHandler = new Handler();
5056
5057             // Create a runnable to set the current WebView.
5058             Runnable setCurrentWebWebRunnable = () -> {
5059                 // Set the current WebView.
5060                 setCurrentWebView(pageNumber);
5061             };
5062
5063             // Try setting the current WebView again after 100 milliseconds.
5064             setCurrentWebViewHandler.postDelayed(setCurrentWebWebRunnable, 100);
5065         }
5066     }
5067
5068     @Override
5069     public void initializeWebView(NestedScrollWebView nestedScrollWebView, int pageNumber, ProgressBar progressBar, String url) {
5070         // Get handles for the activity views.
5071         FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
5072         DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
5073         RelativeLayout mainContentRelativeLayout = findViewById(R.id.main_content_relativelayout);
5074         ActionBar actionBar = getSupportActionBar();
5075         LinearLayout tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
5076         EditText urlEditText = findViewById(R.id.url_edittext);
5077         TabLayout tabLayout = findViewById(R.id.tablayout);
5078         SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
5079
5080         // Remove the incorrect lint warning below that the action bar might be null.
5081         assert actionBar != null;
5082
5083         // Get a handle for the activity
5084         Activity activity = this;
5085
5086         // Get a handle for the input method manager.
5087         InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
5088
5089         // Instantiate the blocklist helper.
5090         BlocklistHelper blocklistHelper = new BlocklistHelper();
5091
5092         // Remove the lint warning below that the input method manager might be null.
5093         assert inputMethodManager != null;
5094
5095         // Get a handle for the shared preferences.
5096         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
5097
5098         // Initialize the favorite icon.
5099         nestedScrollWebView.initializeFavoriteIcon();
5100
5101         // Set the app bar scrolling.
5102         nestedScrollWebView.setNestedScrollingEnabled(sharedPreferences.getBoolean("scroll_app_bar", true));
5103
5104         // Allow pinch to zoom.
5105         nestedScrollWebView.getSettings().setBuiltInZoomControls(true);
5106
5107         // Hide zoom controls.
5108         nestedScrollWebView.getSettings().setDisplayZoomControls(false);
5109
5110         // Don't allow mixed content (HTTP and HTTPS) on the same website.
5111         if (Build.VERSION.SDK_INT >= 21) {
5112             nestedScrollWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);
5113         }
5114
5115         // Set the WebView to load in overview mode (zoomed out to the maximum width).
5116         nestedScrollWebView.getSettings().setLoadWithOverviewMode(true);
5117
5118         // Explicitly disable geolocation.
5119         nestedScrollWebView.getSettings().setGeolocationEnabled(false);
5120
5121         // Create a double-tap gesture detector to toggle full-screen mode.
5122         GestureDetector doubleTapGestureDetector = new GestureDetector(getApplicationContext(), new GestureDetector.SimpleOnGestureListener() {
5123             // Override `onDoubleTap()`.  All other events are handled using the default settings.
5124             @Override
5125             public boolean onDoubleTap(MotionEvent event) {
5126                 if (fullScreenBrowsingModeEnabled) {  // Only process the double-tap if full screen browsing mode is enabled.
5127                     // Toggle the full screen browsing mode tracker.
5128                     inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
5129
5130                     // Toggle the full screen browsing mode.
5131                     if (inFullScreenBrowsingMode) {  // Switch to full screen mode.
5132                         // Store the swipe refresh layout top padding.
5133                         swipeRefreshLayoutPaddingTop = swipeRefreshLayout.getPaddingTop();
5134
5135                         // Hide the app bar if specified.
5136                         if (hideAppBar) {
5137                             // Close the find on page bar if it is visible.
5138                             closeFindOnPage(null);
5139
5140                             // Hide the tab linear layout.
5141                             tabsLinearLayout.setVisibility(View.GONE);
5142
5143                             // Hide the action bar.
5144                             actionBar.hide();
5145
5146                             // Check to see if app bar scrolling is disabled.
5147                             if (!scrollAppBar) {
5148                                 // Remove the padding from the top of the swipe refresh layout.
5149                                 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5150                             }
5151                         }
5152
5153                         // Hide the banner ad in the free flavor.
5154                         if (BuildConfig.FLAVOR.contentEquals("free")) {
5155                             AdHelper.hideAd(findViewById(R.id.adview));
5156                         }
5157
5158                         // Remove the translucent status flag.  This is necessary so the root frame layout can fill the entire screen.
5159                         getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
5160
5161                         /* Hide the system bars.
5162                          * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5163                          * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5164                          * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5165                          * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5166                          */
5167                         rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5168                                 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5169                     } else {  // Switch to normal viewing mode.
5170                         // Show the tab linear layout.
5171                         tabsLinearLayout.setVisibility(View.VISIBLE);
5172
5173                         // Show the action bar.
5174                         actionBar.show();
5175
5176                         // Check to see if app bar scrolling is disabled.
5177                         if (!scrollAppBar) {
5178                             // Add the padding from the top of the swipe refresh layout.
5179                             swipeRefreshLayout.setPadding(0, swipeRefreshLayoutPaddingTop, 0, 0);
5180                         }
5181
5182                         // Show the banner ad in the free flavor.
5183                         if (BuildConfig.FLAVOR.contentEquals("free")) {
5184                             // Reload the ad.
5185                             AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
5186                         }
5187
5188                         // Remove the `SYSTEM_UI` flags from the root frame layout.
5189                         rootFrameLayout.setSystemUiVisibility(0);
5190
5191                         // Add the translucent status flag.
5192                         getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
5193                     }
5194
5195                     // Consume the double-tap.
5196                     return true;
5197                 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
5198                     return false;
5199                 }
5200             }
5201         });
5202
5203         // Pass all touch events on the WebView through the double-tap gesture detector.
5204         nestedScrollWebView.setOnTouchListener((View view, MotionEvent event) -> {
5205             // Call `performClick()` on the view, which is required for accessibility.
5206             view.performClick();
5207
5208             // Send the event to the gesture detector.
5209             return doubleTapGestureDetector.onTouchEvent(event);
5210         });
5211
5212         // Register the WebView for a context menu.  This is used to see link targets and download images.
5213         registerForContextMenu(nestedScrollWebView);
5214
5215         // Allow the downloading of files.
5216         nestedScrollWebView.setDownloadListener((String downloadUrl, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
5217             // Instantiate the save dialog.
5218             DialogFragment saveDialogFragment = SaveDialog.saveUrl(StoragePermissionDialog.SAVE_URL, downloadUrl, userAgent, nestedScrollWebView.getAcceptFirstPartyCookies());
5219
5220             // Show the save dialog.  It must be named `save_dialog` so that the file picker can update the file name.
5221             saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
5222         });
5223
5224         // Update the find on page count.
5225         nestedScrollWebView.setFindListener(new WebView.FindListener() {
5226             // Get a handle for `findOnPageCountTextView`.
5227             final TextView findOnPageCountTextView = findViewById(R.id.find_on_page_count_textview);
5228
5229             @Override
5230             public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
5231                 if ((isDoneCounting) && (numberOfMatches == 0)) {  // There are no matches.
5232                     // Set `findOnPageCountTextView` to `0/0`.
5233                     findOnPageCountTextView.setText(R.string.zero_of_zero);
5234                 } else if (isDoneCounting) {  // There are matches.
5235                     // `activeMatchOrdinal` is zero-based.
5236                     int activeMatch = activeMatchOrdinal + 1;
5237
5238                     // Build the match string.
5239                     String matchString = activeMatch + "/" + numberOfMatches;
5240
5241                     // Set `findOnPageCountTextView`.
5242                     findOnPageCountTextView.setText(matchString);
5243                 }
5244             }
5245         });
5246
5247         // Update the status of swipe to refresh based on the scroll position of the nested scroll WebView.  Also reinforce full screen browsing mode.
5248         // Once the minimum API >= 23 this can be replaced with `nestedScrollWebView.setOnScrollChangeListener()`.
5249         nestedScrollWebView.getViewTreeObserver().addOnScrollChangedListener(() -> {
5250             if (nestedScrollWebView.getSwipeToRefresh()) {
5251                 // Only enable swipe to refresh if the WebView is scrolled to the top.
5252                 swipeRefreshLayout.setEnabled(nestedScrollWebView.getScrollY() == 0);
5253             }
5254
5255             // Reinforce the system UI visibility flags if in full screen browsing mode.
5256             // This hides the status and navigation bars, which are displayed if other elements are shown, like dialog boxes, the options menu, or the keyboard.
5257             if (inFullScreenBrowsingMode) {
5258                 /* Hide the system bars.
5259                  * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5260                  * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5261                  * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5262                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5263                  */
5264                 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5265                         View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5266             }
5267         });
5268
5269         // Set the web chrome client.
5270         nestedScrollWebView.setWebChromeClient(new WebChromeClient() {
5271             // Update the progress bar when a page is loading.
5272             @Override
5273             public void onProgressChanged(WebView view, int progress) {
5274                 // Inject the night mode CSS if night mode is enabled.
5275                 if (nestedScrollWebView.getNightMode()) {  // Night mode is enabled.
5276                     // `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
5277                     // used by WordPress.  `text-decoration: none` removes all text underlines.  `text-shadow: none` removes text shadows, which usually have a hard coded color.
5278                     // `border: none` removes all borders, which can also be used to underline text.  `a {color: #1565C0}` sets links to be a dark blue.
5279                     // `::selection {background: #0D47A1}' sets the text selection highlight color to be a dark blue. `!important` takes precedent over any existing sub-settings.
5280                     nestedScrollWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
5281                             "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
5282                             "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;} ::selection {background: #0D47A1 !important;}'; parent.appendChild(style)})()", value -> {
5283                         // Initialize a handler to display `mainWebView`.
5284                         Handler displayWebViewHandler = new Handler();
5285
5286                         // Setup a runnable to display `mainWebView` after a delay to allow the CSS to be applied.
5287                         Runnable displayWebViewRunnable = () -> {
5288                             // Only display `mainWebView` if the progress bar is gone.  This prevents the display of the `WebView` while it is still loading.
5289                             if (progressBar.getVisibility() == View.GONE) {
5290                                 nestedScrollWebView.setVisibility(View.VISIBLE);
5291                             }
5292                         };
5293
5294                         // Display the WebView after 500 milliseconds.
5295                         displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
5296                     });
5297                 } else {  // Night mode is disabled.
5298                     // Display the nested scroll WebView if night mode is disabled.
5299                     // Because of a race condition between `applyDomainSettings` and `onPageStarted`,
5300                     // when night mode is set by domain settings the WebView may be hidden even if night mode is not currently enabled.
5301                     nestedScrollWebView.setVisibility(View.VISIBLE);
5302                 }
5303
5304                 // Update the progress bar.
5305                 progressBar.setProgress(progress);
5306
5307                 // Set the visibility of the progress bar.
5308                 if (progress < 100) {
5309                     // Show the progress bar.
5310                     progressBar.setVisibility(View.VISIBLE);
5311                 } else {
5312                     // Hide the progress bar.
5313                     progressBar.setVisibility(View.GONE);
5314
5315                     //Stop the swipe to refresh indicator if it is running
5316                     swipeRefreshLayout.setRefreshing(false);
5317                 }
5318             }
5319
5320             // Set the favorite icon when it changes.
5321             @Override
5322             public void onReceivedIcon(WebView view, Bitmap icon) {
5323                 // Only update the favorite icon if the website has finished loading.
5324                 if (progressBar.getVisibility() == View.GONE) {
5325                     // Store the new favorite icon.
5326                     nestedScrollWebView.setFavoriteOrDefaultIcon(icon);
5327
5328                     // Get the current page position.
5329                     int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5330
5331                     // Get the current tab.
5332                     TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
5333
5334                     // Check to see if the tab has been populated.
5335                     if (tab != null) {
5336                         // Get the custom view from the tab.
5337                         View tabView = tab.getCustomView();
5338
5339                         // Check to see if the custom tab view has been populated.
5340                         if (tabView != null) {
5341                             // Get the favorite icon image view from the tab.
5342                             ImageView tabFavoriteIconImageView = tabView.findViewById(R.id.favorite_icon_imageview);
5343
5344                             // Display the favorite icon in the tab.
5345                             tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
5346                         }
5347                     }
5348                 }
5349             }
5350
5351             // Save a copy of the title when it changes.
5352             @Override
5353             public void onReceivedTitle(WebView view, String title) {
5354                 // Get the current page position.
5355                 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5356
5357                 // Get the current tab.
5358                 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
5359
5360                 // Only populate the title text view if the tab has been fully created.
5361                 if (tab != null) {
5362                     // Get the custom view from the tab.
5363                     View tabView = tab.getCustomView();
5364
5365                     // Remove the incorrect warning below that the current tab view might be null.
5366                     assert tabView != null;
5367
5368                     // Get the title text view from the tab.
5369                     TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
5370
5371                     // Set the title according to the URL.
5372                     if (title.equals("about:blank")) {
5373                         // Set the title to indicate a new tab.
5374                         tabTitleTextView.setText(R.string.new_tab);
5375                     } else {
5376                         // Set the title as the tab text.
5377                         tabTitleTextView.setText(title);
5378                     }
5379                 }
5380             }
5381
5382             // Enter full screen video.
5383             @Override
5384             public void onShowCustomView(View video, CustomViewCallback callback) {
5385                 // Get a handle for the full screen video frame layout.
5386                 FrameLayout fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
5387
5388                 // Set the full screen video flag.
5389                 displayingFullScreenVideo = true;
5390
5391                 // Pause the ad if this is the free flavor.
5392                 if (BuildConfig.FLAVOR.contentEquals("free")) {
5393                     // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
5394                     AdHelper.pauseAd(findViewById(R.id.adview));
5395                 }
5396
5397                 // Hide the keyboard.
5398                 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
5399
5400                 // Hide the main content relative layout.
5401                 mainContentRelativeLayout.setVisibility(View.GONE);
5402
5403                 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
5404                 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
5405
5406                 // Remove the translucent status flag.  This is necessary so the root frame layout can fill the entire screen.
5407                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
5408
5409                 /* Hide the system bars.
5410                  * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5411                  * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5412                  * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5413                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5414                  */
5415                 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5416                         View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5417
5418                 // Disable the sliding drawers.
5419                 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
5420
5421                 // Add the video view to the full screen video frame layout.
5422                 fullScreenVideoFrameLayout.addView(video);
5423
5424                 // Show the full screen video frame layout.
5425                 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
5426
5427                 // Disable the screen timeout while the video is playing.  YouTube does this automatically, but not all other videos do.
5428                 fullScreenVideoFrameLayout.setKeepScreenOn(true);
5429             }
5430
5431             // Exit full screen video.
5432             @Override
5433             public void onHideCustomView() {
5434                 // Get a handle for the full screen video frame layout.
5435                 FrameLayout fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
5436
5437                 // Re-enable the screen timeout.
5438                 fullScreenVideoFrameLayout.setKeepScreenOn(false);
5439
5440                 // Unset the full screen video flag.
5441                 displayingFullScreenVideo = false;
5442
5443                 // Remove all the views from the full screen video frame layout.
5444                 fullScreenVideoFrameLayout.removeAllViews();
5445
5446                 // Hide the full screen video frame layout.
5447                 fullScreenVideoFrameLayout.setVisibility(View.GONE);
5448
5449                 // Enable the sliding drawers.
5450                 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
5451
5452                 // Show the main content relative layout.
5453                 mainContentRelativeLayout.setVisibility(View.VISIBLE);
5454
5455                 // Apply the appropriate full screen mode flags.
5456                 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {  // Privacy Browser is currently in full screen browsing mode.
5457                     // Hide the app bar if specified.
5458                     if (hideAppBar) {
5459                         // Hide the tab linear layout.
5460                         tabsLinearLayout.setVisibility(View.GONE);
5461
5462                         // Hide the action bar.
5463                         actionBar.hide();
5464                     }
5465
5466                     // Hide the banner ad in the free flavor.
5467                     if (BuildConfig.FLAVOR.contentEquals("free")) {
5468                         AdHelper.hideAd(findViewById(R.id.adview));
5469                     }
5470
5471                     // Remove the translucent status flag.  This is necessary so the root frame layout can fill the entire screen.
5472                     getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
5473
5474                     /* Hide the system bars.
5475                      * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5476                      * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5477                      * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5478                      * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5479                      */
5480                     rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5481                             View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5482                 } else {  // Switch to normal viewing mode.
5483                     // Remove the `SYSTEM_UI` flags from the root frame layout.
5484                     rootFrameLayout.setSystemUiVisibility(0);
5485
5486                     // Add the translucent status flag.
5487                     getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
5488                 }
5489
5490                 // Reload the ad for the free flavor if not in full screen mode.
5491                 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
5492                     // Reload the ad.
5493                     AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
5494                 }
5495             }
5496
5497             // Upload files.
5498             @Override
5499             public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
5500                 // Show the file chooser if the device is running API >= 21.
5501                 if (Build.VERSION.SDK_INT >= 21) {
5502                     // Store the file path callback.
5503                     fileChooserCallback = filePathCallback;
5504
5505                     // Create an intent to open a chooser based ont the file chooser parameters.
5506                     Intent fileChooserIntent = fileChooserParams.createIntent();
5507
5508                     // Open the file chooser.
5509                     startActivityForResult(fileChooserIntent, BROWSE_FILE_UPLOAD_REQUEST_CODE);
5510                 }
5511                 return true;
5512             }
5513         });
5514
5515         nestedScrollWebView.setWebViewClient(new WebViewClient() {
5516             // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
5517             // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
5518             @Override
5519             public boolean shouldOverrideUrlLoading(WebView view, String url) {
5520                 // Sanitize the url.
5521                 url = sanitizeUrl(url);
5522
5523                 if (url.startsWith("http")) {  // Load the URL in Privacy Browser.
5524                     // Apply the domain settings for the new URL.  This doesn't do anything if the domain has not changed.
5525                     boolean userAgentChanged = applyDomainSettings(nestedScrollWebView, url, true, false);
5526
5527                     // Check if the user agent has changed.
5528                     if (userAgentChanged) {
5529                         // Manually load the URL.  The changing of the user agent will cause WebView to reload the previous URL.
5530                         nestedScrollWebView.loadUrl(url, customHeaders);
5531
5532                         // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
5533                         return true;
5534                     } else {
5535                         // Returning false causes the current WebView to handle the URL and prevents it from adding redirects to the history list.
5536                         return false;
5537                     }
5538                 } else if (url.startsWith("mailto:")) {  // Load the email address in an external email program.
5539                     // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
5540                     Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
5541
5542                     // Parse the url and set it as the data for the intent.
5543                     emailIntent.setData(Uri.parse(url));
5544
5545                     // Open the email program in a new task instead of as part of Privacy Browser.
5546                     emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5547
5548                     // Make it so.
5549                     startActivity(emailIntent);
5550
5551                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5552                     return true;
5553                 } else if (url.startsWith("tel:")) {  // Load the phone number in the dialer.
5554                     // Open the dialer and load the phone number, but wait for the user to place the call.
5555                     Intent dialIntent = new Intent(Intent.ACTION_DIAL);
5556
5557                     // Add the phone number to the intent.
5558                     dialIntent.setData(Uri.parse(url));
5559
5560                     // Open the dialer in a new task instead of as part of Privacy Browser.
5561                     dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5562
5563                     // Make it so.
5564                     startActivity(dialIntent);
5565
5566                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5567                     return true;
5568                 } else {  // Load a system chooser to select an app that can handle the URL.
5569                     // Open an app that can handle the URL.
5570                     Intent genericIntent = new Intent(Intent.ACTION_VIEW);
5571
5572                     // Add the URL to the intent.
5573                     genericIntent.setData(Uri.parse(url));
5574
5575                     // List all apps that can handle the URL instead of just opening the first one.
5576                     genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
5577
5578                     // Open the app in a new task instead of as part of Privacy Browser.
5579                     genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5580
5581                     // Start the app or display a snackbar if no app is available to handle the URL.
5582                     try {
5583                         startActivity(genericIntent);
5584                     } catch (ActivityNotFoundException exception) {
5585                         Snackbar.make(nestedScrollWebView, getString(R.string.unrecognized_url) + "  " + url, Snackbar.LENGTH_SHORT).show();
5586                     }
5587
5588                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5589                     return true;
5590                 }
5591             }
5592
5593             // Check requests against the block lists.  The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
5594             @Override
5595             public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
5596                 // Check to see if the resource request is for the main URL.
5597                 if (url.equals(nestedScrollWebView.getCurrentUrl())) {
5598                     // `return null` loads the resource request, which should never be blocked if it is the main URL.
5599                     return null;
5600                 }
5601
5602                 // 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.
5603                 while (ultraPrivacy == null) {
5604                     // The wait must be synchronized, which only lets one thread run on it at a time, or `java.lang.IllegalMonitorStateException` is thrown.
5605                     synchronized (this) {
5606                         try {
5607                             // Check to see if the blocklists have been populated after 100 ms.
5608                             wait(100);
5609                         } catch (InterruptedException exception) {
5610                             // Do nothing.
5611                         }
5612                     }
5613                 }
5614
5615                 // Sanitize the URL.
5616                 url = sanitizeUrl(url);
5617
5618                 // Get a handle for the navigation view.
5619                 NavigationView navigationView = findViewById(R.id.navigationview);
5620
5621                 // Get a handle for the navigation menu.
5622                 Menu navigationMenu = navigationView.getMenu();
5623
5624                 // Get a handle for the navigation requests menu item.  The menu is 0 based.
5625                 MenuItem navigationRequestsMenuItem = navigationMenu.getItem(6);
5626
5627                 // Create an empty web resource response to be used if the resource request is blocked.
5628                 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
5629
5630                 // Reset the whitelist results tracker.
5631                 String[] whitelistResultStringArray = null;
5632
5633                 // Initialize the third party request tracker.
5634                 boolean isThirdPartyRequest = false;
5635
5636                 // Get the current URL.  `.getUrl()` throws an error because operations on the WebView cannot be made from this thread.
5637                 String currentBaseDomain = nestedScrollWebView.getCurrentDomainName();
5638
5639                 // Store a copy of the current domain for use in later requests.
5640                 String currentDomain = currentBaseDomain;
5641
5642                 // Nobody is happy when comparing null strings.
5643                 if ((currentBaseDomain != null) && (url != null)) {
5644                     // Convert the request URL to a URI.
5645                     Uri requestUri = Uri.parse(url);
5646
5647                     // Get the request host name.
5648                     String requestBaseDomain = requestUri.getHost();
5649
5650                     // Only check for third-party requests if the current base domain is not empty and the request domain is not null.
5651                     if (!currentBaseDomain.isEmpty() && (requestBaseDomain != null)) {
5652                         // Determine the current base domain.
5653                         while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) {  // There is at least one subdomain.
5654                             // Remove the first subdomain.
5655                             currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
5656                         }
5657
5658                         // Determine the request base domain.
5659                         while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) {  // There is at least one subdomain.
5660                             // Remove the first subdomain.
5661                             requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
5662                         }
5663
5664                         // Update the third party request tracker.
5665                         isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
5666                     }
5667                 }
5668
5669                 // Get the current WebView page position.
5670                 int webViewPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5671
5672                 // Determine if the WebView is currently displayed.
5673                 boolean webViewDisplayed = (webViewPagePosition == tabLayout.getSelectedTabPosition());
5674
5675                 // Block third-party requests if enabled.
5676                 if (isThirdPartyRequest && nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS)) {
5677                     // Add the result to the resource requests.
5678                     nestedScrollWebView.addResourceRequest(new String[]{BlocklistHelper.REQUEST_THIRD_PARTY, url});
5679
5680                     // Increment the blocked requests counters.
5681                     nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5682                     nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS);
5683
5684                     // Update the titles of the blocklist menu items if the WebView is currently displayed.
5685                     if (webViewDisplayed) {
5686                         // Updating the UI must be run from the UI thread.
5687                         activity.runOnUiThread(() -> {
5688                             // Update the menu item titles.
5689                             navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5690
5691                             // Update the options menu if it has been populated.
5692                             if (optionsMenu != null) {
5693                                 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5694                                 optionsMenu.findItem(R.id.block_all_third_party_requests).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " +
5695                                         getString(R.string.block_all_third_party_requests));
5696                             }
5697                         });
5698                     }
5699
5700                     // Return an empty web resource response.
5701                     return emptyWebResourceResponse;
5702                 }
5703
5704                 // Check UltraList if it is enabled.
5705                 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST)) {
5706                     // Check the URL against UltraList.
5707                     String[] ultraListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraList);
5708
5709                     // Process the UltraList results.
5710                     if (ultraListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) {  // The resource request matched UltraLists's blacklist.
5711                         // Add the result to the resource requests.
5712                         nestedScrollWebView.addResourceRequest(new String[] {ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]});
5713
5714                         // Increment the blocked requests counters.
5715                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5716                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRALIST);
5717
5718                         // Update the titles of the blocklist menu items if the WebView is currently displayed.
5719                         if (webViewDisplayed) {
5720                             // Updating the UI must be run from the UI thread.
5721                             activity.runOnUiThread(() -> {
5722                                 // Update the menu item titles.
5723                                 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5724
5725                                 // Update the options menu if it has been populated.
5726                                 if (optionsMenu != null) {
5727                                     optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5728                                     optionsMenu.findItem(R.id.ultralist).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRALIST) + " - " + getString(R.string.ultralist));
5729                                 }
5730                             });
5731                         }
5732
5733                         // The resource request was blocked.  Return an empty web resource response.
5734                         return emptyWebResourceResponse;
5735                     } else if (ultraListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) {  // The resource request matched UltraList's whitelist.
5736                         // Add a whitelist entry to the resource requests array.
5737                         nestedScrollWebView.addResourceRequest(new String[] {ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]});
5738
5739                         // The resource request has been allowed by UltraPrivacy.  `return null` loads the requested resource.
5740                         return null;
5741                     }
5742                 }
5743
5744                 // Check UltraPrivacy if it is enabled.
5745                 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY)) {
5746                     // Check the URL against UltraPrivacy.
5747                     String[] ultraPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraPrivacy);
5748
5749                     // Process the UltraPrivacy results.
5750                     if (ultraPrivacyResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) {  // The resource request matched UltraPrivacy's blacklist.
5751                         // Add the result to the resource requests.
5752                         nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5753                                 ultraPrivacyResults[5]});
5754
5755                         // Increment the blocked requests counters.
5756                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5757                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRAPRIVACY);
5758
5759                         // Update the titles of the blocklist menu items if the WebView is currently displayed.
5760                         if (webViewDisplayed) {
5761                             // Updating the UI must be run from the UI thread.
5762                             activity.runOnUiThread(() -> {
5763                                 // Update the menu item titles.
5764                                 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5765
5766                                 // Update the options menu if it has been populated.
5767                                 if (optionsMenu != null) {
5768                                     optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5769                                     optionsMenu.findItem(R.id.ultraprivacy).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRAPRIVACY) + " - " + getString(R.string.ultraprivacy));
5770                                 }
5771                             });
5772                         }
5773
5774                         // The resource request was blocked.  Return an empty web resource response.
5775                         return emptyWebResourceResponse;
5776                     } else if (ultraPrivacyResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) {  // The resource request matched UltraPrivacy's whitelist.
5777                         // Add a whitelist entry to the resource requests array.
5778                         nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5779                                 ultraPrivacyResults[5]});
5780
5781                         // The resource request has been allowed by UltraPrivacy.  `return null` loads the requested resource.
5782                         return null;
5783                     }
5784                 }
5785
5786                 // Check EasyList if it is enabled.
5787                 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST)) {
5788                     // Check the URL against EasyList.
5789                     String[] easyListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyList);
5790
5791                     // Process the EasyList results.
5792                     if (easyListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) {  // The resource request matched EasyList's blacklist.
5793                         // Add the result to the resource requests.
5794                         nestedScrollWebView.addResourceRequest(new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]});
5795
5796                         // Increment the blocked requests counters.
5797                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5798                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASYLIST);
5799
5800                         // Update the titles of the blocklist menu items if the WebView is currently displayed.
5801                         if (webViewDisplayed) {
5802                             // Updating the UI must be run from the UI thread.
5803                             activity.runOnUiThread(() -> {
5804                                 // Update the menu item titles.
5805                                 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5806
5807                                 // Update the options menu if it has been populated.
5808                                 if (optionsMenu != null) {
5809                                     optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5810                                     optionsMenu.findItem(R.id.easylist).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASYLIST) + " - " + getString(R.string.easylist));
5811                                 }
5812                             });
5813                         }
5814
5815                         // The resource request was blocked.  Return an empty web resource response.
5816                         return emptyWebResourceResponse;
5817                     } else if (easyListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) {  // The resource request matched EasyList's whitelist.
5818                         // Update the whitelist result string array tracker.
5819                         whitelistResultStringArray = new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]};
5820                     }
5821                 }
5822
5823                 // Check EasyPrivacy if it is enabled.
5824                 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY)) {
5825                     // Check the URL against EasyPrivacy.
5826                     String[] easyPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyPrivacy);
5827
5828                     // Process the EasyPrivacy results.
5829                     if (easyPrivacyResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) {  // The resource request matched EasyPrivacy's blacklist.
5830                         // Add the result to the resource requests.
5831                         nestedScrollWebView.addResourceRequest(new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4],
5832                                 easyPrivacyResults[5]});
5833
5834                         // Increment the blocked requests counters.
5835                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5836                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASYPRIVACY);
5837
5838                         // Update the titles of the blocklist menu items if the WebView is currently displayed.
5839                         if (webViewDisplayed) {
5840                             // Updating the UI must be run from the UI thread.
5841                             activity.runOnUiThread(() -> {
5842                                 // Update the menu item titles.
5843                                 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5844
5845                                 // Update the options menu if it has been populated.
5846                                 if (optionsMenu != null) {
5847                                     optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5848                                     optionsMenu.findItem(R.id.easyprivacy).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASYPRIVACY) + " - " + getString(R.string.easyprivacy));
5849                                 }
5850                             });
5851                         }
5852
5853                         // The resource request was blocked.  Return an empty web resource response.
5854                         return emptyWebResourceResponse;
5855                     } else if (easyPrivacyResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) {  // The resource request matched EasyPrivacy's whitelist.
5856                         // Update the whitelist result string array tracker.
5857                         whitelistResultStringArray = new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5]};
5858                     }
5859                 }
5860
5861                 // Check Fanboy’s Annoyance List if it is enabled.
5862                 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST)) {
5863                     // Check the URL against Fanboy's Annoyance List.
5864                     String[] fanboysAnnoyanceListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList);
5865
5866                     // Process the Fanboy's Annoyance List results.
5867                     if (fanboysAnnoyanceListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) {  // The resource request matched Fanboy's Annoyance List's blacklist.
5868                         // Add the result to the resource requests.
5869                         nestedScrollWebView.addResourceRequest(new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5870                                 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]});
5871
5872                         // Increment the blocked requests counters.
5873                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5874                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST);
5875
5876                         // Update the titles of the blocklist menu items if the WebView is currently displayed.
5877                         if (webViewDisplayed) {
5878                             // Updating the UI must be run from the UI thread.
5879                             activity.runOnUiThread(() -> {
5880                                 // Update the menu item titles.
5881                                 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5882
5883                                 // Update the options menu if it has been populated.
5884                                 if (optionsMenu != null) {
5885                                     optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5886                                     optionsMenu.findItem(R.id.fanboys_annoyance_list).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " +
5887                                             getString(R.string.fanboys_annoyance_list));
5888                                 }
5889                             });
5890                         }
5891
5892                         // The resource request was blocked.  Return an empty web resource response.
5893                         return emptyWebResourceResponse;
5894                     } else if (fanboysAnnoyanceListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)){  // The resource request matched Fanboy's Annoyance List's whitelist.
5895                         // Update the whitelist result string array tracker.
5896                         whitelistResultStringArray = new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5897                                 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]};
5898                     }
5899                 } else if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST)) {  // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
5900                     // Check the URL against Fanboy's Annoyance List.
5901                     String[] fanboysSocialListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysSocialList);
5902
5903                     // Process the Fanboy's Social Blocking List results.
5904                     if (fanboysSocialListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) {  // The resource request matched Fanboy's Social Blocking List's blacklist.
5905                         // Add the result to the resource requests.
5906                         nestedScrollWebView.addResourceRequest(new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5907                                 fanboysSocialListResults[4], fanboysSocialListResults[5]});
5908
5909                         // Increment the blocked requests counters.
5910                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5911                         nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST);
5912
5913                         // Update the titles of the blocklist menu items if the WebView is currently displayed.
5914                         if (webViewDisplayed) {
5915                             // Updating the UI must be run from the UI thread.
5916                             activity.runOnUiThread(() -> {
5917                                 // Update the menu item titles.
5918                                 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5919
5920                                 // Update the options menu if it has been populated.
5921                                 if (optionsMenu != null) {
5922                                     optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5923                                     optionsMenu.findItem(R.id.fanboys_social_blocking_list).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " +
5924                                             getString(R.string.fanboys_social_blocking_list));
5925                                 }
5926                             });
5927                         }
5928
5929                         // The resource request was blocked.  Return an empty web resource response.
5930                         return emptyWebResourceResponse;
5931                     } else if (fanboysSocialListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) {  // The resource request matched Fanboy's Social Blocking List's whitelist.
5932                         // Update the whitelist result string array tracker.
5933                         whitelistResultStringArray = new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5934                                 fanboysSocialListResults[4], fanboysSocialListResults[5]};
5935                     }
5936                 }
5937
5938                 // Add the request to the log because it hasn't been processed by any of the previous checks.
5939                 if (whitelistResultStringArray != null) {  // The request was processed by a whitelist.
5940                     nestedScrollWebView.addResourceRequest(whitelistResultStringArray);
5941                 } else {  // The request didn't match any blocklist entry.  Log it as a default request.
5942                     nestedScrollWebView.addResourceRequest(new String[]{BlocklistHelper.REQUEST_DEFAULT, url});
5943                 }
5944
5945                 // The resource request has not been blocked.  `return null` loads the requested resource.
5946                 return null;
5947             }
5948
5949             // Handle HTTP authentication requests.
5950             @Override
5951             public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
5952                 // Store the handler.
5953                 nestedScrollWebView.setHttpAuthHandler(handler);
5954
5955                 // Instantiate an HTTP authentication dialog.
5956                 DialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm, nestedScrollWebView.getWebViewFragmentId());
5957
5958                 // Show the HTTP authentication dialog.
5959                 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
5960             }
5961
5962             @Override
5963             public void onPageStarted(WebView view, String url, Bitmap favicon) {
5964                 // Get the preferences.
5965                 boolean scrollAppBar = sharedPreferences.getBoolean("scroll_app_bar", true);
5966                 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
5967
5968                 // Get a handler for the app bar layout.
5969                 AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
5970
5971                 // Set the top padding of the swipe refresh layout according to the app bar scrolling preference.
5972                 if (scrollAppBar) {
5973                     // No padding is needed because it will automatically be placed below the app bar layout due to the scrolling layout behavior.
5974                     swipeRefreshLayout.setPadding(0, 0, 0, 0);
5975
5976                     // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5977                     swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10, defaultProgressViewEndOffset);
5978                 } else {
5979                     // Get the app bar layout height.  This can't be done in `applyAppSettings()` because the app bar is not yet populated.
5980                     int appBarHeight = appBarLayout.getHeight();
5981
5982                     // The swipe refresh layout must be manually moved below the app bar layout.
5983                     swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0);
5984
5985                     // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5986                     swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight);
5987                 }
5988
5989                 // Reset the list of resource requests.
5990                 nestedScrollWebView.clearResourceRequests();
5991
5992                 // Reset the requests counters.
5993                 nestedScrollWebView.resetRequestsCounters();
5994
5995                 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
5996                 if (nestedScrollWebView.getNightMode()) {
5997                     nestedScrollWebView.setVisibility(View.INVISIBLE);
5998                 } else {
5999                     nestedScrollWebView.setVisibility(View.VISIBLE);
6000                 }
6001
6002                 // Hide the keyboard.
6003                 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
6004
6005                 // Get the current page position.
6006                 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
6007
6008                 // Update the URL text bar if the page is currently selected.
6009                 if (tabLayout.getSelectedTabPosition() == currentPagePosition) {
6010                     // Clear the focus from the URL edit text.
6011                     urlEditText.clearFocus();
6012
6013                     // Display the formatted URL text.
6014                     urlEditText.setText(url);
6015
6016                     // Apply text highlighting to `urlTextBox`.
6017                     highlightUrlText();
6018                 }
6019
6020                 // Reset the list of host IP addresses.
6021                 nestedScrollWebView.clearCurrentIpAddresses();
6022
6023                 // Get a URI for the current URL.
6024                 Uri currentUri = Uri.parse(url);
6025
6026                 // Get the IP addresses for the host.
6027                 new GetHostIpAddresses(activity, getSupportFragmentManager(), nestedScrollWebView).execute(currentUri.getHost());
6028
6029                 // Replace Refresh with Stop if the options menu has been created.  (The first WebView typically begins loading before the menu items are instantiated.)
6030                 if (optionsMenu != null) {
6031                     // Get a handle for the refresh menu item.
6032                     MenuItem refreshMenuItem = optionsMenu.findItem(R.id.refresh);
6033
6034                     // Set the title.
6035                     refreshMenuItem.setTitle(R.string.stop);
6036
6037                     // Get the app bar and theme preferences.
6038                     boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
6039
6040                     // If the icon is displayed in the AppBar, set it according to the theme.
6041                     if (displayAdditionalAppBarIcons) {
6042                         if (darkTheme) {
6043                             refreshMenuItem.setIcon(R.drawable.close_dark);
6044                         } else {
6045                             refreshMenuItem.setIcon(R.drawable.close_light);
6046                         }
6047                     }
6048                 }
6049             }
6050
6051             @Override
6052             public void onPageFinished(WebView view, String url) {
6053                 // Flush any cookies to persistent storage.  The cookie manager has become very lazy about flushing cookies in recent versions.
6054                 if (nestedScrollWebView.getAcceptFirstPartyCookies() && Build.VERSION.SDK_INT >= 21) {
6055                     CookieManager.getInstance().flush();
6056                 }
6057
6058                 // Update the Refresh menu item if the options menu has been created.
6059                 if (optionsMenu != null) {
6060                     // Get a handle for the refresh menu item.
6061                     MenuItem refreshMenuItem = optionsMenu.findItem(R.id.refresh);
6062
6063                     // Reset the Refresh title.
6064                     refreshMenuItem.setTitle(R.string.refresh);
6065
6066                     // Get the app bar and theme preferences.
6067                     boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
6068                     boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
6069
6070                     // If the icon is displayed in the AppBar, reset it according to the theme.
6071                     if (displayAdditionalAppBarIcons) {
6072                         if (darkTheme) {
6073                             refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
6074                         } else {
6075                             refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
6076                         }
6077                     }
6078                 }
6079
6080                 // Clear the cache and history if Incognito Mode is enabled.
6081                 if (incognitoModeEnabled) {
6082                     // Clear the cache.  `true` includes disk files.
6083                     nestedScrollWebView.clearCache(true);
6084
6085                     // Clear the back/forward history.
6086                     nestedScrollWebView.clearHistory();
6087
6088                     // Manually delete cache folders.
6089                     try {
6090                         // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
6091                         // which links to `/data/data/com.stoutner.privacybrowser.standard`.
6092                         String privateDataDirectoryString = getApplicationInfo().dataDir;
6093
6094                         // Delete the main cache directory.
6095                         Runtime.getRuntime().exec("rm -rf " + privateDataDirectoryString + "/cache");
6096
6097                         // Delete the secondary `Service Worker` cache directory.
6098                         // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
6099                         Runtime.getRuntime().exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
6100                     } catch (IOException e) {
6101                         // Do nothing if an error is thrown.
6102                     }
6103                 }
6104
6105                 // Get the current page position.
6106                 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
6107
6108                 // Check the current website information against any pinned domain information if the current IP addresses have been loaded.
6109                 if ((nestedScrollWebView.hasPinnedSslCertificate() || nestedScrollWebView.hasPinnedIpAddresses()) && nestedScrollWebView.hasCurrentIpAddresses() &&
6110                         !nestedScrollWebView.ignorePinnedDomainInformation()) {
6111                     CheckPinnedMismatchHelper.checkPinnedMismatch(getSupportFragmentManager(), nestedScrollWebView);
6112                 }
6113
6114                 // 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.
6115                 String currentUrl = nestedScrollWebView.getUrl();
6116
6117                 // Get the current tab.
6118                 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
6119
6120                 // Update the URL text bar if the page is currently selected and the user is not currently typing in the URL edit text.
6121                 // Crash records show that, in some crazy way, it is possible for the current URL to be blank at this point.
6122                 // Probably some sort of race condition when Privacy Browser is being resumed.
6123                 if ((tabLayout.getSelectedTabPosition() == currentPagePosition) && !urlEditText.hasFocus() && (currentUrl != null)) {
6124                     // Check to see if the URL is `about:blank`.
6125                     if (currentUrl.equals("about:blank")) {  // The WebView is blank.
6126                         // Display the hint in the URL edit text.
6127                         urlEditText.setText("");
6128
6129                         // Request focus for the URL text box.
6130                         urlEditText.requestFocus();
6131
6132                         // Display the keyboard.
6133                         inputMethodManager.showSoftInput(urlEditText, 0);
6134
6135                         // Apply the domain settings.  This clears any settings from the previous domain.
6136                         applyDomainSettings(nestedScrollWebView, "", true, false);
6137
6138                         // Only populate the title text view if the tab has been fully created.
6139                         if (tab != null) {
6140                             // Get the custom view from the tab.
6141                             View tabView = tab.getCustomView();
6142
6143                             // Remove the incorrect warning below that the current tab view might be null.
6144                             assert tabView != null;
6145
6146                             // Get the title text view from the tab.
6147                             TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
6148
6149                             // Set the title as the tab text.
6150                             tabTitleTextView.setText(R.string.new_tab);
6151                         }
6152                     } else {  // The WebView has loaded a webpage.
6153                         // Update the URL edit text if it is not currently being edited.
6154                         if (!urlEditText.hasFocus()) {
6155                             // 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.
6156                             String sanitizedUrl = sanitizeUrl(currentUrl);
6157
6158                             // Display the final URL.  Getting the URL from the WebView instead of using the one provided by `onPageFinished()` makes websites like YouTube function correctly.
6159                             urlEditText.setText(sanitizedUrl);
6160
6161                             // Apply text highlighting to the URL.
6162                             highlightUrlText();
6163                         }
6164
6165                         // Only populate the title text view if the tab has been fully created.
6166                         if (tab != null) {
6167                             // Get the custom view from the tab.
6168                             View tabView = tab.getCustomView();
6169
6170                             // Remove the incorrect warning below that the current tab view might be null.
6171                             assert tabView != null;
6172
6173                             // Get the title text view from the tab.
6174                             TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
6175
6176                             // Set the title as the tab text.  Sometimes `onReceivedTitle()` is not called, especially when navigating history.
6177                             tabTitleTextView.setText(nestedScrollWebView.getTitle());
6178                         }
6179                     }
6180                 }
6181             }
6182
6183             // Handle SSL Certificate errors.
6184             @Override
6185             public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
6186                 // Get the current website SSL certificate.
6187                 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
6188
6189                 // Extract the individual pieces of information from the current website SSL certificate.
6190                 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
6191                 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
6192                 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
6193                 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
6194                 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
6195                 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
6196                 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
6197                 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
6198
6199                 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
6200                 if (nestedScrollWebView.hasPinnedSslCertificate()) {
6201                     // Get the pinned SSL certificate.
6202                     ArrayList<Object> pinnedSslCertificateArrayList = nestedScrollWebView.getPinnedSslCertificate();
6203
6204                     // Extract the arrays from the array list.
6205                     String[] pinnedSslCertificateStringArray = (String[]) pinnedSslCertificateArrayList.get(0);
6206                     Date[] pinnedSslCertificateDateArray = (Date[]) pinnedSslCertificateArrayList.get(1);
6207
6208                     // Check if the current SSL certificate matches the pinned certificate.
6209                     if (currentWebsiteIssuedToCName.equals(pinnedSslCertificateStringArray[0]) && currentWebsiteIssuedToOName.equals(pinnedSslCertificateStringArray[1]) &&
6210                         currentWebsiteIssuedToUName.equals(pinnedSslCertificateStringArray[2]) && currentWebsiteIssuedByCName.equals(pinnedSslCertificateStringArray[3]) &&
6211                         currentWebsiteIssuedByOName.equals(pinnedSslCertificateStringArray[4]) && currentWebsiteIssuedByUName.equals(pinnedSslCertificateStringArray[5]) &&
6212                         currentWebsiteSslStartDate.equals(pinnedSslCertificateDateArray[0]) && currentWebsiteSslEndDate.equals(pinnedSslCertificateDateArray[1])) {
6213
6214                         // An SSL certificate is pinned and matches the current domain certificate.  Proceed to the website without displaying an error.
6215                         handler.proceed();
6216                     }
6217                 } else {  // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
6218                     // Store the SSL error handler.
6219                     nestedScrollWebView.setSslErrorHandler(handler);
6220
6221                     // Instantiate an SSL certificate error alert dialog.
6222                     DialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error, nestedScrollWebView.getWebViewFragmentId());
6223
6224                     // Show the SSL certificate error dialog.
6225                     sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
6226                 }
6227             }
6228         });
6229
6230         // Check to see if this is the first page.
6231         if (pageNumber == 0) {
6232             // Set this nested scroll WebView as the current WebView.
6233             currentWebView = nestedScrollWebView;
6234
6235             // Apply the app settings from the shared preferences.
6236             applyAppSettings();
6237
6238             // Initialize the URL to load string.
6239             String urlToLoadString;
6240
6241             // Get the intent that started the app.
6242             Intent launchingIntent = getIntent();
6243
6244             // Get the information from the intent.
6245             String launchingIntentAction = launchingIntent.getAction();
6246             Uri launchingIntentUriData = launchingIntent.getData();
6247
6248             // Parse the launching intent URL.
6249             if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) {  // The intent contains a search string.
6250                 // Create an encoded URL string.
6251                 String encodedUrlString;
6252
6253                 // Sanitize the search input and convert it to a search.
6254                 try {
6255                     encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
6256                 } catch (UnsupportedEncodingException exception) {
6257                     encodedUrlString = "";
6258                 }
6259
6260                 // Store the web search as the URL to load.
6261                 urlToLoadString = searchURL + encodedUrlString;
6262             } else if (launchingIntentUriData != null){  // The intent contains a URL.
6263                 // Store the URL.
6264                 urlToLoadString = launchingIntentUriData.toString();
6265             } else {  // The is no URL in the intent.
6266                 // Store the homepage to be loaded.
6267                 urlToLoadString = sharedPreferences.getString("homepage", getString(R.string.homepage_default_value));
6268             }
6269
6270             // Load the website if not waiting for the proxy.
6271             if (waitingForProxy) {  // Store the URL to be loaded in the Nested Scroll WebView.
6272                 nestedScrollWebView.setWaitingForProxyUrlString(urlToLoadString);
6273             } else {  // Load the URL.
6274                 loadUrl(nestedScrollWebView, urlToLoadString);
6275             }
6276         } else {  // This is not the first tab.
6277             // Apply the domain settings.
6278             applyDomainSettings(nestedScrollWebView, url, false, false);
6279
6280             // Load the URL.
6281             nestedScrollWebView.loadUrl(url, customHeaders);
6282
6283             // Set the focus and display the keyboard if the URL is blank.
6284             if (url.equals("")) {
6285                 // Request focus for the URL text box.
6286                 urlEditText.requestFocus();
6287
6288                 // Create a display keyboard handler.
6289                 Handler displayKeyboardHandler = new Handler();
6290
6291                 // Create a display keyboard runnable.
6292                 Runnable displayKeyboardRunnable = () -> {
6293                     // Display the keyboard.
6294                     inputMethodManager.showSoftInput(urlEditText, 0);
6295                 };
6296
6297                 // Display the keyboard after 100 milliseconds, which leaves enough time for the tab to transition.
6298                 displayKeyboardHandler.postDelayed(displayKeyboardRunnable, 100);
6299             }
6300         }
6301     }
6302 }