]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blobdiff - app/src/main/java/com/stoutner/privacybrowser/activities/MainWebViewActivity.kt
Update the proxy app bar background color. https://redmine.stoutner.com/issues/998
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / activities / MainWebViewActivity.kt
index 0c7035407713416421ca510ff91f1d59e282674f..e13e8567c5c7475805f66e9eec3260b2c8b38abf 100644 (file)
@@ -137,8 +137,12 @@ import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog
 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog
 import com.stoutner.privacybrowser.dialogs.WaitingForProxyDialog
 import com.stoutner.privacybrowser.fragments.WebViewTabFragment
-import com.stoutner.privacybrowser.helpers.BlocklistHelper
+import com.stoutner.privacybrowser.helpers.REQUEST_ALLOWED
+import com.stoutner.privacybrowser.helpers.REQUEST_BLOCKED
+import com.stoutner.privacybrowser.helpers.REQUEST_DEFAULT
+import com.stoutner.privacybrowser.helpers.REQUEST_THIRD_PARTY
 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper
+import com.stoutner.privacybrowser.helpers.CheckBlocklistHelper
 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper
 import com.stoutner.privacybrowser.helpers.ProxyHelper
 import com.stoutner.privacybrowser.helpers.SanitizeUrlHelper
@@ -195,8 +199,6 @@ private const val SAVED_STATE_ARRAY_LIST = "saved_state_array_list"
 private const val SAVED_TAB_POSITION = "saved_tab_position"
 private const val TEMPORARY_MHT_FILE = "temporary_mht_file"
 
-// TODO.  Reorder methods alphabetically.
-
 class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener, FontSizeDialog.UpdateFontSizeListener,
     NavigationView.OnNavigationItemSelectedListener, OpenDialog.OpenListener, PinnedMismatchDialog.PinnedMismatchListener, PopulateBlocklistsCoroutine.PopulateBlocklistsListener, SaveDialog.SaveListener,
     UrlHistoryDialog.NavigateHistoryListener, WebViewTabFragment.NewTabListener {
@@ -217,12 +219,14 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
 
     // Declare the class variables.
     private lateinit var appBar: ActionBar
+    private lateinit var checkBlocklistHelper: CheckBlocklistHelper
     private lateinit var bookmarksCursorAdapter: CursorAdapter
     private lateinit var bookmarksListView: ListView
     private lateinit var bookmarksDrawerPinnedImageView: ImageView
     private lateinit var bookmarksTitleTextView: TextView
     private lateinit var coordinatorLayout: CoordinatorLayout
     private lateinit var cookieManager: CookieManager
+    private lateinit var domainsSettingsSet: MutableSet<String>
     private lateinit var drawerLayout: DrawerLayout
     private lateinit var easyList: ArrayList<List<Array<String>>>
     private lateinit var easyPrivacy: ArrayList<List<Array<String>>>
@@ -331,6 +335,12 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
     private var ultraPrivacy: ArrayList<List<Array<String>>>? = null
     private var waitingForProxy = false
 
+    // Define the save webpage image activity result launcher.  It must be defined before `onCreate()` is run or the app will crash.
+    private val browseFileUploadActivityResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { activityResult ->
+        // Pass the file to the WebView.
+        fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(activityResult.resultCode, activityResult.data))
+    }
+
     // Define the save URL activity result launcher.  It must be defined before `onCreate()` is run or the app will crash.
     private val saveUrlActivityResultLauncher = registerForActivityResult<String, Uri>(ActivityResultContracts.CreateDocument("*/*")) { fileUri ->
         // Only save the URL if the file URI is not null, which happens if the user exited the file picker by pressing back.
@@ -437,12 +447,6 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
         }
     }
 
-    // Define the save webpage image activity result launcher.  It must be defined before `onCreate()` is run or the app will crash.
-    private val browseFileUploadActivityResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { activityResult ->
-        // Pass the file to the WebView.
-        fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(activityResult.resultCode, activityResult.data))
-    }
-
     override fun onCreate(savedInstanceState: Bundle?) {
         // Run the default commands.
         super.onCreate(savedInstanceState)
@@ -624,12 +628,9 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
 
                         // Go back.
                         currentWebView!!.goBack()
-                    } else if (tabLayout.tabCount > 1) {  // There are at least two tabs.
-                        // Close the current tab.
-                        closeCurrentTab()
-                    } else {  // There isn't anything to do in Privacy Browser.
-                        // Run clear and exit.
-                        clearAndExit()
+                    } else {  // Close the current tab.
+                        // A view is required because the method is also called by an XML `onClick`.
+                        closeTab(null)
                     }
                 }
             }
@@ -645,6 +646,15 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
         }
     }
 
+    public override fun onPostCreate(savedInstanceState: Bundle?) {
+        // Run the default commands.
+        super.onPostCreate(savedInstanceState)
+
+        // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished.  This creates the navigation drawer icon.
+        // If the app is restarting to change the app theme the action bar drawer toggle will not yet be populated.
+        actionBarDrawerToggle?.syncState()
+    }
+
     override fun onNewIntent(intent: Intent) {
         // Run the default commands.
         super.onNewIntent(intent)
@@ -734,6 +744,9 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
             // Reset the reapply domain settings on restart flag.
             reapplyDomainSettingsOnRestart = false
 
+            // Update the domains settings set.
+            updateDomainsSettingsSet()
+
             // Reapply the domain settings for each tab.
             for (i in 0 until webViewPagerAdapter!!.count) {
                 // Get the WebView tab fragment.
@@ -833,37 +846,6 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
         pendingDialogsArrayList.clear()
     }
 
-    // `onStop()` runs after `onPause()`.  It is used instead of `onPause()` so the commands are not called every time the screen is partially hidden.
-    public override fun onStop() {
-        // Run the default commands.
-        super.onStop()
-
-        // Only pause the WebViews if the pager adapter is not null, which is the case if the app is restarting to change the initial app theme.
-        if (webViewPagerAdapter != null) {
-            // Pause each web view.
-            for (i in 0 until webViewPagerAdapter!!.count) {
-                // Get the WebView tab fragment.
-                val webViewTabFragment = webViewPagerAdapter!!.getPageFragment(i)
-
-                // Get the fragment view.
-                val fragmentView = webViewTabFragment.view
-
-                // Only pause the WebViews if they exist (they won't when the app is first created).
-                if (fragmentView != null) {
-                    // Get the nested scroll WebView from the tab fragment.
-                    val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
-
-                    // Pause the nested scroll WebView.
-                    nestedScrollWebView.onPause()
-                }
-            }
-        }
-
-        // Pause the WebView JavaScript timers.  This is a global command that pauses JavaScript on all WebViews.
-        if (currentWebView != null)
-            currentWebView!!.pauseTimers()
-    }
-
     public override fun onSaveInstanceState(savedInstanceState: Bundle) {
         // Run the default commands.
         super.onSaveInstanceState(savedInstanceState)
@@ -912,6 +894,37 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
         }
     }
 
+    // `onStop()` runs after `onPause()`.  It is used instead of `onPause()` so the commands are not called every time the screen is partially hidden.
+    public override fun onStop() {
+        // Run the default commands.
+        super.onStop()
+
+        // Only pause the WebViews if the pager adapter is not null, which is the case if the app is restarting to change the initial app theme.
+        if (webViewPagerAdapter != null) {
+            // Pause each web view.
+            for (i in 0 until webViewPagerAdapter!!.count) {
+                // Get the WebView tab fragment.
+                val webViewTabFragment = webViewPagerAdapter!!.getPageFragment(i)
+
+                // Get the fragment view.
+                val fragmentView = webViewTabFragment.view
+
+                // Only pause the WebViews if they exist (they won't when the app is first created).
+                if (fragmentView != null) {
+                    // Get the nested scroll WebView from the tab fragment.
+                    val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
+
+                    // Pause the nested scroll WebView.
+                    nestedScrollWebView.onPause()
+                }
+            }
+        }
+
+        // Pause the WebView JavaScript timers.  This is a global command that pauses JavaScript on all WebViews.
+        if (currentWebView != null)
+            currentWebView!!.pauseTimers()
+    }
+
     public override fun onDestroy() {
         // Unregister the orbot status broadcast receiver if it exists.
         if (orbotStatusBroadcastReceiver != null) {
@@ -919,11 +932,9 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
         }
 
         // Close the bookmarks cursor if it exists.
-        if (bookmarksCursor != null) {
-            bookmarksCursor!!.close()
-        }
+        bookmarksCursor?.close()
 
-        // Close the databases database if it exists.
+        // Close the databases if they exist.
         bookmarksDatabaseHelper?.close()
         domainsDatabaseHelper?.close()
 
@@ -2334,15 +2345,6 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
         return true
     }
 
-    public override fun onPostCreate(savedInstanceState: Bundle?) {
-        // Run the default commands.
-        super.onPostCreate(savedInstanceState)
-
-        // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished.  This creates the navigation drawer icon.
-        // If the app is restarting to change the app theme the action bar drawer toggle will not yet be populated.
-        actionBarDrawerToggle?.syncState()
-    }
-
     override fun onCreateContextMenu(contextMenu: ContextMenu, view: View, contextMenuInfo: ContextMenu.ContextMenuInfo?) {
         // Get the hit test result.
         val hitTestResult = currentWebView!!.hitTestResult
@@ -2666,3252 +2668,3259 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
         }
     }
 
-    override fun onCreateBookmark(dialogFragment: DialogFragment, favoriteIconBitmap: Bitmap) {
-        // Get the dialog.
-        val dialog = dialogFragment.dialog!!
-
-        // Get the views from the dialog fragment.
-        val createBookmarkNameEditText = dialog.findViewById<EditText>(R.id.create_bookmark_name_edittext)
-        val createBookmarkUrlEditText = dialog.findViewById<EditText>(R.id.create_bookmark_url_edittext)
-
-        // Extract the strings from the edit texts.
-        val bookmarkNameString = createBookmarkNameEditText.text.toString()
-        val bookmarkUrlString = createBookmarkUrlEditText.text.toString()
+    // The view parameter cannot be removed because it is called from the layout onClick.
+    fun addTab(@Suppress("UNUSED_PARAMETER")view: View?) {
+        // Add a new tab with a blank URL.
+        addNewTab("", true)
+    }
 
-        // Create a favorite icon byte array output stream.
-        val favoriteIconByteArrayOutputStream = ByteArrayOutputStream()
+    private fun addNewTab(urlString: String, moveToTab: Boolean) {
+        // Clear the focus from the URL edit text, so that it will be populated with the information from the new tab.
+        urlEditText.clearFocus()
 
-        // Convert the favorite icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
-        favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream)
+        // Get the new page number.  The page numbers are 0 indexed, so the new page number will match the current count.
+        val newTabNumber = tabLayout.tabCount
 
-        // Convert the favorite icon byte array stream to a byte array.
-        val favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray()
+        // Add a new tab.
+        tabLayout.addTab(tabLayout.newTab())
 
-        // Display the new bookmark below the current items in the (0 indexed) list.
-        val newBookmarkDisplayOrder = bookmarksListView.count
+        // Get the new tab.
+        val newTab = tabLayout.getTabAt(newTabNumber)!!
 
-        // Create the bookmark.
-        bookmarksDatabaseHelper!!.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray)
+        // Set a custom view on the new tab.
+        newTab.setCustomView(R.layout.tab_custom_view)
 
-        // Update the bookmarks cursor with the current contents of this folder.
-        bookmarksCursor = bookmarksDatabaseHelper!!.getBookmarksByDisplayOrder(currentBookmarksFolder)
+        // Add the new WebView page.
+        webViewPagerAdapter!!.addPage(newTabNumber, webViewPager, urlString, moveToTab)
 
-        // Update the list view.
-        bookmarksCursorAdapter.changeCursor(bookmarksCursor)
+        // Show the app bar if it is at the bottom of the screen and the new tab is taking focus.
+        if (bottomAppBar && moveToTab && appBarLayout.translationY != 0f) {
+            // Animate the bottom app bar onto the screen.
+            objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0f)
 
-        // Scroll to the new bookmark.
-        bookmarksListView.setSelection(newBookmarkDisplayOrder)
+            // Make it so.
+            objectAnimator.start()
+        }
     }
 
-    override fun onCreateBookmarkFolder(dialogFragment: DialogFragment, favoriteIconBitmap: Bitmap) {
-        // Get the dialog.
-        val dialog = dialogFragment.dialog!!
+    private fun applyAppSettings() {
+        // Store the values from the shared preferences in variables.
+        incognitoModeEnabled = sharedPreferences.getBoolean(getString(R.string.incognito_mode_key), false)
+        sanitizeTrackingQueries = sharedPreferences.getBoolean(getString(R.string.tracking_queries_key), true)
+        sanitizeAmpRedirects = sharedPreferences.getBoolean(getString(R.string.amp_redirects_key), true)
+        proxyMode = sharedPreferences.getString(getString(R.string.proxy_key), getString(R.string.proxy_default_value))!!
+        fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean(getString(R.string.full_screen_browsing_mode_key), false)
+        hideAppBar = sharedPreferences.getBoolean(getString(R.string.hide_app_bar_key), true)
+        downloadWithExternalApp = sharedPreferences.getBoolean(getString(R.string.download_with_external_app_key), false)
+        scrollAppBar = sharedPreferences.getBoolean(getString(R.string.scroll_app_bar_key), true)
 
-        // Get handles for the views in the dialog fragment.
-        val folderNameEditText = dialog.findViewById<EditText>(R.id.folder_name_edittext)
-        val defaultIconRadioButton = dialog.findViewById<RadioButton>(R.id.default_icon_radiobutton)
-        val defaultIconImageView = dialog.findViewById<ImageView>(R.id.default_icon_imageview)
+        // Apply the saved proxy mode if the app has been restarted.
+        if (savedProxyMode != null) {
+            // Apply the saved proxy mode.
+            proxyMode = savedProxyMode!!
 
-        // Get new folder name string.
-        val folderNameString = folderNameEditText.text.toString()
+            // Reset the saved proxy mode.
+            savedProxyMode = null
+        }
 
-        // Set the folder icon bitmap according to the dialog.
-        val folderIconBitmap: Bitmap = if (defaultIconRadioButton.isChecked) {  // Use the default folder icon.
-            // Get the default folder icon drawable.
-            val folderIconDrawable = defaultIconImageView.drawable
+        // Get the search string.
+        val searchString = sharedPreferences.getString(getString(R.string.search_key), getString(R.string.search_default_value))!!
 
-            // Convert the folder icon drawable to a bitmap drawable.
-            val folderIconBitmapDrawable = folderIconDrawable as BitmapDrawable
+        // Set the search string, using the custom search URL if specified.
+        searchURL = if (searchString == getString(R.string.custom_url_item))
+            sharedPreferences.getString(getString(R.string.search_custom_url_key), getString(R.string.search_custom_url_default_value))!!
+        else
+            searchString
 
-            // Convert the folder icon bitmap drawable to a bitmap.
-            folderIconBitmapDrawable.bitmap
-        } else {  // Use the WebView favorite icon.
-            // Copy the favorite icon bitmap to the folder icon bitmap.
-            favoriteIconBitmap
-        }
+        // Apply the proxy.
+        applyProxy(false)
 
-        // Create a folder icon byte array output stream.
-        val folderIconByteArrayOutputStream = ByteArrayOutputStream()
+        // Adjust the layout and scrolling parameters according to the position of the app bar.
+        if (bottomAppBar) {  // The app bar is on the bottom.
+            // Adjust the UI.
+            if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) {  // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
+                // Reset the WebView padding to fill the available space.
+                swipeRefreshLayout.setPadding(0, 0, 0, 0)
+            } else {  // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
+                // Move the WebView above the app bar layout.
+                swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
 
-        // Convert the folder icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
-        folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream)
+                // Show the app bar if it is scrolled off the screen.
+                if (appBarLayout.translationY != 0f) {
+                    // Animate the bottom app bar onto the screen.
+                    objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0f)
 
-        // Convert the folder icon byte array stream to a byte array.
-        val folderIconByteArray = folderIconByteArrayOutputStream.toByteArray()
+                    // Make it so.
+                    objectAnimator.start()
+                }
+            }
+        } else {  // The app bar is on the top.
+            // Get the current layout parameters.  Using coordinator layout parameters allows the `setBehavior()` command and using app bar layout parameters allows the `setScrollFlags()` command.
+            val swipeRefreshLayoutParams = swipeRefreshLayout.layoutParams as CoordinatorLayout.LayoutParams
+            val toolbarLayoutParams = toolbar.layoutParams as AppBarLayout.LayoutParams
+            val findOnPageLayoutParams = findOnPageLinearLayout.layoutParams as AppBarLayout.LayoutParams
+            val tabsLayoutParams = tabsLinearLayout.layoutParams as AppBarLayout.LayoutParams
 
-        // Move all the bookmarks down one in the display order.
-        for (i in 0 until bookmarksListView.count) {
-            // Get the bookmark database id.
-            val databaseId = bookmarksListView.getItemIdAtPosition(i).toInt()
+            // Add the scrolling behavior to the layout parameters.
+            if (scrollAppBar) {
+                // Enable scrolling of the app bar.
+                swipeRefreshLayoutParams.behavior = AppBarLayout.ScrollingViewBehavior()
+                toolbarLayoutParams.scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS or AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP
+                findOnPageLayoutParams.scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS or AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP
+                tabsLayoutParams.scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS or AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP
+            } else {
+                // Disable scrolling of the app bar.
+                swipeRefreshLayoutParams.behavior = null
+                toolbarLayoutParams.scrollFlags = 0
+                findOnPageLayoutParams.scrollFlags = 0
+                tabsLayoutParams.scrollFlags = 0
 
-            // Move the bookmark down one slot.
-            bookmarksDatabaseHelper!!.updateDisplayOrder(databaseId, i + 1)
-        }
+                // Expand the app bar if it is currently collapsed.
+                appBarLayout.setExpanded(true)
+            }
 
-        // Create the folder, which will be placed at the top of the list view.
-        bookmarksDatabaseHelper!!.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray)
+            // Set the app bar scrolling for each WebView.
+            for (i in 0 until webViewPagerAdapter!!.count) {
+                // Get the WebView tab fragment.
+                val webViewTabFragment = webViewPagerAdapter!!.getPageFragment(i)
 
-        // Update the bookmarks cursor with the current contents of this folder.
-        bookmarksCursor = bookmarksDatabaseHelper!!.getBookmarksByDisplayOrder(currentBookmarksFolder)
+                // Get the fragment view.
+                val fragmentView = webViewTabFragment.view
 
-        // Update the list view.
-        bookmarksCursorAdapter.changeCursor(bookmarksCursor)
-
-        // Scroll to the new folder.
-        bookmarksListView.setSelection(0)
-    }
-
-    private fun loadUrlFromTextBox() {
-        // Get the text from URL text box and convert it to a string.  trim() removes white spaces from the beginning and end of the string.
-        var unformattedUrlString = urlEditText.text.toString().trim { it <= ' ' }
-
-        // Create the formatted URL string.
-        var urlString = ""
+                // Only modify the WebViews if they exist.
+                if (fragmentView != null) {
+                    // Get the nested scroll WebView from the tab fragment.
+                    val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
 
-        // Check to see if the unformatted URL string is a valid URL.  Otherwise, convert it into a search.
-        if (unformattedUrlString.startsWith("content://")) {  // This is a content URL.
-            // Load the entire content URL.
-            urlString = unformattedUrlString
-        } else if (Patterns.WEB_URL.matcher(unformattedUrlString).matches() || unformattedUrlString.startsWith("http://") || unformattedUrlString.startsWith("https://") ||
-            unformattedUrlString.startsWith("file://")) {  // This is a standard URL.
+                    // Set the app bar scrolling.
+                    nestedScrollWebView.isNestedScrollingEnabled = scrollAppBar
+                }
+            }
+        }
 
-            // Add `https://` at the beginning if there is no protocol.  Otherwise the app will segfault.
-            if (!unformattedUrlString.startsWith("http") && !unformattedUrlString.startsWith("file://"))
-                unformattedUrlString = "https://$unformattedUrlString"
+        // Update the full screen browsing mode settings.
+        if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {  // Privacy Browser is currently in full screen browsing mode.
+            // Update the visibility of the app bar, which might have changed in the settings.
+            if (hideAppBar) {
+                // Hide the tab linear layout.
+                tabsLinearLayout.visibility = View.GONE
 
-            // Initialize the unformatted URL.
-            var unformattedUrl: URL? = null
+                // Hide the app bar.
+                appBar.hide()
+            } else {
+                // Show the tab linear layout.
+                tabsLinearLayout.visibility = View.VISIBLE
 
-            // Convert the unformatted URL string to a URL.
-            try {
-                unformattedUrl = URL(unformattedUrlString)
-            } catch (exception: MalformedURLException) {
-                exception.printStackTrace()
+                // Show the app bar.
+                appBar.show()
             }
 
-            // Get the components of the URL.
-            val scheme = unformattedUrl?.protocol
-            val authority = unformattedUrl?.authority
-            val path = unformattedUrl?.path
-            val query = unformattedUrl?.query
-            val fragment = unformattedUrl?.ref
+            /* Hide the system bars.
+             * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
+             * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
+             * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
+             * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
+             */
 
-            // Create a URI.
-            val uri = Uri.Builder()
+            // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
+            @Suppress("DEPRECATION")
+            rootFrameLayout.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
+        } else {  // Privacy Browser is not in full screen browsing mode.
+            // 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.
+            inFullScreenBrowsingMode = false
 
-            // Build the URI from the components of the URL.
-            uri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment)
+            // Show the tab linear layout.
+            tabsLinearLayout.visibility = View.VISIBLE
 
-            // Decode the URI as a UTF-8 string in.
-            try {
-                urlString = URLDecoder.decode(uri.build().toString(), "UTF-8")
-            } catch (exception: UnsupportedEncodingException) {
-                // Do nothing.  The formatted URL string will remain blank.
-            }
-        } else if (unformattedUrlString.isNotEmpty()) {  // This is not a URL, but rather a search string.
-            // Sanitize the search input.
-            val encodedSearchString = try {
-                URLEncoder.encode(unformattedUrlString, "UTF-8")
-            } catch (exception: UnsupportedEncodingException) {
-                ""
-            }
+            // Show the app bar.
+            appBar.show()
 
-            // Add the base search URL.
-            urlString = searchURL + encodedSearchString
+            // Remove the `SYSTEM_UI` flags from the root frame layout.  The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
+            @Suppress("DEPRECATION")
+            rootFrameLayout.systemUiVisibility = 0
         }
-
-        // 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.
-        urlEditText.clearFocus()
-
-        // Make it so.
-        loadUrl(currentWebView!!, urlString)
     }
 
-    private fun loadUrl(nestedScrollWebView: NestedScrollWebView, url: String) {
-        // Sanitize the URL.
-        val urlString = sanitizeUrl(url)
-
-        // Apply the domain settings and load the URL.
-        applyDomainSettings(nestedScrollWebView, urlString, resetTab = true, reloadWebsite = false, loadUrl = true)
-    }
+    // `reloadWebsite` is used if returning from the Domains activity.  Otherwise JavaScript might not function correctly if it is newly enabled.
+    @SuppressLint("SetJavaScriptEnabled")
+    private fun applyDomainSettings(nestedScrollWebView: NestedScrollWebView, url: String?, resetTab: Boolean, reloadWebsite: Boolean, loadUrl: Boolean) {
+        // Store the current URL.
+        nestedScrollWebView.currentUrl = url!!
 
-    // The view parameter cannot be removed because it is called from the layout onClick.
-    fun findPreviousOnPage(@Suppress("UNUSED_PARAMETER")view: View?) {
-        // Go to the previous highlighted phrase on the page.  `false` goes backwards instead of forwards.
-        currentWebView!!.findNext(false)
-    }
+        // Parse the URL into a URI.
+        val uri = Uri.parse(url)
 
-    // The view parameter cannot be removed because it is called from the layout onClick.
-    fun findNextOnPage(@Suppress("UNUSED_PARAMETER")view: View?) {
-        // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
-        currentWebView!!.findNext(true)
-    }
+        // Extract the domain from the URI.
+        var newHostName = uri.host
 
-    // The view parameter cannot be removed because it is called from the layout onClick.
-    fun closeFindOnPage(@Suppress("UNUSED_PARAMETER")view: View?) {
-        // Delete the contents of the find on page edit text.
-        findOnPageEditText.text = null
+        // Strings don't like to be null.
+        if (newHostName == null)
+            newHostName = ""
 
-        // Clear the highlighted phrases if the WebView is not null.
-        currentWebView?.clearMatches()
+        // 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.
+        if (nestedScrollWebView.currentDomainName != newHostName || newHostName == "") {
+            // Set the new host name as the current domain name.
+            nestedScrollWebView.currentDomainName = newHostName
 
-        // Hide the find on page linear layout.
-        findOnPageLinearLayout.visibility = View.GONE
+            // Reset the ignoring of pinned domain information.
+            nestedScrollWebView.ignorePinnedDomainInformation = false
 
-        // Show the toolbar.
-        toolbar.visibility = View.VISIBLE
+            // Clear any pinned SSL certificate or IP addresses.
+            nestedScrollWebView.clearPinnedSslCertificate()
+            nestedScrollWebView.pinnedIpAddresses = ""
 
-        // Get a handle for the input method manager.
-        val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
+            // Reset the favorite icon if specified.
+            if (resetTab) {
+                // Initialize the favorite icon.
+                nestedScrollWebView.initializeFavoriteIcon()
 
-        // Hide the keyboard.
-        inputMethodManager.hideSoftInputFromWindow(toolbar.windowToken, 0)
-    }
+                // Get the current page position.
+                val currentPagePosition = webViewPagerAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
 
-    override fun onApplyNewFontSize(dialogFragment: DialogFragment) {
-        // Get the dialog.
-        val dialog = dialogFragment.dialog!!
+                // Get the corresponding tab.
+                val tab = tabLayout.getTabAt(currentPagePosition)
 
-        // Get a handle for the font size edit text.
-        val fontSizeEditText = dialog.findViewById<EditText>(R.id.font_size_edittext)
+                // Update the tab if it isn't null, which sometimes happens when restarting from the background.
+                if (tab != null) {
+                    // Get the tab custom view.
+                    val tabCustomView = tab.customView!!
 
-        // Initialize the new font size variable with the current font size.
-        var newFontSize = currentWebView!!.settings.textZoom
+                    // Get the tab views.
+                    val tabFavoriteIconImageView = tabCustomView.findViewById<ImageView>(R.id.favorite_icon_imageview)
+                    val tabTitleTextView = tabCustomView.findViewById<TextView>(R.id.title_textview)
 
-        // Get the font size from the edit text.
-        try {
-            newFontSize = fontSizeEditText.text.toString().toInt()
-        } catch (exception: Exception) {
-            // If the edit text does not contain a valid font size do nothing.
-        }
+                    // Set the default favorite icon as the favorite icon for this tab.
+                    tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nestedScrollWebView.getFavoriteIcon(), 64, 64, true))
 
-        // Apply the new font size.
-        currentWebView!!.settings.textZoom = newFontSize
-    }
+                    // Set the loading title text.
+                    tabTitleTextView.setText(R.string.loading)
+                }
+            }
 
-    override fun onOpen(dialogFragment: DialogFragment) {
-        // Get the dialog.
-        val dialog = dialogFragment.dialog!!
+            // Initialize the domain name in database variable.
+            var domainNameInDatabase: String? = null
 
-        // Get handles for the views.
-        val fileNameEditText = dialog.findViewById<EditText>(R.id.file_name_edittext)
-        val mhtCheckBox = dialog.findViewById<CheckBox>(R.id.mht_checkbox)
+            // Check the hostname against the domain settings set.
+            if (domainsSettingsSet.contains(newHostName)) {  // The hostname is contained in the domain settings set.
+                // Record the domain name in the database.
+                domainNameInDatabase = newHostName
 
-        // Get the file path string.
-        val openFilePath = fileNameEditText.text.toString()
+                // Set the domain settings applied tracker to true.
+                nestedScrollWebView.domainSettingsApplied = true
+            } else {  // The hostname is not contained in the domain settings set.
+                // Set the domain settings applied tracker to false.
+                nestedScrollWebView.domainSettingsApplied = false
+            }
 
-        // Apply the domain settings.  This resets the favorite icon and removes any domain settings.
-        applyDomainSettings(currentWebView!!, openFilePath, resetTab = true, reloadWebsite = false, loadUrl = false)
+            // Check all the subdomains of the host name against wildcard domains in the domain cursor.
+            while (!nestedScrollWebView.domainSettingsApplied && newHostName!!.contains(".")) {  // Stop checking if domain settings are already applied or there are no more `.` in the hostname.
+                if (domainsSettingsSet.contains("*.$newHostName")) {  // Check the host name prepended by `*.`.
+                    // Set the domain settings applied tracker to true.
+                    nestedScrollWebView.domainSettingsApplied = true
 
-        // Open the file according to the type.
-        if (mhtCheckBox.isChecked) {  // Force opening of an MHT file.
-            try {
-                // Get the MHT file input stream.
-                val mhtFileInputStream = contentResolver.openInputStream(Uri.parse(openFilePath))
+                    // Store the applied domain names as it appears in the database.
+                    domainNameInDatabase = "*.$newHostName"
+                }
 
-                // Create a temporary MHT file.
-                val temporaryMhtFile = File.createTempFile(TEMPORARY_MHT_FILE, ".mht", cacheDir)
+                // Strip out the lowest subdomain of of the host name.
+                newHostName = newHostName.substring(newHostName.indexOf(".") + 1)
+            }
 
-                // Get a file output stream for the temporary MHT file.
-                val temporaryMhtFileOutputStream = FileOutputStream(temporaryMhtFile)
+            // Store the general preference information.
+            val defaultFontSizeString = sharedPreferences.getString(getString(R.string.font_size_key), getString(R.string.font_size_default_value))
+            val defaultUserAgentName = sharedPreferences.getString(getString(R.string.user_agent_key), getString(R.string.user_agent_default_value))
+            val defaultSwipeToRefresh = sharedPreferences.getBoolean(getString(R.string.swipe_to_refresh_key), true)
+            val webViewTheme = sharedPreferences.getString(getString(R.string.webview_theme_key), getString(R.string.webview_theme_default_value))
+            val wideViewport = sharedPreferences.getBoolean(getString(R.string.wide_viewport_key), true)
+            val displayWebpageImages = sharedPreferences.getBoolean(getString(R.string.display_webpage_images_key), true)
 
-                // Create a transfer byte array.
-                val transferByteArray = ByteArray(1024)
+            // Get the WebView theme entry values string array.
+            val webViewThemeEntryValuesStringArray = resources.getStringArray(R.array.webview_theme_entry_values)
 
-                // Create an integer to track the number of bytes read.
-                var bytesRead: Int
+            // Initialize the user agent array adapter and string array.
+            val userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item)
+            val userAgentDataArray = resources.getStringArray(R.array.user_agent_data)
 
-                // Copy the temporary MHT file input stream to the MHT output stream.
-                while (mhtFileInputStream!!.read(transferByteArray).also { bytesRead = it } > 0)
-                    temporaryMhtFileOutputStream.write(transferByteArray, 0, bytesRead)
+            // Apply either the domain settings for the default settings.
+            if (nestedScrollWebView.domainSettingsApplied) {  // The url has custom domain settings.
+                // Get a cursor for the current host.
+                val currentDomainSettingsCursor = domainsDatabaseHelper!!.getCursorForDomainName(domainNameInDatabase!!)
 
-                // Flush the temporary MHT file output stream.
-                temporaryMhtFileOutputStream.flush()
+                // Move to the first position.
+                currentDomainSettingsCursor.moveToFirst()
 
-                // Close the streams.
-                temporaryMhtFileOutputStream.close()
-                mhtFileInputStream.close()
-
-                // Load the temporary MHT file.
-                currentWebView!!.loadUrl(temporaryMhtFile.toString())
-            } catch (exception: Exception) {
-                // Display a snackbar.
-                Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
-            }
-        } else {  // Let the WebView handle opening of the file.
-            // Open the file.
-            currentWebView!!.loadUrl(openFilePath)
-        }
-    }
-
-    private fun downloadUrlWithExternalApp(url: String) {
-        // Create a download intent.  Not specifying the action type will display the maximum number of options.
-        val downloadIntent = Intent()
-
-        // Set the URI and the mime type.
-        downloadIntent.setDataAndType(Uri.parse(url), "text/html")
-
-        // Flag the intent to open in a new task.
-        downloadIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
-
-        // Show the chooser.
-        startActivity(Intent.createChooser(downloadIntent, getString(R.string.download_with_external_app)))
-    }
-
-    override fun onSaveUrl(originalUrlString: String, fileNameString: String, dialogFragment: DialogFragment) {
-        // Store the URL.  This will be used in the save URL activity result launcher.
-        saveUrlString = if (originalUrlString.startsWith("data:")) {
-            // Save the original URL.
-            originalUrlString
-        } else {
-            // Get the dialog.
-            val dialog = dialogFragment.dialog!!
-
-            // Get a handle for the dialog URL edit text.
-            val dialogUrlEditText = dialog.findViewById<EditText>(R.id.url_edittext)
-
-            // Get the URL from the edit text, which may have been modified.
-            dialogUrlEditText.text.toString()
-        }
-
-        // Open the file picker.
-        saveUrlActivityResultLauncher.launch(fileNameString)
-    }
-
-    // Remove the warning that `OnTouchListener()` needs to override `performClick()`, as the only purpose of setting the `OnTouchListener()` is to make it do nothing.
-    @SuppressLint("ClickableViewAccessibility")
-    private fun initializeApp() {
-        // Get a handle for the input method.
-        val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
+                // Get the settings from the cursor.
+                nestedScrollWebView.domainSettingsDatabaseId = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ID))
+                nestedScrollWebView.settings.javaScriptEnabled = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1
+                nestedScrollWebView.acceptCookies = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.COOKIES)) == 1
+                nestedScrollWebView.settings.domStorageEnabled = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1
+                // Form data can be removed once the minimum API >= 26.
+                val saveFormData = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1
+                nestedScrollWebView.easyListEnabled = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1
+                nestedScrollWebView.easyPrivacyEnabled = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1
+                nestedScrollWebView.fanboysAnnoyanceListEnabled = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1
+                nestedScrollWebView.fanboysSocialBlockingListEnabled =
+                    currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1
+                nestedScrollWebView.ultraListEnabled = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ULTRALIST)) == 1
+                nestedScrollWebView.ultraPrivacyEnabled = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1
+                nestedScrollWebView.blockAllThirdPartyRequests = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1
+                val userAgentName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.USER_AGENT))
+                val fontSize = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.FONT_SIZE))
+                val swipeToRefreshInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SWIPE_TO_REFRESH))
+                val webViewThemeInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.WEBVIEW_THEME))
+                val wideViewportInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.WIDE_VIEWPORT))
+                val displayWebpageImagesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.DISPLAY_IMAGES))
+                val pinnedSslCertificate = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1
+                val pinnedSslIssuedToCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME))
+                val pinnedSslIssuedToOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION))
+                val pinnedSslIssuedToUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT))
+                val pinnedSslIssuedByCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME))
+                val pinnedSslIssuedByOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION))
+                val pinnedSslIssuedByUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT))
+                val pinnedSslStartDate = Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_START_DATE)))
+                val pinnedSslEndDate = Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_END_DATE)))
+                val pinnedIpAddresses = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.PINNED_IP_ADDRESSES)) == 1
+                val pinnedHostIpAddresses = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.IP_ADDRESSES))
 
-        // Initialize the color spans for highlighting the URLs.
-        initialGrayColorSpan = ForegroundColorSpan(getColor(R.color.gray_500))
-        finalGrayColorSpan = ForegroundColorSpan(getColor(R.color.gray_500))
-        redColorSpan = ForegroundColorSpan(getColor(R.color.red_text))
+                // Close the current host domain settings cursor.
+                currentDomainSettingsCursor.close()
 
-        // Remove the formatting from the URL edit text when the user is editing the text.
-        urlEditText.onFocusChangeListener = View.OnFocusChangeListener { _: View?, hasFocus: Boolean ->
-            if (hasFocus) {  // The user is editing the URL text box.
-                // Remove the syntax highlighting.
-                urlEditText.text.removeSpan(redColorSpan)
-                urlEditText.text.removeSpan(initialGrayColorSpan)
-                urlEditText.text.removeSpan(finalGrayColorSpan)
-            } else {  // The user has stopped editing the URL text box.
-                // Move to the beginning of the string.
-                urlEditText.setSelection(0)
+                // If there is a pinned SSL certificate, store it in the WebView.
+                if (pinnedSslCertificate)
+                    nestedScrollWebView.setPinnedSslCertificate(pinnedSslIssuedToCName, pinnedSslIssuedToOName, pinnedSslIssuedToUName, pinnedSslIssuedByCName, pinnedSslIssuedByOName, pinnedSslIssuedByUName,
+                        pinnedSslStartDate, pinnedSslEndDate)
 
-                // Reapply the syntax highlighting.
-                UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
-            }
-        }
+                // If there is a pinned IP address, store it in the WebView.
+                if (pinnedIpAddresses)
+                    nestedScrollWebView.pinnedIpAddresses = pinnedHostIpAddresses
 
-        // Set the go button on the keyboard to load the URL in url text box.
-        urlEditText.setOnKeyListener { _: View?, keyCode: Int, keyEvent: KeyEvent ->
-            // If the event is a key-down event on the `enter` button, load the URL.
-            if ((keyEvent.action == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {  // The enter key was pressed.
-                // Load the URL.
-                loadUrlFromTextBox()
+                // Apply the cookie domain settings.
+                cookieManager.setAcceptCookie(nestedScrollWebView.acceptCookies)
 
-                // Consume the event.
-                return@setOnKeyListener true
-            } else {  // Some other key was pressed.
-                // Do not consume the event.
-                return@setOnKeyListener false
-            }
-        }
+                // Apply the form data setting if the API < 26.
+                @Suppress("DEPRECATION")
+                if (Build.VERSION.SDK_INT < 26)
+                    nestedScrollWebView.settings.saveFormData = saveFormData
 
-        // Create an Orbot status broadcast receiver.
-        orbotStatusBroadcastReceiver = object : BroadcastReceiver() {
-            override fun onReceive(context: Context, intent: Intent) {
-                // Get the content of the status message.
-                orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS")!!
+                // Apply the font size.
+                try {  // Try the specified font size to see if it is valid.
+                    if (fontSize == 0) {  // Apply the default font size.
+                        // Set the font size from the value in the app settings.
+                        nestedScrollWebView.settings.textZoom = defaultFontSizeString!!.toInt()
+                    } else {  // Apply the font size from domain settings.
+                        nestedScrollWebView.settings.textZoom = fontSize
+                    }
+                } catch (exception: Exception) {  // The specified font size is invalid
+                    // Set the font size to be 100%
+                    nestedScrollWebView.settings.textZoom = 100
+                }
 
-                // If Privacy Browser is waiting on the proxy, load the website now that Orbot is connected.
-                if ((orbotStatus == ProxyHelper.ORBOT_STATUS_ON) && waitingForProxy) {
-                    // Reset the waiting for proxy status.
-                    waitingForProxy = false
+                // Set the user agent.
+                if (userAgentName == getString(R.string.system_default_user_agent)) {  // Use the system default user agent.
+                    // Set the user agent according to the system default.
+                    when (val defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName)) {
+                        // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
+                        UNRECOGNIZED_USER_AGENT -> nestedScrollWebView.settings.userAgentString = defaultUserAgentName
 
-                    // Get a list of the current fragments.
-                    val fragmentList = supportFragmentManager.fragments
+                        // Set the user agent to `""`, which uses the default value.
+                        SETTINGS_WEBVIEW_DEFAULT_USER_AGENT -> nestedScrollWebView.settings.userAgentString = ""
 
-                    // Check each fragment to see if it is a waiting for proxy dialog.  Sometimes more than one is displayed.
-                    for (i in fragmentList.indices) {
-                        // Get the fragment tag.
-                        val fragmentTag = fragmentList[i].tag
+                        // Set the default custom user agent.
+                        SETTINGS_CUSTOM_USER_AGENT -> nestedScrollWebView.settings.userAgentString =
+                            sharedPreferences.getString(getString(R.string.custom_user_agent_key), getString(R.string.custom_user_agent_default_value))
 
-                        // Check to see if it is the waiting for proxy dialog.
-                        if (fragmentTag != null && fragmentTag == getString(R.string.waiting_for_proxy_dialog)) {
-                            // Dismiss the waiting for proxy dialog.
-                            (fragmentList[i] as DialogFragment).dismiss()
-                        }
+                        // Get the user agent string from the user agent data array
+                        else -> nestedScrollWebView.settings.userAgentString = userAgentDataArray[defaultUserAgentArrayPosition]
                     }
+                } else {  // Set the user agent according to the stored name.
+                    // Set the user agent.
+                    when (val userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName)) {
+                        // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
+                        UNRECOGNIZED_USER_AGENT ->
+                            nestedScrollWebView.settings.userAgentString = userAgentName
 
-                    // Reload existing URLs and load any URLs that are waiting for the proxy.
-                    for (i in 0 until webViewPagerAdapter!!.count) {
-                        // Get the WebView tab fragment.
-                        val webViewTabFragment = webViewPagerAdapter!!.getPageFragment(i)
-
-                        // Get the fragment view.
-                        val fragmentView = webViewTabFragment.view
-
-                        // Only process the WebViews if they exist.
-                        if (fragmentView != null) {
-                            // Get the nested scroll WebView from the tab fragment.
-                            val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
+                        // Set the user agent to `""`, which uses the default value.
+                        SETTINGS_WEBVIEW_DEFAULT_USER_AGENT ->
+                            nestedScrollWebView.settings.userAgentString = ""
 
-                            // Get the waiting for proxy URL string.
-                            val waitingForProxyUrlString = nestedScrollWebView.waitingForProxyUrlString
+                        // Get the user agent string from the user agent data array.
+                        else ->
+                            nestedScrollWebView.settings.userAgentString = userAgentDataArray[userAgentArrayPosition]
+                    }
+                }
 
-                            // Load the pending URL if it exists.
-                            if (waitingForProxyUrlString.isNotEmpty()) {  // A URL is waiting to be loaded.
-                                // Load the URL.
-                                loadUrl(nestedScrollWebView, waitingForProxyUrlString)
+                // Set swipe to refresh.
+                when (swipeToRefreshInt) {
+                    DomainsDatabaseHelper.SYSTEM_DEFAULT -> {
+                        // Store the swipe to refresh status in the nested scroll WebView.
+                        nestedScrollWebView.swipeToRefresh = defaultSwipeToRefresh
 
-                                // Reset the waiting for proxy URL string.
-                                nestedScrollWebView.waitingForProxyUrlString = ""
-                            } else {  // No URL is waiting to be loaded.
-                                // Reload the existing URL.
-                                nestedScrollWebView.reload()
+                        // Update the swipe refresh layout.
+                        if (defaultSwipeToRefresh) {  // Swipe to refresh is enabled.
+                            // Update the status of the swipe refresh layout if the current WebView is not null (crash reports indicate that in some unexpected way it sometimes is null).
+                            if (currentWebView != null) {
+                                // Only enable the swipe refresh layout if the WebView is scrolled to the top.  It is updated every time the scroll changes.
+                                swipeRefreshLayout.isEnabled = (currentWebView!!.scrollY == 0)
                             }
+                        } else {  // Swipe to refresh is disabled.
+                            // Disable the swipe refresh layout.
+                            swipeRefreshLayout.isEnabled = false
                         }
                     }
-                }
-            }
-        }
-
-        // Register the Orbot status broadcast receiver.
-        registerReceiver(orbotStatusBroadcastReceiver, IntentFilter("org.torproject.android.intent.action.STATUS"))
-
-        // Get handles for views that need to be modified.
-        val bookmarksHeaderLinearLayout = findViewById<LinearLayout>(R.id.bookmarks_header_linearlayout)
-        val launchBookmarksActivityFab = findViewById<FloatingActionButton>(R.id.launch_bookmarks_activity_fab)
-        val createBookmarkFolderFab = findViewById<FloatingActionButton>(R.id.create_bookmark_folder_fab)
-        val createBookmarkFab = findViewById<FloatingActionButton>(R.id.create_bookmark_fab)
-
-        // Update the WebView pager every time a tab is modified.
-        webViewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
-            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}
-
-            override fun onPageSelected(position: Int) {
-                // Close the find on page bar if it is open.
-                closeFindOnPage(null)
 
-                // Set the current WebView.
-                setCurrentWebView(position)
-
-                // Select the corresponding tab if it does not match the currently selected page.  This will happen if the page was scrolled by creating a new tab.
-                if (tabLayout.selectedTabPosition != position) {
-                    // Wait until the new tab has been created.
-                    tabLayout.post {
-                        // Get a handle for the tab.
-                        val tab = tabLayout.getTabAt(position)!!
+                    DomainsDatabaseHelper.ENABLED -> {
+                        // Store the swipe to refresh status in the nested scroll WebView.
+                        nestedScrollWebView.swipeToRefresh = true
 
-                        // Select the tab.
-                        tab.select()
+                        // Update the status of the swipe refresh layout if the current WebView is not null (crash reports indicate that in some unexpected way it sometimes is null).
+                        if (currentWebView != null) {
+                            // Only enable the swipe refresh layout if the WebView is scrolled to the top.  It is updated every time the scroll changes.
+                            swipeRefreshLayout.isEnabled = (currentWebView!!.scrollY == 0)
+                        }
                     }
-                }
-            }
 
-            override fun onPageScrollStateChanged(state: Int) {}
-        })
+                    DomainsDatabaseHelper.DISABLED -> {
+                        // Store the swipe to refresh status in the nested scroll WebView.
+                        nestedScrollWebView.swipeToRefresh = false
 
-        // Handle tab selections.
-        tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
-            override fun onTabSelected(tab: TabLayout.Tab) {
-                // Select the same page in the view pager.
-                webViewPager.currentItem = tab.position
-            }
+                        // Disable swipe to refresh.
+                        swipeRefreshLayout.isEnabled = false
+                    }
+                }
 
-            override fun onTabUnselected(tab: TabLayout.Tab) {}
+                // Set the WebView theme if device is running API >= 29 and algorithmic darkening is supported.
+                if ((Build.VERSION.SDK_INT >= 29) && WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {
+                    // Set the WebView theme.
+                    when (webViewThemeInt) {
+                        // Set the WebView theme.
+                        DomainsDatabaseHelper.SYSTEM_DEFAULT ->
+                            when (webViewTheme) {
+                                // The light theme is selected.  Turn off algorithmic darkening.
+                                webViewThemeEntryValuesStringArray[1] -> WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
 
-            override fun onTabReselected(tab: TabLayout.Tab) {
-                // Instantiate the View SSL Certificate dialog.
-                val viewSslCertificateDialogFragment: DialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView!!.webViewFragmentId, currentWebView!!.getFavoriteIcon())
+                                // The dark theme is selected.  Turn on algorithmic darkening.
+                                webViewThemeEntryValuesStringArray[2] -> WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
 
-                // Display the View SSL Certificate dialog.
-                viewSslCertificateDialogFragment.show(supportFragmentManager, getString(R.string.view_ssl_certificate))
-            }
-        })
+                                // The system default theme is selected.
+                                else -> {
+                                    // Get the current system theme status.
+                                    val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
 
-        // Set a touch listener on the bookmarks header linear layout so that touches don't pass through to the button underneath.
-        bookmarksHeaderLinearLayout.setOnTouchListener { _: View?, _: MotionEvent? -> true }
+                                    // Set the algorithmic darkening according to the current system theme status.
+                                    WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, currentThemeStatus == Configuration.UI_MODE_NIGHT_YES)
+                                }
+                            }
 
-        // Set the launch bookmarks activity floating action button to launch the bookmarks activity.
-        launchBookmarksActivityFab.setOnClickListener {
-            // Get a copy of the favorite icon bitmap.
-            val currentFavoriteIconBitmap = currentWebView!!.getFavoriteIcon()
+                        // Turn off algorithmic darkening.
+                        DomainsDatabaseHelper.LIGHT_THEME -> WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
 
-            // Create a favorite icon byte array output stream.
-            val currentFavoriteIconByteArrayOutputStream = ByteArrayOutputStream()
+                        // Turn on algorithmic darkening.
+                        DomainsDatabaseHelper.DARK_THEME -> WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
+                    }
+                }
 
-            // Convert the favorite icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
-            currentFavoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, currentFavoriteIconByteArrayOutputStream)
+                // Set the wide viewport status.
+                when (wideViewportInt) {
+                    DomainsDatabaseHelper.SYSTEM_DEFAULT -> nestedScrollWebView.settings.useWideViewPort = wideViewport
+                    DomainsDatabaseHelper.ENABLED -> nestedScrollWebView.settings.useWideViewPort = true
+                    DomainsDatabaseHelper.DISABLED -> nestedScrollWebView.settings.useWideViewPort = false
+                }
 
-            // Convert the favorite icon byte array stream to a byte array.
-            val currentFavoriteIconByteArray = currentFavoriteIconByteArrayOutputStream.toByteArray()
+                // Set the display webpage images status.
+                when (displayWebpageImagesInt) {
+                    DomainsDatabaseHelper.SYSTEM_DEFAULT -> nestedScrollWebView.settings.loadsImagesAutomatically = displayWebpageImages
+                    DomainsDatabaseHelper.ENABLED -> nestedScrollWebView.settings.loadsImagesAutomatically = true
+                    DomainsDatabaseHelper.DISABLED -> nestedScrollWebView.settings.loadsImagesAutomatically = false
+                }
 
-            // Create an intent to launch the bookmarks activity.
-            val bookmarksIntent = Intent(applicationContext, BookmarksActivity::class.java)
+                // Set a background on the URL relative layout to indicate that custom domain settings are being used.
+                urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.drawable.domain_settings_url_background)
+            } else {  // The new URL does not have custom domain settings.  Load the defaults.
+                // Store the values from the shared preferences.
+                nestedScrollWebView.settings.javaScriptEnabled = sharedPreferences.getBoolean(getString(R.string.javascript_key), false)
+                nestedScrollWebView.acceptCookies = sharedPreferences.getBoolean(getString(R.string.cookies_key), false)
+                nestedScrollWebView.settings.domStorageEnabled = sharedPreferences.getBoolean(getString(R.string.dom_storage_key), false)
+                val saveFormData = sharedPreferences.getBoolean(getString(R.string.save_form_data_key), false) // Form data can be removed once the minimum API >= 26.
+                nestedScrollWebView.easyListEnabled = sharedPreferences.getBoolean(getString(R.string.easylist_key), true)
+                nestedScrollWebView.easyPrivacyEnabled = sharedPreferences.getBoolean(getString(R.string.easyprivacy_key), true)
+                nestedScrollWebView.fanboysAnnoyanceListEnabled = sharedPreferences.getBoolean(getString(R.string.fanboys_annoyance_list_key), true)
+                nestedScrollWebView.fanboysSocialBlockingListEnabled = sharedPreferences.getBoolean(getString(R.string.fanboys_social_blocking_list_key), true)
+                nestedScrollWebView.ultraListEnabled = sharedPreferences.getBoolean(getString(R.string.ultralist_key), true)
+                nestedScrollWebView.ultraPrivacyEnabled = sharedPreferences.getBoolean(getString(R.string.ultraprivacy_key), true)
+                nestedScrollWebView.blockAllThirdPartyRequests = sharedPreferences.getBoolean(getString(R.string.block_all_third_party_requests_key), false)
 
-            // Add the extra information to the intent.
-            bookmarksIntent.putExtra(CURRENT_FOLDER, currentBookmarksFolder)
-            bookmarksIntent.putExtra(CURRENT_TITLE, currentWebView!!.title)
-            bookmarksIntent.putExtra(CURRENT_URL, currentWebView!!.url)
-            bookmarksIntent.putExtra(CURRENT_FAVORITE_ICON_BYTE_ARRAY, currentFavoriteIconByteArray)
+                // Apply the default cookie setting.
+                cookieManager.setAcceptCookie(nestedScrollWebView.acceptCookies)
 
-            // Make it so.
-            startActivity(bookmarksIntent)
-        }
+                // Apply the default font size setting.
+                try {
+                    // Try to set the font size from the value in the app settings.
+                    nestedScrollWebView.settings.textZoom = defaultFontSizeString!!.toInt()
+                } catch (exception: Exception) {
+                    // If the app settings value is invalid, set the font size to 100%.
+                    nestedScrollWebView.settings.textZoom = 100
+                }
 
-        // Set the create new bookmark folder floating action button to display an alert dialog.
-        createBookmarkFolderFab.setOnClickListener {
-            // Create a create bookmark folder dialog.
-            val createBookmarkFolderDialog: DialogFragment = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView!!.getFavoriteIcon())
+                // Apply the form data setting if the API < 26.
+                if (Build.VERSION.SDK_INT < 26)
+                    @Suppress("DEPRECATION")
+                    nestedScrollWebView.settings.saveFormData = saveFormData
 
-            // Show the create bookmark folder dialog.
-            createBookmarkFolderDialog.show(supportFragmentManager, getString(R.string.create_folder))
-        }
+                // Store the swipe to refresh status in the nested scroll WebView.
+                nestedScrollWebView.swipeToRefresh = defaultSwipeToRefresh
 
-        // Set the create new bookmark floating action button to display an alert dialog.
-        createBookmarkFab.setOnClickListener {
-            // Instantiate the create bookmark dialog.
-            val createBookmarkDialog: DialogFragment = CreateBookmarkDialog.createBookmark(currentWebView!!.url!!, currentWebView!!.title!!, currentWebView!!.getFavoriteIcon())
+                // Update the swipe refresh layout.
+                if (defaultSwipeToRefresh) {  // Swipe to refresh is enabled.
+                    // Update the status of the swipe refresh layout if the current WebView is not null (crash reports indicate that in some unexpected way it sometimes is null).
+                    if (currentWebView != null) {
+                        // Only enable the swipe refresh layout if the WebView is scrolled to the top.  It is updated every time the scroll changes.
+                        swipeRefreshLayout.isEnabled = currentWebView!!.scrollY == 0
+                    }
+                } else {  // Swipe to refresh is disabled.
+                    // Disable the swipe refresh layout.
+                    swipeRefreshLayout.isEnabled = false
+                }
 
-            // Display the create bookmark dialog.
-            createBookmarkDialog.show(supportFragmentManager, getString(R.string.create_bookmark))
-        }
+                // Reset the domain settings database ID.
+                nestedScrollWebView.domainSettingsDatabaseId = -1
 
-        // Search for the string on the page whenever a character changes in the find on page edit text.
-        findOnPageEditText.addTextChangedListener(object : TextWatcher {
-            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
+                // Set the user agent.
+                when (val userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName)) {
+                    // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
+                    UNRECOGNIZED_USER_AGENT -> nestedScrollWebView.settings.userAgentString = defaultUserAgentName
 
-            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
+                    // Set the user agent to `""`, which uses the default value.
+                    SETTINGS_WEBVIEW_DEFAULT_USER_AGENT -> nestedScrollWebView.settings.userAgentString = ""
 
-            override fun afterTextChanged(s: Editable) {
-                // 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.
-                currentWebView?.findAllAsync(findOnPageEditText.text.toString())
-            }
-        })
+                    // Set the default custom user agent.
+                    SETTINGS_CUSTOM_USER_AGENT -> nestedScrollWebView.settings.userAgentString =
+                        sharedPreferences.getString(getString(R.string.custom_user_agent_key), getString(R.string.custom_user_agent_default_value))
 
-        // Set the `check mark` button for the find on page edit text keyboard to close the soft keyboard.
-        findOnPageEditText.setOnKeyListener { _: View?, keyCode: Int, keyEvent: KeyEvent ->
-            if ((keyEvent.action == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {  // The `enter` key was pressed.
-                // Hide the soft keyboard.
-                inputMethodManager.hideSoftInputFromWindow(currentWebView!!.windowToken, 0)
+                    // Get the user agent string from the user agent data array
+                    else -> nestedScrollWebView.settings.userAgentString = userAgentDataArray[userAgentArrayPosition]
+                }
 
-                // Consume the event.
-                return@setOnKeyListener true
-            } else {  // A different key was pressed.
-                // Do not consume the event.
-                return@setOnKeyListener false
-            }
-        }
+                // Set the WebView theme if the device is running API >= 29 and algorithmic darkening is supported.
+                if ((Build.VERSION.SDK_INT >= 29) && WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {
+                    // Set the WebView theme.
+                    when (webViewTheme) {
+                        // The light theme is selected.  Turn off algorithmic darkening.
+                        webViewThemeEntryValuesStringArray[1] -> WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
 
-        // Implement swipe to refresh.
-        swipeRefreshLayout.setOnRefreshListener {
-            // Reload the website.
-            currentWebView!!.reload()
-        }
+                        // The dark theme is selected.  Turn on algorithmic darkening.
+                        webViewThemeEntryValuesStringArray[2] -> WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
 
-        // Store the default progress view offsets.
-        defaultProgressViewStartOffset = swipeRefreshLayout.progressViewStartOffset
-        defaultProgressViewEndOffset = swipeRefreshLayout.progressViewEndOffset
+                        // The system default theme is selected.  Get the current system theme status.
+                        else -> {
+                            // Get the current theme status.
+                            val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
 
-        // Set the refresh color scheme according to the theme.
-        swipeRefreshLayout.setColorSchemeResources(R.color.blue_text)
+                            // Set the algorithmic darkening according to the current system theme status.
+                            WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, currentThemeStatus == Configuration.UI_MODE_NIGHT_YES)
+                        }
+                    }
+                }
 
-        // Initialize a color background typed value.
-        val colorBackgroundTypedValue = TypedValue()
+                // Set the viewport.
+                nestedScrollWebView.settings.useWideViewPort = wideViewport
 
-        // Get the color background from the theme.
-        theme.resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true)
+                // Set the loading of webpage images.
+                nestedScrollWebView.settings.loadsImagesAutomatically = displayWebpageImages
 
-        // Get the color background int from the typed value.
-        val colorBackgroundInt = colorBackgroundTypedValue.data
+                // Set a transparent background on the URL relative layout.
+                urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.color.transparent)
+            }
 
-        // Set the swipe refresh background color.
-        swipeRefreshLayout.setProgressBackgroundColorSchemeColor(colorBackgroundInt)
+            // Update the privacy icons.
+            updatePrivacyIcons(true)
+        }
 
-        // Set the drawer titles, which identify the drawer layouts in accessibility mode.
-        drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer))
-        drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks))
+        // Reload the website if returning from the Domains activity.
+        if (reloadWebsite)
+            nestedScrollWebView.reload()
 
-        // Load the bookmarks folder.
-        loadBookmarksFolder()
+        // Load the URL if directed.  This makes sure that the domain settings are properly loaded before the URL.  By using `loadUrl()`, instead of `loadUrlFromBase()`, the Referer header will never be sent.
+        if (loadUrl)
+            nestedScrollWebView.loadUrl(url)
+    }
 
-        // Handle clicks on bookmarks.
-        bookmarksListView.onItemClickListener = AdapterView.OnItemClickListener { _: AdapterView<*>?, _: View?, _: Int, id: Long ->
-            // Convert the id from long to int to match the format of the bookmarks database.
-            val databaseId = id.toInt()
+    private fun applyProxy(reloadWebViews: Boolean) {
+        // Set the proxy according to the mode.
+        proxyHelper.setProxy(applicationContext, appBarLayout, proxyMode)
 
-            // Get the bookmark cursor for this ID.
-            val bookmarkCursor = bookmarksDatabaseHelper!!.getBookmark(databaseId)
+        // Reset the waiting for proxy tracker.
+        waitingForProxy = false
 
-            // Move the bookmark cursor to the first row.
-            bookmarkCursor.moveToFirst()
+        // Set the proxy.
+        when (proxyMode) {
+            ProxyHelper.NONE -> {
+                // Initialize a color background typed value.
+                val colorBackgroundTypedValue = TypedValue()
 
-            // Act upon the bookmark according to the type.
-            if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {  // The selected bookmark is a folder.
-                // Store the folder name.
-                currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME))
+                // Get the color background from the theme.
+                theme.resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true)
 
-                // Load the new folder.
-                loadBookmarksFolder()
-            } else {  // The selected bookmark is not a folder.
-                // Load the bookmark URL.
-                loadUrl(currentWebView!!, bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_URL)))
+                // Get the color background int from the typed value.
+                val colorBackgroundInt = colorBackgroundTypedValue.data
 
-                // Close the bookmarks drawer if it is not pinned.
-                if (!bookmarksDrawerPinned)
-                    drawerLayout.closeDrawer(GravityCompat.END)
+                // Set the default app bar layout background.
+                appBarLayout.setBackgroundColor(colorBackgroundInt)
             }
 
-            // Close the cursor.
-            bookmarkCursor.close()
-        }
+            ProxyHelper.TOR -> {
+                // Set the app bar background to indicate proxying is enabled.
+                appBarLayout.setBackgroundResource(R.color.blue_background)
+
+                // Check to see if Orbot is installed.
+                try {
+                    // Get the package manager.
+                    val packageManager = packageManager
 
-        // Handle long-presses on bookmarks.
-        bookmarksListView.onItemLongClickListener = AdapterView.OnItemLongClickListener { _: AdapterView<*>?, _: View?, _: Int, id: Long ->
-            // Convert the database ID from `long` to `int`.
-            val databaseId = id.toInt()
+                    // 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.  The deprecated method must be used until the minimum API >= 33.
+                    @Suppress("DEPRECATION")
+                    packageManager.getPackageInfo("org.torproject.android", 0)
 
-            // Run the commands associated with the type.
-            if (bookmarksDatabaseHelper!!.isFolder(databaseId)) {  // The bookmark is a folder.
-                // Get a cursor of all the bookmarks in the folder.
-                val bookmarksCursor = bookmarksDatabaseHelper!!.getFolderBookmarks(databaseId)
+                    // Check to see if the proxy is ready.
+                    if (orbotStatus != ProxyHelper.ORBOT_STATUS_ON) {  // Orbot is not ready.
+                        // Set the waiting for proxy status.
+                        waitingForProxy = true
 
-                // Move to the first entry in the cursor.
-                bookmarksCursor.moveToFirst()
+                        // Show the waiting for proxy dialog if it isn't already displayed.
+                        if (supportFragmentManager.findFragmentByTag(getString(R.string.waiting_for_proxy_dialog)) == null) {
+                            // Get a handle for the waiting for proxy alert dialog.
+                            val waitingForProxyDialogFragment = WaitingForProxyDialog()
 
-                // Open each bookmark
-                for (i in 0 until bookmarksCursor.count) {
-                    // Load the bookmark in a new tab, moving to the tab for the first bookmark if the drawer is not pinned.
-                    addNewTab(bookmarksCursor.getString(bookmarksCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_URL)), !bookmarksDrawerPinned && (i == 0))
+                            // Try to show the dialog.  Sometimes the window is not yet active if returning from Settings.
+                            try {
+                                // Show the waiting for proxy alert dialog.
+                                waitingForProxyDialogFragment.show(supportFragmentManager, getString(R.string.waiting_for_proxy_dialog))
+                            } catch (waitingForTorException: Exception) {
+                                // Add the dialog to the pending dialog array list.  It will be displayed in `onStart()`.
+                                pendingDialogsArrayList.add(PendingDialogDataClass(waitingForProxyDialogFragment, getString(R.string.waiting_for_proxy_dialog)))
+                            }
+                        }
+                    }
+                } catch (exception: PackageManager.NameNotFoundException) {  // Orbot is not installed.
+                    // Show the Orbot not installed dialog if it is not already displayed.
+                    if (supportFragmentManager.findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
+                        // Get a handle for the Orbot not installed alert dialog.
+                        val orbotNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode)
 
-                    // Move to the next bookmark.
-                    bookmarksCursor.moveToNext()
+                        // Try to show the dialog.  Sometimes the window is not yet active if returning from Settings.
+                        try {
+                            // Display the Orbot not installed alert dialog.
+                            orbotNotInstalledDialogFragment.show(supportFragmentManager, getString(R.string.proxy_not_installed_dialog))
+                        } catch (orbotNotInstalledException: Exception) {
+                            // Add the dialog to the pending dialog array list.  It will be displayed in `onStart()`.
+                            pendingDialogsArrayList.add(PendingDialogDataClass(orbotNotInstalledDialogFragment, getString(R.string.proxy_not_installed_dialog)))
+                        }
+                    }
                 }
+            }
 
-                // Close the cursor.
-                bookmarksCursor.close()
-            } else {  // The bookmark is not a folder.
-                // Get the bookmark cursor for this ID.
-                val bookmarkCursor = bookmarksDatabaseHelper!!.getBookmark(databaseId)
-
-                // Move the bookmark cursor to the first row.
-                bookmarkCursor.moveToFirst()
+            ProxyHelper.I2P -> {
+                // Set the app bar background to indicate proxying is enabled.
+                appBarLayout.setBackgroundResource(R.color.blue_background)
 
-                // Load the bookmark in a new tab and move to the tab if the drawer is not pinned.
-                addNewTab(bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_URL)), !bookmarksDrawerPinned)
+                // Check to see if I2P is installed.
+                try {
+                    // Check to see if the F-Droid flavor is installed.  This will throw an error and drop to the catch section if it isn't installed.
+                    // The deprecated method must be used until the minimum API >= 33.
+                    @Suppress("DEPRECATION")
+                    packageManager.getPackageInfo("net.i2p.android.router", 0)
+                } catch (fdroidException: PackageManager.NameNotFoundException) {  // The F-Droid flavor is not installed.
+                    try {
+                        // Check to see if the Google Play flavor is installed.  This will throw an error and drop to the catch section if it isn't installed.
+                        // The deprecated method must be used until the minimum API >= 33.
+                        @Suppress("DEPRECATION")
+                        packageManager.getPackageInfo("net.i2p.android", 0)
+                    } catch (googlePlayException: PackageManager.NameNotFoundException) {  // The Google Play flavor is not installed.
+                        // Sow the I2P not installed dialog if it is not already displayed.
+                        if (supportFragmentManager.findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
+                            // Get a handle for the waiting for proxy alert dialog.
+                            val i2pNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode)
 
-                // Close the cursor.
-                bookmarkCursor.close()
+                            // Try to show the dialog.  Sometimes the window is not yet active if returning from Settings.
+                            try {
+                                // Display the I2P not installed alert dialog.
+                                i2pNotInstalledDialogFragment.show(supportFragmentManager, getString(R.string.proxy_not_installed_dialog))
+                            } catch (i2pNotInstalledException: Exception) {
+                                // Add the dialog to the pending dialog array list.  It will be displayed in `onStart()`.
+                                pendingDialogsArrayList.add(PendingDialogDataClass(i2pNotInstalledDialogFragment, getString(R.string.proxy_not_installed_dialog)))
+                            }
+                        }
+                    }
+                }
             }
 
-            // Close the bookmarks drawer if it is not pinned.
-            if (!bookmarksDrawerPinned)
-                drawerLayout.closeDrawer(GravityCompat.END)
-
-            // Consume the event.
-            true
+            ProxyHelper.CUSTOM ->
+                // Set the app bar background to indicate proxying is enabled.
+                appBarLayout.setBackgroundResource(R.color.blue_background)
         }
 
-        // The drawer listener is used to update the navigation menu.
-        drawerLayout.addDrawerListener(object : DrawerLayout.DrawerListener {
-            override fun onDrawerSlide(drawerView: View, slideOffset: Float) {}
+        // Reload the WebViews if requested and not waiting for the proxy.
+        if (reloadWebViews && !waitingForProxy) {
+            // Reload the WebViews.
+            for (i in 0 until webViewPagerAdapter!!.count) {
+                // Get the WebView tab fragment.
+                val webViewTabFragment = webViewPagerAdapter!!.getPageFragment(i)
 
-            override fun onDrawerOpened(drawerView: View) {}
+                // Get the fragment view.
+                val fragmentView = webViewTabFragment.view
 
-            override fun onDrawerClosed(drawerView: View) {
-                // Reset the drawer icon when the drawer is closed.  Otherwise, it remains an arrow if the drawer is open when the app is restarted.
-                actionBarDrawerToggle!!.syncState()
+                // Only reload the WebViews if they exist.
+                if (fragmentView != null) {
+                    // Get the nested scroll WebView from the tab fragment.
+                    val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
+
+                    // Reload the WebView.
+                    nestedScrollWebView.reload()
+                }
             }
+        }
+    }
 
-            override fun onDrawerStateChanged(newState: Int) {
-                if (newState == DrawerLayout.STATE_SETTLING || newState == DrawerLayout.STATE_DRAGGING) {  // A drawer is opening or closing.
-                    // Update the navigation menu items if the WebView is not null.
-                    if (currentWebView != null) {
-                        navigationBackMenuItem.isEnabled = currentWebView!!.canGoBack()
-                        navigationForwardMenuItem.isEnabled = currentWebView!!.canGoForward()
-                        navigationHistoryMenuItem.isEnabled = currentWebView!!.canGoBack() || currentWebView!!.canGoForward()
-                        navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + currentWebView!!.getRequestsCount(BLOCKED_REQUESTS)
+    // The view parameter cannot be removed because it is called from the layout onClick.
+    fun bookmarksBack(@Suppress("UNUSED_PARAMETER")view: View?) {
+        if (currentBookmarksFolder.isEmpty()) {  // The home folder is displayed.
+            // close the bookmarks drawer.
+            drawerLayout.closeDrawer(GravityCompat.END)
+        } else {  // A subfolder is displayed.
+            // Set the former parent folder as the current folder.
+            currentBookmarksFolder = bookmarksDatabaseHelper!!.getParentFolderName(currentBookmarksFolder)
 
-                        // Hide the keyboard (if displayed).
-                        inputMethodManager.hideSoftInputFromWindow(currentWebView!!.windowToken, 0)
-                    }
+            // Load the new folder.
+            loadBookmarksFolder()
+        }
+    }
 
-                    // Clear the focus from from the URL text box.  This removes any text selection markers and context menus, which otherwise draw above the open drawers.
-                    urlEditText.clearFocus()
+    private fun clearAndExit() {
+        // Close the bookmarks cursor if it exists.
+        bookmarksCursor?.close()
 
-                    // Clear the focus from from the WebView if it is not null, which can happen if a user opens a drawer while the browser is being resumed.
-                    // Clearing the focus from the WebView removes any text selection markers and context menus, which otherwise draw above the open drawers.
-                    currentWebView?.clearFocus()
-                }
-            }
-        })
+        // Close the databases helpers if they exist.
+        bookmarksDatabaseHelper?.close()
+        domainsDatabaseHelper?.close()
 
-        // Inflate a bare WebView to get the default user agent.  It is not used to render content on the screen.
-        @SuppressLint("InflateParams") val webViewLayout = layoutInflater.inflate(R.layout.bare_webview, null, false)
+        // Get the status of the clear everything preference.
+        val clearEverything = sharedPreferences.getBoolean(getString(R.string.clear_everything_key), true)
 
-        // Get a handle for the WebView.
-        val bareWebView = webViewLayout.findViewById<WebView>(R.id.bare_webview)
+        // Get a handle for the runtime.
+        val runtime = Runtime.getRuntime()
 
-        // Store the default user agent.
-        webViewDefaultUserAgent = bareWebView.settings.userAgentString
+        // 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`.
+        val privateDataDirectoryString = applicationInfo.dataDir
 
-        // Destroy the bare WebView.
-        bareWebView.destroy()
-    }
+        // Clear cookies.
+        if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_cookies_key), true)) {
+            // Ass the cookie manager to delete all the cookies.
+            cookieManager.removeAllCookies(null)
 
-    private fun applyAppSettings() {
-        // Store the values from the shared preferences in variables.
-        incognitoModeEnabled = sharedPreferences.getBoolean(getString(R.string.incognito_mode_key), false)
-        sanitizeTrackingQueries = sharedPreferences.getBoolean(getString(R.string.tracking_queries_key), true)
-        sanitizeAmpRedirects = sharedPreferences.getBoolean(getString(R.string.amp_redirects_key), true)
-        proxyMode = sharedPreferences.getString(getString(R.string.proxy_key), getString(R.string.proxy_default_value))!!
-        fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean(getString(R.string.full_screen_browsing_mode_key), false)
-        hideAppBar = sharedPreferences.getBoolean(getString(R.string.hide_app_bar_key), true)
-        downloadWithExternalApp = sharedPreferences.getBoolean(getString(R.string.download_with_external_app_key), false)
-        scrollAppBar = sharedPreferences.getBoolean(getString(R.string.scroll_app_bar_key), true)
+            // Ask the cookie manager to flush the cookie database.
+            cookieManager.flush()
 
-        // Apply the saved proxy mode if the app has been restarted.
-        if (savedProxyMode != null) {
-            // Apply the saved proxy mode.
-            proxyMode = savedProxyMode!!
+            // Manually delete the cookies database, as the cookie manager sometimes will not flush its changes to disk before system exit is run.
+            try {
+                // Two commands must be used because `Runtime.exec()` does not like `*`.
+                val deleteCookiesProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/Cookies")
+                val deleteCookiesJournalProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/Cookies-journal")
 
-            // Reset the saved proxy mode.
-            savedProxyMode = null
+                // Wait until the processes have finished.
+                deleteCookiesProcess.waitFor()
+                deleteCookiesJournalProcess.waitFor()
+            } catch (exception: Exception) {
+                // Do nothing if an error is thrown.
+            }
         }
 
-        // Get the search string.
-        val searchString = sharedPreferences.getString(getString(R.string.search_key), getString(R.string.search_default_value))!!
+        // Clear DOM storage.
+        if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_dom_storage_key), true)) {
+            // Ask web storage to clear the DOM storage.
+            WebStorage.getInstance().deleteAllData()
 
-        // Set the search string, using the custom search URL if specified.
-        searchURL = if (searchString == getString(R.string.custom_url_item))
-            sharedPreferences.getString(getString(R.string.search_custom_url_key), getString(R.string.search_custom_url_default_value))!!
-        else
-            searchString
+            // Manually delete the DOM storage files and directories, as web storage sometimes will not flush its changes to disk before system exit is run.
+            try {
+                // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
+                val deleteLocalStorageProcess = runtime.exec(arrayOf("rm", "-rf", "$privateDataDirectoryString/app_webview/Local Storage/"))
 
-        // Apply the proxy.
-        applyProxy(false)
+                // Multiple commands must be used because `Runtime.exec()` does not like `*`.
+                val deleteIndexProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview/IndexedDB")
+                val deleteQuotaManagerProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/QuotaManager")
+                val deleteQuotaManagerJournalProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/QuotaManager-journal")
+                val deleteDatabaseProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview/databases")
 
-        // Adjust the layout and scrolling parameters according to the position of the app bar.
-        if (bottomAppBar) {  // The app bar is on the bottom.
-            // Adjust the UI.
-            if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) {  // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
-                // Reset the WebView padding to fill the available space.
-                swipeRefreshLayout.setPadding(0, 0, 0, 0)
-            } else {  // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
-                // Move the WebView above the app bar layout.
-                swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
+                // Wait until the processes have finished.
+                deleteLocalStorageProcess.waitFor()
+                deleteIndexProcess.waitFor()
+                deleteQuotaManagerProcess.waitFor()
+                deleteQuotaManagerJournalProcess.waitFor()
+                deleteDatabaseProcess.waitFor()
+            } catch (exception: Exception) {
+                // Do nothing if an error is thrown.
+            }
+        }
 
-                // Show the app bar if it is scrolled off the screen.
-                if (appBarLayout.translationY != 0f) {
-                    // Animate the bottom app bar onto the screen.
-                    objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0f)
+        // Clear form data if the API < 26.
+        if (Build.VERSION.SDK_INT < 26 && (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_form_data_key), true))) {
+            // Ask the WebView database to clear the form data.
+            @Suppress("DEPRECATION")
+            WebViewDatabase.getInstance(this).clearFormData()
 
-                    // Make it so.
-                    objectAnimator.start()
-                }
+            // Manually delete the form data database, as the WebView database sometimes will not flush its changes to disk before system exit is run.
+            try {
+                // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
+                val deleteWebDataProcess = runtime.exec(arrayOf("rm", "-f", "$privateDataDirectoryString/app_webview/Web Data"))
+                val deleteWebDataJournalProcess = runtime.exec(arrayOf("rm", "-f", "$privateDataDirectoryString/app_webview/Web Data-journal"))
+
+                // Wait until the processes have finished.
+                deleteWebDataProcess.waitFor()
+                deleteWebDataJournalProcess.waitFor()
+            } catch (exception: Exception) {
+                // Do nothing if an error is thrown.
             }
-        } else {  // The app bar is on the top.
-            // Get the current layout parameters.  Using coordinator layout parameters allows the `setBehavior()` command and using app bar layout parameters allows the `setScrollFlags()` command.
-            val swipeRefreshLayoutParams = swipeRefreshLayout.layoutParams as CoordinatorLayout.LayoutParams
-            val toolbarLayoutParams = toolbar.layoutParams as AppBarLayout.LayoutParams
-            val findOnPageLayoutParams = findOnPageLinearLayout.layoutParams as AppBarLayout.LayoutParams
-            val tabsLayoutParams = tabsLinearLayout.layoutParams as AppBarLayout.LayoutParams
+        }
 
-            // Add the scrolling behavior to the layout parameters.
-            if (scrollAppBar) {
-                // Enable scrolling of the app bar.
-                swipeRefreshLayoutParams.behavior = AppBarLayout.ScrollingViewBehavior()
-                toolbarLayoutParams.scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS or AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP
-                findOnPageLayoutParams.scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS or AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP
-                tabsLayoutParams.scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS or AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP
-            } else {
-                // Disable scrolling of the app bar.
-                swipeRefreshLayoutParams.behavior = null
-                toolbarLayoutParams.scrollFlags = 0
-                findOnPageLayoutParams.scrollFlags = 0
-                tabsLayoutParams.scrollFlags = 0
+        // Clear the logcat.
+        if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_logcat_key), true)) {
+            try {
+                // Clear the logcat.  `-c` clears the logcat.  `-b all` clears all the buffers (instead of just crash, main, and system).
+                val process = Runtime.getRuntime().exec("logcat -b all -c")
 
-                // Expand the app bar if it is currently collapsed.
-                appBarLayout.setExpanded(true)
+                // Wait for the process to finish.
+                process.waitFor()
+            } catch (exception: IOException) {
+                // Do nothing.
+            } catch (exception: InterruptedException) {
+                // Do nothing.
             }
+        }
 
-            // Set the app bar scrolling for each WebView.
+        // Clear the cache.
+        if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_cache_key), true)) {
+            // Clear the cache from each WebView.
             for (i in 0 until webViewPagerAdapter!!.count) {
                 // Get the WebView tab fragment.
                 val webViewTabFragment = webViewPagerAdapter!!.getPageFragment(i)
 
-                // Get the fragment view.
-                val fragmentView = webViewTabFragment.view
+                // Get the WebView fragment view.
+                val webViewFragmentView = webViewTabFragment.view
 
-                // Only modify the WebViews if they exist.
-                if (fragmentView != null) {
+                // Only clear the cache if the WebView exists.
+                if (webViewFragmentView != null) {
                     // Get the nested scroll WebView from the tab fragment.
-                    val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
+                    val nestedScrollWebView = webViewFragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
 
-                    // Set the app bar scrolling.
-                    nestedScrollWebView.isNestedScrollingEnabled = scrollAppBar
+                    // Clear the cache for this WebView.
+                    nestedScrollWebView.clearCache(true)
                 }
             }
-        }
 
-        // Update the full screen browsing mode settings.
-        if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {  // Privacy Browser is currently in full screen browsing mode.
-            // Update the visibility of the app bar, which might have changed in the settings.
-            if (hideAppBar) {
-                // Hide the tab linear layout.
-                tabsLinearLayout.visibility = View.GONE
+            // Manually delete the cache directories.
+            try {
+                // Delete the main cache directory.
+                val deleteCacheProcess = runtime.exec("rm -rf $privateDataDirectoryString/cache")
 
-                // Hide the app bar.
-                appBar.hide()
-            } else {
-                // Show the tab linear layout.
-                tabsLinearLayout.visibility = View.VISIBLE
+                // Delete the secondary `Service Worker` cache directory.
+                // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
+                val deleteServiceWorkerProcess = runtime.exec(arrayOf("rm", "-rf", "$privateDataDirectoryString/app_webview/Default/Service Worker/"))
 
-                // Show the app bar.
-                appBar.show()
+                // Wait until the processes have finished.
+                deleteCacheProcess.waitFor()
+                deleteServiceWorkerProcess.waitFor()
+            } catch (exception: Exception) {
+                // Do nothing if an error is thrown.
             }
+        }
 
-            /* Hide the system bars.
-             * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
-             * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
-             * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
-             * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
-             */
+        // Wipe out each WebView.
+        for (i in 0 until webViewPagerAdapter!!.count) {
+            // Get the WebView tab fragment.
+            val webViewTabFragment = webViewPagerAdapter!!.getPageFragment(i)
 
-            // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
-            @Suppress("DEPRECATION")
-            rootFrameLayout.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
-        } else {  // Privacy Browser is not in full screen browsing mode.
-            // 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.
-            inFullScreenBrowsingMode = false
+            // Get the WebView frame layout.
+            val webViewFrameLayout = webViewTabFragment.view as FrameLayout?
 
-            // Show the tab linear layout.
-            tabsLinearLayout.visibility = View.VISIBLE
+            // Only wipe out the WebView if it exists.
+            if (webViewFrameLayout != null) {
+                // Get the nested scroll WebView from the tab fragment.
+                val nestedScrollWebView = webViewFrameLayout.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
 
-            // Show the app bar.
-            appBar.show()
+                // Clear SSL certificate preferences for this WebView.
+                nestedScrollWebView.clearSslPreferences()
 
-            // Remove the `SYSTEM_UI` flags from the root frame layout.  The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
-            @Suppress("DEPRECATION")
-            rootFrameLayout.systemUiVisibility = 0
-        }
-    }
+                // Clear the back/forward history for this WebView.
+                nestedScrollWebView.clearHistory()
 
-    override fun navigateHistory(url: String, steps: Int) {
-        // Apply the domain settings.
-        applyDomainSettings(currentWebView!!, url, resetTab = false, reloadWebsite = false, loadUrl = false)
+                // Remove all the views from the frame layout.
+                webViewFrameLayout.removeAllViews()
 
-        // Load the history entry.
-        currentWebView!!.goBackOrForward(steps)
-    }
+                // Destroy the internal state of the WebView.
+                nestedScrollWebView.destroy()
+            }
+        }
 
-    override fun pinnedErrorGoBack() {
-        // Get the current web back forward list.
-        val webBackForwardList = currentWebView!!.copyBackForwardList()
+        // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
+        // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
+        if (clearEverything) {
+            try {
+                // Delete the folder.
+                val deleteAppWebviewProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview")
 
-        // Get the previous entry URL.
-        val previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex - 1).url
+                // Wait until the process has finished.
+                deleteAppWebviewProcess.waitFor()
+            } catch (exception: Exception) {
+                // Do nothing if an error is thrown.
+            }
+        }
 
-        // Apply the domain settings.
-        applyDomainSettings(currentWebView!!, previousUrl, resetTab = false, reloadWebsite = false, loadUrl = false)
+        // Close Privacy Browser.  `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
+        finishAndRemoveTask()
 
-        // Go back.
-        currentWebView!!.goBack()
+        // Remove the terminated program from RAM.  The status code is `0`.
+        exitProcess(0)
     }
 
-    // `reloadWebsite` is used if returning from the Domains activity.  Otherwise JavaScript might not function correctly if it is newly enabled.
-    @SuppressLint("SetJavaScriptEnabled")
-    private fun applyDomainSettings(nestedScrollWebView: NestedScrollWebView, url: String?, resetTab: Boolean, reloadWebsite: Boolean, loadUrl: Boolean) {
-        // Store the current URL.
-        nestedScrollWebView.currentUrl = url!!
+    // The view parameter cannot be removed because it is called from the layout onClick.
+    fun closeFindOnPage(@Suppress("UNUSED_PARAMETER")view: View?) {
+        // Delete the contents of the find on page edit text.
+        findOnPageEditText.text = null
 
-        // Parse the URL into a URI.
-        val uri = Uri.parse(url)
+        // Clear the highlighted phrases if the WebView is not null.
+        currentWebView?.clearMatches()
 
-        // Extract the domain from the URI.
-        var newHostName = uri.host
+        // Hide the find on page linear layout.
+        findOnPageLinearLayout.visibility = View.GONE
 
-        // Strings don't like to be null.
-        if (newHostName == null)
-            newHostName = ""
+        // Show the toolbar.
+        toolbar.visibility = View.VISIBLE
 
-        // 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.
-        if (nestedScrollWebView.currentDomainName != newHostName || newHostName == "") {
-            // Set the new host name as the current domain name.
-            nestedScrollWebView.currentDomainName = newHostName
+        // Get a handle for the input method manager.
+        val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
 
-            // Reset the ignoring of pinned domain information.
-            nestedScrollWebView.ignorePinnedDomainInformation = false
+        // Hide the keyboard.
+        inputMethodManager.hideSoftInputFromWindow(toolbar.windowToken, 0)
+    }
 
-            // Clear any pinned SSL certificate or IP addresses.
-            nestedScrollWebView.clearPinnedSslCertificate()
-            nestedScrollWebView.pinnedIpAddresses = ""
+    // The view parameter cannot be removed because it is called from the layout onClick.
+    fun closeTab(@Suppress("UNUSED_PARAMETER")view: View?) {
+        // Run the command according to the number of tabs.
+        if (tabLayout.tabCount > 1) {  // There is more than one tab open.
+            // Get the current tab number.
+            val currentTabNumber = tabLayout.selectedTabPosition
+
+            // Delete the current tab.
+            tabLayout.removeTabAt(currentTabNumber)
+
+            // Delete the current page.  If the selected page number did not change during the delete (because the newly selected tab has has same number as the previously deleted tab), it will return true,
+            // meaning that the current WebView must be reset.  Otherwise it will happen automatically as the selected tab number changes.
+            if (webViewPagerAdapter!!.deletePage(currentTabNumber, webViewPager))
+                setCurrentWebView(currentTabNumber)
+        } else {  // There is only one tab open.
+            clearAndExit()
+        }
+    }
 
-            // Reset the favorite icon if specified.
-            if (resetTab) {
-                // Initialize the favorite icon.
-                nestedScrollWebView.initializeFavoriteIcon()
+    override fun createBookmark(dialogFragment: DialogFragment, favoriteIconBitmap: Bitmap) {
+        // Get the dialog.
+        val dialog = dialogFragment.dialog!!
 
-                // Get the current page position.
-                val currentPagePosition = webViewPagerAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
+        // Get the views from the dialog fragment.
+        val createBookmarkNameEditText = dialog.findViewById<EditText>(R.id.create_bookmark_name_edittext)
+        val createBookmarkUrlEditText = dialog.findViewById<EditText>(R.id.create_bookmark_url_edittext)
 
-                // Get the corresponding tab.
-                val tab = tabLayout.getTabAt(currentPagePosition)
+        // Extract the strings from the edit texts.
+        val bookmarkNameString = createBookmarkNameEditText.text.toString()
+        val bookmarkUrlString = createBookmarkUrlEditText.text.toString()
 
-                // Update the tab if it isn't null, which sometimes happens when restarting from the background.
-                if (tab != null) {
-                    // Get the tab custom view.
-                    val tabCustomView = tab.customView!!
+        // Create a favorite icon byte array output stream.
+        val favoriteIconByteArrayOutputStream = ByteArrayOutputStream()
 
-                    // Get the tab views.
-                    val tabFavoriteIconImageView = tabCustomView.findViewById<ImageView>(R.id.favorite_icon_imageview)
-                    val tabTitleTextView = tabCustomView.findViewById<TextView>(R.id.title_textview)
+        // Convert the favorite icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
+        favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream)
+
+        // Convert the favorite icon byte array stream to a byte array.
+        val favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray()
+
+        // Display the new bookmark below the current items in the (0 indexed) list.
+        val newBookmarkDisplayOrder = bookmarksListView.count
+
+        // Create the bookmark.
+        bookmarksDatabaseHelper!!.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray)
 
-                    // Set the default favorite icon as the favorite icon for this tab.
-                    tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nestedScrollWebView.getFavoriteIcon(), 64, 64, true))
+        // Update the bookmarks cursor with the current contents of this folder.
+        bookmarksCursor = bookmarksDatabaseHelper!!.getBookmarksByDisplayOrder(currentBookmarksFolder)
 
-                    // Set the loading title text.
-                    tabTitleTextView.setText(R.string.loading)
-                }
-            }
+        // Update the list view.
+        bookmarksCursorAdapter.changeCursor(bookmarksCursor)
 
-            // Get a full domain name cursor.
-            val domainNameCursor = domainsDatabaseHelper!!.domainNameCursorOrderedByDomain
+        // Scroll to the new bookmark.
+        bookmarksListView.setSelection(newBookmarkDisplayOrder)
+    }
 
-            // Initialize the domain settings set.
-            val domainSettingsSet: MutableSet<String> = HashSet()
+    override fun createBookmarkFolder(dialogFragment: DialogFragment, favoriteIconBitmap: Bitmap) {
+        // Get the dialog.
+        val dialog = dialogFragment.dialog!!
 
-            // Get the domain name column index.
-            val domainNameColumnIndex = domainNameCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.DOMAIN_NAME)
+        // Get handles for the views in the dialog fragment.
+        val folderNameEditText = dialog.findViewById<EditText>(R.id.folder_name_edittext)
+        val defaultIconRadioButton = dialog.findViewById<RadioButton>(R.id.default_icon_radiobutton)
+        val defaultIconImageView = dialog.findViewById<ImageView>(R.id.default_icon_imageview)
 
-            // Populate the domain settings set.
-            for (i in 0 until domainNameCursor.count) {
-                // Move the domains cursor to the current row.
-                domainNameCursor.moveToPosition(i)
+        // Get new folder name string.
+        val folderNameString = folderNameEditText.text.toString()
 
-                // Store the domain name in the domain settings set.
-                domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex))
-            }
+        // Set the folder icon bitmap according to the dialog.
+        val folderIconBitmap: Bitmap = if (defaultIconRadioButton.isChecked) {  // Use the default folder icon.
+            // Get the default folder icon drawable.
+            val folderIconDrawable = defaultIconImageView.drawable
 
-            // Close the domain name cursor.
-            domainNameCursor.close()
+            // Convert the folder icon drawable to a bitmap drawable.
+            val folderIconBitmapDrawable = folderIconDrawable as BitmapDrawable
 
-            // Initialize the domain name in database variable.
-            var domainNameInDatabase: String? = null
+            // Convert the folder icon bitmap drawable to a bitmap.
+            folderIconBitmapDrawable.bitmap
+        } else {  // Use the WebView favorite icon.
+            // Copy the favorite icon bitmap to the folder icon bitmap.
+            favoriteIconBitmap
+        }
 
-            // Check the hostname against the domain settings set.
-            if (domainSettingsSet.contains(newHostName)) {  // The hostname is contained in the domain settings set.
-                // Record the domain name in the database.
-                domainNameInDatabase = newHostName
+        // Create a folder icon byte array output stream.
+        val folderIconByteArrayOutputStream = ByteArrayOutputStream()
 
-                // Set the domain settings applied tracker to true.
-                nestedScrollWebView.domainSettingsApplied = true
-            } else {  // The hostname is not contained in the domain settings set.
-                // Set the domain settings applied tracker to false.
-                nestedScrollWebView.domainSettingsApplied = false
-            }
+        // Convert the folder icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
+        folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream)
 
-            // Check all the subdomains of the host name against wildcard domains in the domain cursor.
-            while (!nestedScrollWebView.domainSettingsApplied && newHostName!!.contains(".")) {  // Stop checking if domain settings are already applied or there are no more `.` in the hostname.
-                if (domainSettingsSet.contains("*.$newHostName")) {  // Check the host name prepended by `*.`.
-                    // Set the domain settings applied tracker to true.
-                    nestedScrollWebView.domainSettingsApplied = true
+        // Convert the folder icon byte array stream to a byte array.
+        val folderIconByteArray = folderIconByteArrayOutputStream.toByteArray()
 
-                    // Store the applied domain names as it appears in the database.
-                    domainNameInDatabase = "*.$newHostName"
-                }
+        // Move all the bookmarks down one in the display order.
+        for (i in 0 until bookmarksListView.count) {
+            // Get the bookmark database id.
+            val databaseId = bookmarksListView.getItemIdAtPosition(i).toInt()
 
-                // Strip out the lowest subdomain of of the host name.
-                newHostName = newHostName.substring(newHostName.indexOf(".") + 1)
-            }
+            // Move the bookmark down one slot.
+            bookmarksDatabaseHelper!!.updateDisplayOrder(databaseId, i + 1)
+        }
 
-            // Store the general preference information.
-            val defaultFontSizeString = sharedPreferences.getString(getString(R.string.font_size_key), getString(R.string.font_size_default_value))
-            val defaultUserAgentName = sharedPreferences.getString(getString(R.string.user_agent_key), getString(R.string.user_agent_default_value))
-            val defaultSwipeToRefresh = sharedPreferences.getBoolean(getString(R.string.swipe_to_refresh_key), true)
-            val webViewTheme = sharedPreferences.getString(getString(R.string.webview_theme_key), getString(R.string.webview_theme_default_value))
-            val wideViewport = sharedPreferences.getBoolean(getString(R.string.wide_viewport_key), true)
-            val displayWebpageImages = sharedPreferences.getBoolean(getString(R.string.display_webpage_images_key), true)
+        // Create the folder, which will be placed at the top of the list view.
+        bookmarksDatabaseHelper!!.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray)
 
-            // Get the WebView theme entry values string array.
-            val webViewThemeEntryValuesStringArray = resources.getStringArray(R.array.webview_theme_entry_values)
+        // Update the bookmarks cursor with the current contents of this folder.
+        bookmarksCursor = bookmarksDatabaseHelper!!.getBookmarksByDisplayOrder(currentBookmarksFolder)
 
-            // Initialize the user agent array adapter and string array.
-            val userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item)
-            val userAgentDataArray = resources.getStringArray(R.array.user_agent_data)
+        // Update the list view.
+        bookmarksCursorAdapter.changeCursor(bookmarksCursor)
 
-            // Apply either the domain settings for the default settings.
-            if (nestedScrollWebView.domainSettingsApplied) {  // The url has custom domain settings.
-                // Get a cursor for the current host.
-                val currentDomainSettingsCursor = domainsDatabaseHelper!!.getCursorForDomainName(domainNameInDatabase!!)
+        // Scroll to the new folder.
+        bookmarksListView.setSelection(0)
+    }
 
-                // Move to the first position.
-                currentDomainSettingsCursor.moveToFirst()
+    private fun downloadUrlWithExternalApp(url: String) {
+        // Create a download intent.  Not specifying the action type will display the maximum number of options.
+        val downloadIntent = Intent()
 
-                // Get the settings from the cursor.
-                nestedScrollWebView.domainSettingsDatabaseId = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ID))
-                nestedScrollWebView.settings.javaScriptEnabled = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1
-                nestedScrollWebView.acceptCookies = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.COOKIES)) == 1
-                nestedScrollWebView.settings.domStorageEnabled = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1
-                // Form data can be removed once the minimum API >= 26.
-                val saveFormData = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1
-                nestedScrollWebView.easyListEnabled = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1
-                nestedScrollWebView.easyPrivacyEnabled = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1
-                nestedScrollWebView.fanboysAnnoyanceListEnabled = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1
-                nestedScrollWebView.fanboysSocialBlockingListEnabled =
-                    currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1
-                nestedScrollWebView.ultraListEnabled = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ULTRALIST)) == 1
-                nestedScrollWebView.ultraPrivacyEnabled = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1
-                nestedScrollWebView.blockAllThirdPartyRequests = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1
-                val userAgentName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.USER_AGENT))
-                val fontSize = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.FONT_SIZE))
-                val swipeToRefreshInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SWIPE_TO_REFRESH))
-                val webViewThemeInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.WEBVIEW_THEME))
-                val wideViewportInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.WIDE_VIEWPORT))
-                val displayWebpageImagesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.DISPLAY_IMAGES))
-                val pinnedSslCertificate = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1
-                val pinnedSslIssuedToCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME))
-                val pinnedSslIssuedToOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION))
-                val pinnedSslIssuedToUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT))
-                val pinnedSslIssuedByCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME))
-                val pinnedSslIssuedByOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION))
-                val pinnedSslIssuedByUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT))
-                val pinnedSslStartDate = Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_START_DATE)))
-                val pinnedSslEndDate = Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.SSL_END_DATE)))
-                val pinnedIpAddresses = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.PINNED_IP_ADDRESSES)) == 1
-                val pinnedHostIpAddresses = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.IP_ADDRESSES))
+        // Set the URI and the mime type.
+        downloadIntent.setDataAndType(Uri.parse(url), "text/html")
 
-                // Close the current host domain settings cursor.
-                currentDomainSettingsCursor.close()
+        // Flag the intent to open in a new task.
+        downloadIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
 
-                // If there is a pinned SSL certificate, store it in the WebView.
-                if (pinnedSslCertificate)
-                    nestedScrollWebView.setPinnedSslCertificate(pinnedSslIssuedToCName, pinnedSslIssuedToOName, pinnedSslIssuedToUName, pinnedSslIssuedByCName, pinnedSslIssuedByOName, pinnedSslIssuedByUName,
-                        pinnedSslStartDate, pinnedSslEndDate)
+        // Show the chooser.
+        startActivity(Intent.createChooser(downloadIntent, getString(R.string.download_with_external_app)))
+    }
 
-                // If there is a pinned IP address, store it in the WebView.
-                if (pinnedIpAddresses)
-                    nestedScrollWebView.pinnedIpAddresses = pinnedHostIpAddresses
+    private fun exitFullScreenVideo() {
+        // Re-enable the screen timeout.
+        fullScreenVideoFrameLayout.keepScreenOn = false
 
-                // Apply the cookie domain settings.
-                cookieManager.setAcceptCookie(nestedScrollWebView.acceptCookies)
+        // Unset the full screen video flag.
+        displayingFullScreenVideo = false
 
-                // Apply the form data setting if the API < 26.
-                @Suppress("DEPRECATION")
-                if (Build.VERSION.SDK_INT < 26)
-                    nestedScrollWebView.settings.saveFormData = saveFormData
+        // Remove all the views from the full screen video frame layout.
+        fullScreenVideoFrameLayout.removeAllViews()
 
-                // Apply the font size.
-                try {  // Try the specified font size to see if it is valid.
-                    if (fontSize == 0) {  // Apply the default font size.
-                        // Set the font size from the value in the app settings.
-                        nestedScrollWebView.settings.textZoom = defaultFontSizeString!!.toInt()
-                    } else {  // Apply the font size from domain settings.
-                        nestedScrollWebView.settings.textZoom = fontSize
-                    }
-                } catch (exception: Exception) {  // The specified font size is invalid
-                    // Set the font size to be 100%
-                    nestedScrollWebView.settings.textZoom = 100
-                }
+        // Hide the full screen video frame layout.
+        fullScreenVideoFrameLayout.visibility = View.GONE
 
-                // Set the user agent.
-                if (userAgentName == getString(R.string.system_default_user_agent)) {  // Use the system default user agent.
-                    // Set the user agent according to the system default.
-                    when (val defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName)) {
-                        // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
-                        UNRECOGNIZED_USER_AGENT -> nestedScrollWebView.settings.userAgentString = defaultUserAgentName
+        // Enable the sliding drawers.
+        drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED)
 
-                        // Set the user agent to `""`, which uses the default value.
-                        SETTINGS_WEBVIEW_DEFAULT_USER_AGENT -> nestedScrollWebView.settings.userAgentString = ""
+        // Show the coordinator layout.
+        coordinatorLayout.visibility = View.VISIBLE
 
-                        // Set the default custom user agent.
-                        SETTINGS_CUSTOM_USER_AGENT -> nestedScrollWebView.settings.userAgentString =
-                            sharedPreferences.getString(getString(R.string.custom_user_agent_key), getString(R.string.custom_user_agent_default_value))
+        // Apply the appropriate full screen mode flags.
+        if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {  // Privacy Browser is currently in full screen browsing mode.
+            // Hide the app bar if specified.
+            if (hideAppBar) {
+                // Hide the tab linear layout.
+                tabsLinearLayout.visibility = View.GONE
 
-                        // Get the user agent string from the user agent data array
-                        else -> nestedScrollWebView.settings.userAgentString = userAgentDataArray[defaultUserAgentArrayPosition]
-                    }
-                } else {  // Set the user agent according to the stored name.
-                    // Set the user agent.
-                    when (val userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName)) {
-                        // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
-                        UNRECOGNIZED_USER_AGENT ->
-                            nestedScrollWebView.settings.userAgentString = userAgentName
+                // Hide the app bar.
+                appBar.hide()
+            }
 
-                        // Set the user agent to `""`, which uses the default value.
-                        SETTINGS_WEBVIEW_DEFAULT_USER_AGENT ->
-                            nestedScrollWebView.settings.userAgentString = ""
+            /* Hide the system bars.
+             * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
+             * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
+             * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
+             * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
+             */
 
-                        // Get the user agent string from the user agent data array.
-                        else ->
-                            nestedScrollWebView.settings.userAgentString = userAgentDataArray[userAgentArrayPosition]
-                    }
-                }
+            // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
+            @Suppress("DEPRECATION")
+            rootFrameLayout.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
+        } else {  // Switch to normal viewing mode.
+            // Remove the `SYSTEM_UI` flags from the root frame layout.  The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
+            @Suppress("DEPRECATION")
+            rootFrameLayout.systemUiVisibility = 0
+        }
+    }
 
-                // Set swipe to refresh.
-                when (swipeToRefreshInt) {
-                    DomainsDatabaseHelper.SYSTEM_DEFAULT -> {
-                        // Store the swipe to refresh status in the nested scroll WebView.
-                        nestedScrollWebView.swipeToRefresh = defaultSwipeToRefresh
+    // The view parameter cannot be removed because it is called from the layout onClick.
+    fun findNextOnPage(@Suppress("UNUSED_PARAMETER")view: View?) {
+        // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
+        currentWebView!!.findNext(true)
+    }
 
-                        // Update the swipe refresh layout.
-                        if (defaultSwipeToRefresh) {  // Swipe to refresh is enabled.
-                            // Update the status of the swipe refresh layout if the current WebView is not null (crash reports indicate that in some unexpected way it sometimes is null).
-                            if (currentWebView != null) {
-                                // Only enable the swipe refresh layout if the WebView is scrolled to the top.  It is updated every time the scroll changes.
-                                swipeRefreshLayout.isEnabled = (currentWebView!!.scrollY == 0)
-                            }
-                        } else {  // Swipe to refresh is disabled.
-                            // Disable the swipe refresh layout.
-                            swipeRefreshLayout.isEnabled = false
-                        }
-                    }
+    // The view parameter cannot be removed because it is called from the layout onClick.
+    fun findPreviousOnPage(@Suppress("UNUSED_PARAMETER")view: View?) {
+        // Go to the previous highlighted phrase on the page.  `false` goes backwards instead of forwards.
+        currentWebView!!.findNext(false)
+    }
 
-                    DomainsDatabaseHelper.ENABLED -> {
-                        // Store the swipe to refresh status in the nested scroll WebView.
-                        nestedScrollWebView.swipeToRefresh = true
+    override fun finishedPopulatingBlocklists(combinedBlocklists: ArrayList<ArrayList<List<Array<String>>>>) {
+        // Store the blocklists.
+        easyList = combinedBlocklists[0]
+        easyPrivacy = combinedBlocklists[1]
+        fanboysAnnoyanceList = combinedBlocklists[2]
+        fanboysSocialList = combinedBlocklists[3]
+        ultraList = combinedBlocklists[4]
+        ultraPrivacy = combinedBlocklists[5]
 
-                        // Update the status of the swipe refresh layout if the current WebView is not null (crash reports indicate that in some unexpected way it sometimes is null).
-                        if (currentWebView != null) {
-                            // Only enable the swipe refresh layout if the WebView is scrolled to the top.  It is updated every time the scroll changes.
-                            swipeRefreshLayout.isEnabled = (currentWebView!!.scrollY == 0)
-                        }
-                    }
+        // Check to see if the activity has been restarted with a saved state.
+        if ((savedStateArrayList == null) || (savedStateArrayList!!.size == 0)) {  // The activity has not been restarted or it was restarted on start to change the theme.
+            // Add the first tab.
+            addNewTab("", true)
+        } else {  // The activity has been restarted.
+            // Restore each tab.
+            for (i in savedStateArrayList!!.indices) {
+                // Add a new tab.
+                tabLayout.addTab(tabLayout.newTab())
 
-                    DomainsDatabaseHelper.DISABLED -> {
-                        // Store the swipe to refresh status in the nested scroll WebView.
-                        nestedScrollWebView.swipeToRefresh = false
+                // Get the new tab.
+                val newTab = tabLayout.getTabAt(i)!!
 
-                        // Disable swipe to refresh.
-                        swipeRefreshLayout.isEnabled = false
-                    }
-                }
+                // Set a custom view on the new tab.
+                newTab.setCustomView(R.layout.tab_custom_view)
 
-                // Set the WebView theme if device is running API >= 29 and algorithmic darkening is supported.
-                if ((Build.VERSION.SDK_INT >= 29) && WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {
-                    // Set the WebView theme.
-                    when (webViewThemeInt) {
-                        // Set the WebView theme.
-                        DomainsDatabaseHelper.SYSTEM_DEFAULT ->
-                            when (webViewTheme) {
-                                // The light theme is selected.  Turn off algorithmic darkening.
-                                webViewThemeEntryValuesStringArray[1] -> WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
+                // Add the new page.
+                webViewPagerAdapter!!.restorePage(savedStateArrayList!![i], savedNestedScrollWebViewStateArrayList!![i])
+            }
 
-                                // The dark theme is selected.  Turn on algorithmic darkening.
-                                webViewThemeEntryValuesStringArray[2] -> WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
+            // Reset the saved state variables.
+            savedStateArrayList = null
+            savedNestedScrollWebViewStateArrayList = null
 
-                                // The system default theme is selected.
-                                else -> {
-                                    // Get the current system theme status.
-                                    val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
+            // Restore the selected tab position.
+            if (savedTabPosition == 0) {  // The first tab is selected.
+                // Set the first page as the current WebView.
+                setCurrentWebView(0)
+            } else {  // The first tab is not selected.
+                // Move to the selected tab.
+                webViewPager.currentItem = savedTabPosition
+            }
 
-                                    // Set the algorithmic darkening according to the current system theme status.
-                                    WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, currentThemeStatus == Configuration.UI_MODE_NIGHT_YES)
-                                }
-                            }
+            // Get the intent that started the app.
+            val intent = intent
 
-                        // Turn off algorithmic darkening.
-                        DomainsDatabaseHelper.LIGHT_THEME -> WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
+            // Reset the intent.  This prevents a duplicate tab from being created on restart.
+            setIntent(Intent())
 
-                        // Turn on algorithmic darkening.
-                        DomainsDatabaseHelper.DARK_THEME -> WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
+            // Get the information from the intent.
+            val intentAction = intent.action
+            val intentUriData = intent.data
+            val intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT)
+
+            // Determine if this is a web search.
+            val isWebSearch = (intentAction != null) && (intentAction == Intent.ACTION_WEB_SEARCH)
+
+            // 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.
+            if ((intentUriData != null) || (intentStringExtra != null) || isWebSearch) {
+                // Get the URL string.
+                val urlString = if (isWebSearch) {  // The intent is a web search.
+                    // Sanitize the search input.
+                    val encodedSearchString: String = try {
+                        URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8")
+                    } catch (exception: UnsupportedEncodingException) {
+                        ""
                     }
-                }
 
-                // Set the wide viewport status.
-                when (wideViewportInt) {
-                    DomainsDatabaseHelper.SYSTEM_DEFAULT -> nestedScrollWebView.settings.useWideViewPort = wideViewport
-                    DomainsDatabaseHelper.ENABLED -> nestedScrollWebView.settings.useWideViewPort = true
-                    DomainsDatabaseHelper.DISABLED -> nestedScrollWebView.settings.useWideViewPort = false
+                    // Add the base search URL.
+                    searchURL + encodedSearchString
+                } else { // The intent contains a URL formatted as a URI or a URL in the string extra.
+                    // Get the URL string.
+                    intentUriData?.toString() ?: intentStringExtra!!
                 }
 
-                // Set the display webpage images status.
-                when (displayWebpageImagesInt) {
-                    DomainsDatabaseHelper.SYSTEM_DEFAULT -> nestedScrollWebView.settings.loadsImagesAutomatically = displayWebpageImages
-                    DomainsDatabaseHelper.ENABLED -> nestedScrollWebView.settings.loadsImagesAutomatically = true
-                    DomainsDatabaseHelper.DISABLED -> nestedScrollWebView.settings.loadsImagesAutomatically = false
+                // Add a new tab if specified in the preferences.
+                if (sharedPreferences.getBoolean(getString(R.string.open_intents_in_new_tab_key), true)) {  // Load the URL in a new tab.
+                    // Set the loading new intent flag.
+                    loadingNewIntent = true
+
+                    // Add a new tab.
+                    addNewTab(urlString, true)
+                } else {  // Load the URL in the current tab.
+                    // Make it so.
+                    loadUrl(currentWebView!!, urlString)
                 }
+            }
+        }
+    }
 
-                // Set a background on the URL relative layout to indicate that custom domain settings are being used.
-                urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.drawable.domain_settings_url_background)
-            } else {  // The new URL does not have custom domain settings.  Load the defaults.
-                // Store the values from the shared preferences.
-                nestedScrollWebView.settings.javaScriptEnabled = sharedPreferences.getBoolean(getString(R.string.javascript_key), false)
-                nestedScrollWebView.acceptCookies = sharedPreferences.getBoolean(getString(R.string.cookies_key), false)
-                nestedScrollWebView.settings.domStorageEnabled = sharedPreferences.getBoolean(getString(R.string.dom_storage_key), false)
-                val saveFormData = sharedPreferences.getBoolean(getString(R.string.save_form_data_key), false) // Form data can be removed once the minimum API >= 26.
-                nestedScrollWebView.easyListEnabled = sharedPreferences.getBoolean(getString(R.string.easylist_key), true)
-                nestedScrollWebView.easyPrivacyEnabled = sharedPreferences.getBoolean(getString(R.string.easyprivacy_key), true)
-                nestedScrollWebView.fanboysAnnoyanceListEnabled = sharedPreferences.getBoolean(getString(R.string.fanboys_annoyance_list_key), true)
-                nestedScrollWebView.fanboysSocialBlockingListEnabled = sharedPreferences.getBoolean(getString(R.string.fanboys_social_blocking_list_key), true)
-                nestedScrollWebView.ultraListEnabled = sharedPreferences.getBoolean(getString(R.string.ultralist_key), true)
-                nestedScrollWebView.ultraPrivacyEnabled = sharedPreferences.getBoolean(getString(R.string.ultraprivacy_key), true)
-                nestedScrollWebView.blockAllThirdPartyRequests = sharedPreferences.getBoolean(getString(R.string.block_all_third_party_requests_key), false)
+    // Remove the warning that `OnTouchListener()` needs to override `performClick()`, as the only purpose of setting the `OnTouchListener()` is to make it do nothing.
+    @SuppressLint("ClickableViewAccessibility")
+    private fun initializeApp() {
+        // Get a handle for the input method.
+        val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
 
-                // Apply the default cookie setting.
-                cookieManager.setAcceptCookie(nestedScrollWebView.acceptCookies)
+        // Initialize the color spans for highlighting the URLs.
+        initialGrayColorSpan = ForegroundColorSpan(getColor(R.color.gray_500))
+        finalGrayColorSpan = ForegroundColorSpan(getColor(R.color.gray_500))
+        redColorSpan = ForegroundColorSpan(getColor(R.color.red_text))
 
-                // Apply the default font size setting.
-                try {
-                    // Try to set the font size from the value in the app settings.
-                    nestedScrollWebView.settings.textZoom = defaultFontSizeString!!.toInt()
-                } catch (exception: Exception) {
-                    // If the app settings value is invalid, set the font size to 100%.
-                    nestedScrollWebView.settings.textZoom = 100
-                }
+        // Remove the formatting from the URL edit text when the user is editing the text.
+        urlEditText.onFocusChangeListener = View.OnFocusChangeListener { _: View?, hasFocus: Boolean ->
+            if (hasFocus) {  // The user is editing the URL text box.
+                // Remove the syntax highlighting.
+                urlEditText.text.removeSpan(redColorSpan)
+                urlEditText.text.removeSpan(initialGrayColorSpan)
+                urlEditText.text.removeSpan(finalGrayColorSpan)
+            } else {  // The user has stopped editing the URL text box.
+                // Move to the beginning of the string.
+                urlEditText.setSelection(0)
 
-                // Apply the form data setting if the API < 26.
-                if (Build.VERSION.SDK_INT < 26)
-                    @Suppress("DEPRECATION")
-                    nestedScrollWebView.settings.saveFormData = saveFormData
+                // Reapply the syntax highlighting.
+                UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
+            }
+        }
 
-                // Store the swipe to refresh status in the nested scroll WebView.
-                nestedScrollWebView.swipeToRefresh = defaultSwipeToRefresh
+        // Set the go button on the keyboard to load the URL in url text box.
+        urlEditText.setOnKeyListener { _: View?, keyCode: Int, keyEvent: KeyEvent ->
+            // If the event is a key-down event on the `enter` button, load the URL.
+            if ((keyEvent.action == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {  // The enter key was pressed.
+                // Load the URL.
+                loadUrlFromTextBox()
 
-                // Update the swipe refresh layout.
-                if (defaultSwipeToRefresh) {  // Swipe to refresh is enabled.
-                    // Update the status of the swipe refresh layout if the current WebView is not null (crash reports indicate that in some unexpected way it sometimes is null).
-                    if (currentWebView != null) {
-                        // Only enable the swipe refresh layout if the WebView is scrolled to the top.  It is updated every time the scroll changes.
-                        swipeRefreshLayout.isEnabled = currentWebView!!.scrollY == 0
-                    }
-                } else {  // Swipe to refresh is disabled.
-                    // Disable the swipe refresh layout.
-                    swipeRefreshLayout.isEnabled = false
-                }
+                // Consume the event.
+                return@setOnKeyListener true
+            } else {  // Some other key was pressed.
+                // Do not consume the event.
+                return@setOnKeyListener false
+            }
+        }
 
-                // Reset the domain settings database ID.
-                nestedScrollWebView.domainSettingsDatabaseId = -1
+        // Create an Orbot status broadcast receiver.
+        orbotStatusBroadcastReceiver = object : BroadcastReceiver() {
+            override fun onReceive(context: Context, intent: Intent) {
+                // Get the content of the status message.
+                orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS")!!
 
-                // Set the user agent.
-                when (val userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName)) {
-                    // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
-                    UNRECOGNIZED_USER_AGENT -> nestedScrollWebView.settings.userAgentString = defaultUserAgentName
+                // If Privacy Browser is waiting on the proxy, load the website now that Orbot is connected.
+                if ((orbotStatus == ProxyHelper.ORBOT_STATUS_ON) && waitingForProxy) {
+                    // Reset the waiting for proxy status.
+                    waitingForProxy = false
 
-                    // Set the user agent to `""`, which uses the default value.
-                    SETTINGS_WEBVIEW_DEFAULT_USER_AGENT -> nestedScrollWebView.settings.userAgentString = ""
+                    // Get a list of the current fragments.
+                    val fragmentList = supportFragmentManager.fragments
 
-                    // Set the default custom user agent.
-                    SETTINGS_CUSTOM_USER_AGENT -> nestedScrollWebView.settings.userAgentString =
-                        sharedPreferences.getString(getString(R.string.custom_user_agent_key), getString(R.string.custom_user_agent_default_value))
+                    // Check each fragment to see if it is a waiting for proxy dialog.  Sometimes more than one is displayed.
+                    for (i in fragmentList.indices) {
+                        // Get the fragment tag.
+                        val fragmentTag = fragmentList[i].tag
 
-                    // Get the user agent string from the user agent data array
-                    else -> nestedScrollWebView.settings.userAgentString = userAgentDataArray[userAgentArrayPosition]
-                }
+                        // Check to see if it is the waiting for proxy dialog.
+                        if (fragmentTag != null && fragmentTag == getString(R.string.waiting_for_proxy_dialog)) {
+                            // Dismiss the waiting for proxy dialog.
+                            (fragmentList[i] as DialogFragment).dismiss()
+                        }
+                    }
 
-                // Set the WebView theme if the device is running API >= 29 and algorithmic darkening is supported.
-                if ((Build.VERSION.SDK_INT >= 29) && WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {
-                    // Set the WebView theme.
-                    when (webViewTheme) {
-                        // The light theme is selected.  Turn off algorithmic darkening.
-                        webViewThemeEntryValuesStringArray[1] -> WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
+                    // Reload existing URLs and load any URLs that are waiting for the proxy.
+                    for (i in 0 until webViewPagerAdapter!!.count) {
+                        // Get the WebView tab fragment.
+                        val webViewTabFragment = webViewPagerAdapter!!.getPageFragment(i)
 
-                        // The dark theme is selected.  Turn on algorithmic darkening.
-                        webViewThemeEntryValuesStringArray[2] -> WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
+                        // Get the fragment view.
+                        val fragmentView = webViewTabFragment.view
+
+                        // Only process the WebViews if they exist.
+                        if (fragmentView != null) {
+                            // Get the nested scroll WebView from the tab fragment.
+                            val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
 
-                        // The system default theme is selected.  Get the current system theme status.
-                        else -> {
-                            // Get the current theme status.
-                            val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
+                            // Get the waiting for proxy URL string.
+                            val waitingForProxyUrlString = nestedScrollWebView.waitingForProxyUrlString
 
-                            // Set the algorithmic darkening according to the current system theme status.
-                            WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, currentThemeStatus == Configuration.UI_MODE_NIGHT_YES)
+                            // Load the pending URL if it exists.
+                            if (waitingForProxyUrlString.isNotEmpty()) {  // A URL is waiting to be loaded.
+                                // Load the URL.
+                                loadUrl(nestedScrollWebView, waitingForProxyUrlString)
+
+                                // Reset the waiting for proxy URL string.
+                                nestedScrollWebView.waitingForProxyUrlString = ""
+                            } else {  // No URL is waiting to be loaded.
+                                // Reload the existing URL.
+                                nestedScrollWebView.reload()
+                            }
                         }
                     }
                 }
-
-                // Set the viewport.
-                nestedScrollWebView.settings.useWideViewPort = wideViewport
-
-                // Set the loading of webpage images.
-                nestedScrollWebView.settings.loadsImagesAutomatically = displayWebpageImages
-
-                // Set a transparent background on the URL relative layout.
-                urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.color.transparent)
             }
-
-            // Update the privacy icons.
-            updatePrivacyIcons(true)
         }
 
-        // Reload the website if returning from the Domains activity.
-        if (reloadWebsite)
-            nestedScrollWebView.reload()
-
-        // Load the URL if directed.  This makes sure that the domain settings are properly loaded before the URL.  By using `loadUrl()`, instead of `loadUrlFromBase()`, the Referer header will never be sent.
-        if (loadUrl)
-            nestedScrollWebView.loadUrl(url)
-    }
+        // Register the Orbot status broadcast receiver.
+        registerReceiver(orbotStatusBroadcastReceiver, IntentFilter("org.torproject.android.intent.action.STATUS"))
 
-    private fun applyProxy(reloadWebViews: Boolean) {
-        // Set the proxy according to the mode.
-        proxyHelper.setProxy(applicationContext, appBarLayout, proxyMode)
+        // Get handles for views that need to be modified.
+        val bookmarksHeaderLinearLayout = findViewById<LinearLayout>(R.id.bookmarks_header_linearlayout)
+        val launchBookmarksActivityFab = findViewById<FloatingActionButton>(R.id.launch_bookmarks_activity_fab)
+        val createBookmarkFolderFab = findViewById<FloatingActionButton>(R.id.create_bookmark_folder_fab)
+        val createBookmarkFab = findViewById<FloatingActionButton>(R.id.create_bookmark_fab)
 
-        // Reset the waiting for proxy tracker.
-        waitingForProxy = false
+        // Update the WebView pager every time a tab is modified.
+        webViewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
+            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}
 
-        // Set the proxy.
-        when (proxyMode) {
-            ProxyHelper.NONE -> {
-                // Initialize a color background typed value.
-                val colorBackgroundTypedValue = TypedValue()
+            override fun onPageSelected(position: Int) {
+                // Close the find on page bar if it is open.
+                closeFindOnPage(null)
 
-                // Get the color background from the theme.
-                theme.resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true)
+                // Set the current WebView.
+                setCurrentWebView(position)
 
-                // Get the color background int from the typed value.
-                val colorBackgroundInt = colorBackgroundTypedValue.data
+                // Select the corresponding tab if it does not match the currently selected page.  This will happen if the page was scrolled by creating a new tab.
+                if (tabLayout.selectedTabPosition != position) {
+                    // Wait until the new tab has been created.
+                    tabLayout.post {
+                        // Get a handle for the tab.
+                        val tab = tabLayout.getTabAt(position)!!
 
-                // Set the default app bar layout background.
-                appBarLayout.setBackgroundColor(colorBackgroundInt)
+                        // Select the tab.
+                        tab.select()
+                    }
+                }
             }
 
-            ProxyHelper.TOR -> {
-                // Set the app bar background to indicate proxying is enabled.
-                appBarLayout.setBackgroundResource(R.color.proxy_appbar_background)
-
-                // Check to see if Orbot is installed.
-                try {
-                    // Get the package manager.
-                    val packageManager = packageManager
-
-                    // 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.  The deprecated method must be used until the minimum API >= 33.
-                    @Suppress("DEPRECATION")
-                    packageManager.getPackageInfo("org.torproject.android", 0)
+            override fun onPageScrollStateChanged(state: Int) {}
+        })
 
-                    // Check to see if the proxy is ready.
-                    if (orbotStatus != ProxyHelper.ORBOT_STATUS_ON) {  // Orbot is not ready.
-                        // Set the waiting for proxy status.
-                        waitingForProxy = true
+        // Handle tab selections.
+        tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
+            override fun onTabSelected(tab: TabLayout.Tab) {
+                // Select the same page in the view pager.
+                webViewPager.currentItem = tab.position
+            }
 
-                        // Show the waiting for proxy dialog if it isn't already displayed.
-                        if (supportFragmentManager.findFragmentByTag(getString(R.string.waiting_for_proxy_dialog)) == null) {
-                            // Get a handle for the waiting for proxy alert dialog.
-                            val waitingForProxyDialogFragment = WaitingForProxyDialog()
+            override fun onTabUnselected(tab: TabLayout.Tab) {}
 
-                            // Try to show the dialog.  Sometimes the window is not yet active if returning from Settings.
-                            try {
-                                // Show the waiting for proxy alert dialog.
-                                waitingForProxyDialogFragment.show(supportFragmentManager, getString(R.string.waiting_for_proxy_dialog))
-                            } catch (waitingForTorException: Exception) {
-                                // Add the dialog to the pending dialog array list.  It will be displayed in `onStart()`.
-                                pendingDialogsArrayList.add(PendingDialogDataClass(waitingForProxyDialogFragment, getString(R.string.waiting_for_proxy_dialog)))
-                            }
-                        }
-                    }
-                } catch (exception: PackageManager.NameNotFoundException) {  // Orbot is not installed.
-                    // Show the Orbot not installed dialog if it is not already displayed.
-                    if (supportFragmentManager.findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
-                        // Get a handle for the Orbot not installed alert dialog.
-                        val orbotNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode)
+            override fun onTabReselected(tab: TabLayout.Tab) {
+                // Instantiate the View SSL Certificate dialog.
+                val viewSslCertificateDialogFragment: DialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView!!.webViewFragmentId, currentWebView!!.getFavoriteIcon())
 
-                        // Try to show the dialog.  Sometimes the window is not yet active if returning from Settings.
-                        try {
-                            // Display the Orbot not installed alert dialog.
-                            orbotNotInstalledDialogFragment.show(supportFragmentManager, getString(R.string.proxy_not_installed_dialog))
-                        } catch (orbotNotInstalledException: Exception) {
-                            // Add the dialog to the pending dialog array list.  It will be displayed in `onStart()`.
-                            pendingDialogsArrayList.add(PendingDialogDataClass(orbotNotInstalledDialogFragment, getString(R.string.proxy_not_installed_dialog)))
-                        }
-                    }
-                }
+                // Display the View SSL Certificate dialog.
+                viewSslCertificateDialogFragment.show(supportFragmentManager, getString(R.string.view_ssl_certificate))
             }
+        })
 
-            ProxyHelper.I2P -> {
-                // Set the app bar background to indicate proxying is enabled.
-                appBarLayout.setBackgroundResource(R.color.proxy_appbar_background)
+        // Set a touch listener on the bookmarks header linear layout so that touches don't pass through to the button underneath.
+        bookmarksHeaderLinearLayout.setOnTouchListener { _: View?, _: MotionEvent? -> true }
 
-                // Check to see if I2P is installed.
-                try {
-                    // Check to see if the F-Droid flavor is installed.  This will throw an error and drop to the catch section if it isn't installed.
-                    // The deprecated method must be used until the minimum API >= 33.
-                    @Suppress("DEPRECATION")
-                    packageManager.getPackageInfo("net.i2p.android.router", 0)
-                } catch (fdroidException: PackageManager.NameNotFoundException) {  // The F-Droid flavor is not installed.
-                    try {
-                        // Check to see if the Google Play flavor is installed.  This will throw an error and drop to the catch section if it isn't installed.
-                        // The deprecated method must be used until the minimum API >= 33.
-                        @Suppress("DEPRECATION")
-                        packageManager.getPackageInfo("net.i2p.android", 0)
-                    } catch (googlePlayException: PackageManager.NameNotFoundException) {  // The Google Play flavor is not installed.
-                        // Sow the I2P not installed dialog if it is not already displayed.
-                        if (supportFragmentManager.findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
-                            // Get a handle for the waiting for proxy alert dialog.
-                            val i2pNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode)
+        // Set the launch bookmarks activity floating action button to launch the bookmarks activity.
+        launchBookmarksActivityFab.setOnClickListener {
+            // Get a copy of the favorite icon bitmap.
+            val currentFavoriteIconBitmap = currentWebView!!.getFavoriteIcon()
 
-                            // Try to show the dialog.  Sometimes the window is not yet active if returning from Settings.
-                            try {
-                                // Display the I2P not installed alert dialog.
-                                i2pNotInstalledDialogFragment.show(supportFragmentManager, getString(R.string.proxy_not_installed_dialog))
-                            } catch (i2pNotInstalledException: Exception) {
-                                // Add the dialog to the pending dialog array list.  It will be displayed in `onStart()`.
-                                pendingDialogsArrayList.add(PendingDialogDataClass(i2pNotInstalledDialogFragment, getString(R.string.proxy_not_installed_dialog)))
-                            }
-                        }
-                    }
-                }
-            }
+            // Create a favorite icon byte array output stream.
+            val currentFavoriteIconByteArrayOutputStream = ByteArrayOutputStream()
 
-            ProxyHelper.CUSTOM ->
-                // Set the app bar background to indicate proxying is enabled.
-                appBarLayout.setBackgroundResource(R.color.proxy_appbar_background)
-        }
+            // Convert the favorite icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
+            currentFavoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, currentFavoriteIconByteArrayOutputStream)
 
-        // Reload the WebViews if requested and not waiting for the proxy.
-        if (reloadWebViews && !waitingForProxy) {
-            // Reload the WebViews.
-            for (i in 0 until webViewPagerAdapter!!.count) {
-                // Get the WebView tab fragment.
-                val webViewTabFragment = webViewPagerAdapter!!.getPageFragment(i)
+            // Convert the favorite icon byte array stream to a byte array.
+            val currentFavoriteIconByteArray = currentFavoriteIconByteArrayOutputStream.toByteArray()
 
-                // Get the fragment view.
-                val fragmentView = webViewTabFragment.view
+            // Create an intent to launch the bookmarks activity.
+            val bookmarksIntent = Intent(applicationContext, BookmarksActivity::class.java)
 
-                // Only reload the WebViews if they exist.
-                if (fragmentView != null) {
-                    // Get the nested scroll WebView from the tab fragment.
-                    val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
+            // Add the extra information to the intent.
+            bookmarksIntent.putExtra(CURRENT_FOLDER, currentBookmarksFolder)
+            bookmarksIntent.putExtra(CURRENT_TITLE, currentWebView!!.title)
+            bookmarksIntent.putExtra(CURRENT_URL, currentWebView!!.url)
+            bookmarksIntent.putExtra(CURRENT_FAVORITE_ICON_BYTE_ARRAY, currentFavoriteIconByteArray)
 
-                    // Reload the WebView.
-                    nestedScrollWebView.reload()
-                }
-            }
+            // Make it so.
+            startActivity(bookmarksIntent)
         }
-    }
 
-    private fun updatePrivacyIcons(runInvalidateOptionsMenu: Boolean) {
-        // Only update the privacy icons if the options menu and the current WebView have already been populated.
-        if ((optionsMenu != null) && (currentWebView != null)) {
-            // Update the privacy icon.
-            if (currentWebView!!.settings.javaScriptEnabled)  // JavaScript is enabled.
-                optionsPrivacyMenuItem.setIcon(R.drawable.javascript_enabled)
-            else if (currentWebView!!.acceptCookies)  // JavaScript is disabled but cookies are enabled.
-                optionsPrivacyMenuItem.setIcon(R.drawable.warning)
-            else  // All the dangerous features are disabled.
-                optionsPrivacyMenuItem.setIcon(R.drawable.privacy_mode)
+        // Set the create new bookmark folder floating action button to display an alert dialog.
+        createBookmarkFolderFab.setOnClickListener {
+            // Create a create bookmark folder dialog.
+            val createBookmarkFolderDialog: DialogFragment = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView!!.getFavoriteIcon())
 
-            // Update the cookies icon.
-            if (currentWebView!!.acceptCookies)
-                optionsCookiesMenuItem.setIcon(R.drawable.cookies_enabled)
-            else
-                optionsCookiesMenuItem.setIcon(R.drawable.cookies_disabled)
+            // Show the create bookmark folder dialog.
+            createBookmarkFolderDialog.show(supportFragmentManager, getString(R.string.create_folder))
+        }
 
-            // Update the refresh icon.
-            if (optionsRefreshMenuItem.title == getString(R.string.refresh))  // The refresh icon is displayed.
-                optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled)
-            else  // The stop icon is displayed.
-                optionsRefreshMenuItem.setIcon(R.drawable.close_blue)
+        // Set the create new bookmark floating action button to display an alert dialog.
+        createBookmarkFab.setOnClickListener {
+            // Instantiate the create bookmark dialog.
+            val createBookmarkDialog: DialogFragment = CreateBookmarkDialog.createBookmark(currentWebView!!.url!!, currentWebView!!.title!!, currentWebView!!.getFavoriteIcon())
 
-            // `invalidateOptionsMenu()` calls `onPrepareOptionsMenu()` and redraws the icons in the app bar.
-            if (runInvalidateOptionsMenu)
-                invalidateOptionsMenu()
+            // Display the create bookmark dialog.
+            createBookmarkDialog.show(supportFragmentManager, getString(R.string.create_bookmark))
         }
-    }
 
-    private fun loadBookmarksFolder() {
-        // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
-        bookmarksCursor = bookmarksDatabaseHelper!!.getBookmarksByDisplayOrder(currentBookmarksFolder)
+        // Search for the string on the page whenever a character changes in the find on page edit text.
+        findOnPageEditText.addTextChangedListener(object : TextWatcher {
+            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
+
+            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
 
-        // Populate the bookmarks cursor adapter.
-        bookmarksCursorAdapter = object : CursorAdapter(this, bookmarksCursor, false) {
-            override fun newView(context: Context, cursor: Cursor, parent: ViewGroup): View {
-                // Inflate the individual item layout.
-                return layoutInflater.inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false)
+            override fun afterTextChanged(s: Editable) {
+                // 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.
+                currentWebView?.findAllAsync(findOnPageEditText.text.toString())
             }
+        })
 
-            override fun bindView(view: View, context: Context, cursor: Cursor) {
-                // Get handles for the views.
-                val bookmarkFavoriteIcon = view.findViewById<ImageView>(R.id.bookmark_favorite_icon)
-                val bookmarkNameTextView = view.findViewById<TextView>(R.id.bookmark_name)
+        // Set the `check mark` button for the find on page edit text keyboard to close the soft keyboard.
+        findOnPageEditText.setOnKeyListener { _: View?, keyCode: Int, keyEvent: KeyEvent ->
+            if ((keyEvent.action == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {  // The `enter` key was pressed.
+                // Hide the soft keyboard.
+                inputMethodManager.hideSoftInputFromWindow(currentWebView!!.windowToken, 0)
 
-                // Get the favorite icon byte array from the cursor.
-                val favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.FAVORITE_ICON))
+                // Consume the event.
+                return@setOnKeyListener true
+            } else {  // A different key was pressed.
+                // Do not consume the event.
+                return@setOnKeyListener false
+            }
+        }
 
-                // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
-                val favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.size)
+        // Implement swipe to refresh.
+        swipeRefreshLayout.setOnRefreshListener {
+            // Reload the website.
+            currentWebView!!.reload()
+        }
 
-                // Display the bitmap in the bookmark favorite icon.
-                bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap)
+        // Store the default progress view offsets.
+        defaultProgressViewStartOffset = swipeRefreshLayout.progressViewStartOffset
+        defaultProgressViewEndOffset = swipeRefreshLayout.progressViewEndOffset
 
-                // Display the bookmark name from the cursor in the bookmark name text view.
-                bookmarkNameTextView.text = cursor.getString(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME))
+        // Set the refresh color scheme according to the theme.
+        swipeRefreshLayout.setColorSchemeResources(R.color.blue_text)
 
-                // Make the font bold for folders.
-                if (cursor.getInt(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.IS_FOLDER)) == 1)
-                    bookmarkNameTextView.typeface = Typeface.DEFAULT_BOLD
-                else  // Reset the font to default for normal bookmarks.
-                    bookmarkNameTextView.typeface = Typeface.DEFAULT
-            }
-        }
+        // Initialize a color background typed value.
+        val colorBackgroundTypedValue = TypedValue()
 
-        // Populate the list view with the adapter.
-        bookmarksListView.adapter = bookmarksCursorAdapter
+        // Get the color background from the theme.
+        theme.resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true)
 
-        // Set the bookmarks drawer title.
-        if (currentBookmarksFolder.isEmpty())
-            bookmarksTitleTextView.setText(R.string.bookmarks)
-        else
-            bookmarksTitleTextView.text = currentBookmarksFolder
-    }
+        // Get the color background int from the typed value.
+        val colorBackgroundInt = colorBackgroundTypedValue.data
 
-    private fun openWithApp(url: String) {
-        // Create an open with app intent with `ACTION_VIEW`.
-        val openWithAppIntent = Intent(Intent.ACTION_VIEW)
+        // Set the swipe refresh background color.
+        swipeRefreshLayout.setProgressBackgroundColorSchemeColor(colorBackgroundInt)
 
-        // Set the URI but not the MIME type.  This should open all available apps.
-        openWithAppIntent.data = Uri.parse(url)
+        // Set the drawer titles, which identify the drawer layouts in accessibility mode.
+        drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer))
+        drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks))
 
-        // Flag the intent to open in a new task.
-        openWithAppIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
+        // Load the bookmarks folder.
+        loadBookmarksFolder()
 
-        // Try the intent.
-        try {
-            // Show the chooser.
-            startActivity(openWithAppIntent)
-        } catch (exception: ActivityNotFoundException) {  // There are no apps available to open the URL.
-            // Show a snackbar with the error.
-            Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
-        }
-    }
+        // Handle clicks on bookmarks.
+        bookmarksListView.onItemClickListener = AdapterView.OnItemClickListener { _: AdapterView<*>?, _: View?, _: Int, id: Long ->
+            // Convert the id from long to int to match the format of the bookmarks database.
+            val databaseId = id.toInt()
 
-    private fun openWithBrowser(url: String) {
+            // Get the bookmark cursor for this ID.
+            val bookmarkCursor = bookmarksDatabaseHelper!!.getBookmark(databaseId)
 
-        // Create an open with browser intent with `ACTION_VIEW`.
-        val openWithBrowserIntent = Intent(Intent.ACTION_VIEW)
+            // Move the bookmark cursor to the first row.
+            bookmarkCursor.moveToFirst()
 
-        // Set the URI and the MIME type.  `"text/html"` should load browser options.
-        openWithBrowserIntent.setDataAndType(Uri.parse(url), "text/html")
+            // Act upon the bookmark according to the type.
+            if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {  // The selected bookmark is a folder.
+                // Store the folder name.
+                currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME))
 
-        // Flag the intent to open in a new task.
-        openWithBrowserIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
+                // Load the new folder.
+                loadBookmarksFolder()
+            } else {  // The selected bookmark is not a folder.
+                // Load the bookmark URL.
+                loadUrl(currentWebView!!, bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_URL)))
 
-        // Try the intent.
-        try {
-            // Show the chooser.
-            startActivity(openWithBrowserIntent)
-        } catch (exception: ActivityNotFoundException) {  // There are no browsers available to open the URL.
-            // Show a snackbar with the error.
-            Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
+                // Close the bookmarks drawer if it is not pinned.
+                if (!bookmarksDrawerPinned)
+                    drawerLayout.closeDrawer(GravityCompat.END)
+            }
+
+            // Close the cursor.
+            bookmarkCursor.close()
         }
-    }
 
-    private fun sanitizeUrl(urlString: String): String {
-        // Initialize a sanitized URL string.
-        var sanitizedUrlString = urlString
+        // Handle long-presses on bookmarks.
+        bookmarksListView.onItemLongClickListener = AdapterView.OnItemLongClickListener { _: AdapterView<*>?, _: View?, _: Int, id: Long ->
+            // Convert the database ID from `long` to `int`.
+            val databaseId = id.toInt()
 
-        // Sanitize tracking queries.
-        if (sanitizeTrackingQueries)
-            sanitizedUrlString = SanitizeUrlHelper.sanitizeTrackingQueries(sanitizedUrlString)
+            // Run the commands associated with the type.
+            if (bookmarksDatabaseHelper!!.isFolder(databaseId)) {  // The bookmark is a folder.
+                // Get a cursor of all the bookmarks in the folder.
+                val bookmarksCursor = bookmarksDatabaseHelper!!.getFolderBookmarks(databaseId)
 
-        // Sanitize AMP redirects.
-        if (sanitizeAmpRedirects)
-            sanitizedUrlString = SanitizeUrlHelper.sanitizeAmpRedirects(sanitizedUrlString)
+                // Move to the first entry in the cursor.
+                bookmarksCursor.moveToFirst()
 
-        // Return the sanitized URL string.
-        return sanitizedUrlString
-    }
+                // Open each bookmark
+                for (i in 0 until bookmarksCursor.count) {
+                    // Load the bookmark in a new tab, moving to the tab for the first bookmark if the drawer is not pinned.
+                    addNewTab(bookmarksCursor.getString(bookmarksCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_URL)), !bookmarksDrawerPinned && (i == 0))
 
-    override fun finishedPopulatingBlocklists(combinedBlocklists: ArrayList<ArrayList<List<Array<String>>>>) {
-        // Store the blocklists.
-        easyList = combinedBlocklists[0]
-        easyPrivacy = combinedBlocklists[1]
-        fanboysAnnoyanceList = combinedBlocklists[2]
-        fanboysSocialList = combinedBlocklists[3]
-        ultraList = combinedBlocklists[4]
-        ultraPrivacy = combinedBlocklists[5]
+                    // Move to the next bookmark.
+                    bookmarksCursor.moveToNext()
+                }
 
-        // Check to see if the activity has been restarted with a saved state.
-        if ((savedStateArrayList == null) || (savedStateArrayList!!.size == 0)) {  // The activity has not been restarted or it was restarted on start to change the theme.
-            // Add the first tab.
-            addNewTab("", true)
-        } else {  // The activity has been restarted.
-            // Restore each tab.
-            for (i in savedStateArrayList!!.indices) {
-                // Add a new tab.
-                tabLayout.addTab(tabLayout.newTab())
+                // Close the cursor.
+                bookmarksCursor.close()
+            } else {  // The bookmark is not a folder.
+                // Get the bookmark cursor for this ID.
+                val bookmarkCursor = bookmarksDatabaseHelper!!.getBookmark(databaseId)
 
-                // Get the new tab.
-                val newTab = tabLayout.getTabAt(i)!!
+                // Move the bookmark cursor to the first row.
+                bookmarkCursor.moveToFirst()
 
-                // Set a custom view on the new tab.
-                newTab.setCustomView(R.layout.tab_custom_view)
+                // Load the bookmark in a new tab and move to the tab if the drawer is not pinned.
+                addNewTab(bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_URL)), !bookmarksDrawerPinned)
 
-                // Add the new page.
-                webViewPagerAdapter!!.restorePage(savedStateArrayList!![i], savedNestedScrollWebViewStateArrayList!![i])
+                // Close the cursor.
+                bookmarkCursor.close()
             }
 
-            // Reset the saved state variables.
-            savedStateArrayList = null
-            savedNestedScrollWebViewStateArrayList = null
+            // Close the bookmarks drawer if it is not pinned.
+            if (!bookmarksDrawerPinned)
+                drawerLayout.closeDrawer(GravityCompat.END)
 
-            // Restore the selected tab position.
-            if (savedTabPosition == 0) {  // The first tab is selected.
-                // Set the first page as the current WebView.
-                setCurrentWebView(0)
-            } else {  // The first tab is not selected.
-                // Move to the selected tab.
-                webViewPager.currentItem = savedTabPosition
-            }
+            // Consume the event.
+            true
+        }
 
-            // Get the intent that started the app.
-            val intent = intent
+        // The drawer listener is used to update the navigation menu.
+        drawerLayout.addDrawerListener(object : DrawerLayout.DrawerListener {
+            override fun onDrawerSlide(drawerView: View, slideOffset: Float) {}
 
-            // Reset the intent.  This prevents a duplicate tab from being created on restart.
-            setIntent(Intent())
+            override fun onDrawerOpened(drawerView: View) {}
 
-            // Get the information from the intent.
-            val intentAction = intent.action
-            val intentUriData = intent.data
-            val intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT)
+            override fun onDrawerClosed(drawerView: View) {
+                // Reset the drawer icon when the drawer is closed.  Otherwise, it remains an arrow if the drawer is open when the app is restarted.
+                actionBarDrawerToggle!!.syncState()
+            }
 
-            // Determine if this is a web search.
-            val isWebSearch = (intentAction != null) && (intentAction == Intent.ACTION_WEB_SEARCH)
+            override fun onDrawerStateChanged(newState: Int) {
+                if (newState == DrawerLayout.STATE_SETTLING || newState == DrawerLayout.STATE_DRAGGING) {  // A drawer is opening or closing.
+                    // Update the navigation menu items if the WebView is not null.
+                    if (currentWebView != null) {
+                        navigationBackMenuItem.isEnabled = currentWebView!!.canGoBack()
+                        navigationForwardMenuItem.isEnabled = currentWebView!!.canGoForward()
+                        navigationHistoryMenuItem.isEnabled = currentWebView!!.canGoBack() || currentWebView!!.canGoForward()
+                        navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + currentWebView!!.getRequestsCount(BLOCKED_REQUESTS)
 
-            // 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.
-            if ((intentUriData != null) || (intentStringExtra != null) || isWebSearch) {
-                // Get the URL string.
-                val urlString = if (isWebSearch) {  // The intent is a web search.
-                    // Sanitize the search input.
-                    val encodedSearchString: String = try {
-                        URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8")
-                    } catch (exception: UnsupportedEncodingException) {
-                        ""
+                        // Hide the keyboard (if displayed).
+                        inputMethodManager.hideSoftInputFromWindow(currentWebView!!.windowToken, 0)
                     }
 
-                    // Add the base search URL.
-                    searchURL + encodedSearchString
-                } else { // The intent contains a URL formatted as a URI or a URL in the string extra.
-                    // Get the URL string.
-                    intentUriData?.toString() ?: intentStringExtra!!
-                }
-
-                // Add a new tab if specified in the preferences.
-                if (sharedPreferences.getBoolean(getString(R.string.open_intents_in_new_tab_key), true)) {  // Load the URL in a new tab.
-                    // Set the loading new intent flag.
-                    loadingNewIntent = true
+                    // Clear the focus from from the URL text box.  This removes any text selection markers and context menus, which otherwise draw above the open drawers.
+                    urlEditText.clearFocus()
 
-                    // Add a new tab.
-                    addNewTab(urlString, true)
-                } else {  // Load the URL in the current tab.
-                    // Make it so.
-                    loadUrl(currentWebView!!, urlString)
+                    // Clear the focus from from the WebView if it is not null, which can happen if a user opens a drawer while the browser is being resumed.
+                    // Clearing the focus from the WebView removes any text selection markers and context menus, which otherwise draw above the open drawers.
+                    currentWebView?.clearFocus()
                 }
             }
-        }
-    }
+        })
 
-    // The view parameter cannot be removed because it is called from the layout onClick.
-    fun addTab(@Suppress("UNUSED_PARAMETER")view: View?) {
-        // Add a new tab with a blank URL.
-        addNewTab("", true)
-    }
+        // Inflate a bare WebView to get the default user agent.  It is not used to render content on the screen.
+        @SuppressLint("InflateParams") val webViewLayout = layoutInflater.inflate(R.layout.bare_webview, null, false)
 
-    private fun addNewTab(urlString: String, moveToTab: Boolean) {
-        // Clear the focus from the URL edit text, so that it will be populated with the information from the new tab.
-        urlEditText.clearFocus()
+        // Get a handle for the WebView.
+        val bareWebView = webViewLayout.findViewById<WebView>(R.id.bare_webview)
 
-        // Get the new page number.  The page numbers are 0 indexed, so the new page number will match the current count.
-        val newTabNumber = tabLayout.tabCount
+        // Store the default user agent.
+        webViewDefaultUserAgent = bareWebView.settings.userAgentString
 
-        // Add a new tab.
-        tabLayout.addTab(tabLayout.newTab())
+        // Destroy the bare WebView.
+        bareWebView.destroy()
 
-        // Get the new tab.
-        val newTab = tabLayout.getTabAt(newTabNumber)!!
+        // Update the domains settings set.
+        updateDomainsSettingsSet()
 
-        // Set a custom view on the new tab.
-        newTab.setCustomView(R.layout.tab_custom_view)
+        // Instantiate the check blocklist helper.
+        checkBlocklistHelper = CheckBlocklistHelper()
+    }
 
-        // Add the new WebView page.
-        webViewPagerAdapter!!.addPage(newTabNumber, webViewPager, urlString, moveToTab)
+    @SuppressLint("ClickableViewAccessibility")
+    override fun initializeWebView(nestedScrollWebView: NestedScrollWebView, pageNumber: Int, progressBar: ProgressBar, urlString: String, restoringState: Boolean) {
+        // Get the WebView theme.
+        val webViewTheme = sharedPreferences.getString(getString(R.string.webview_theme_key), getString(R.string.webview_theme_default_value))
 
-        // Show the app bar if it is at the bottom of the screen and the new tab is taking focus.
-        if (bottomAppBar && moveToTab && appBarLayout.translationY != 0f) {
-            // Animate the bottom app bar onto the screen.
-            objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0f)
+        // Get the WebView theme entry values string array.
+        val webViewThemeEntryValuesStringArray = resources.getStringArray(R.array.webview_theme_entry_values)
 
-            // Make it so.
-            objectAnimator.start()
+        // Set the WebView theme if device is running API >= 29 and algorithmic darkening is supported.
+        if (Build.VERSION.SDK_INT >= 29 && WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {
+            // Set the WebView them.  A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
+            if (webViewTheme == webViewThemeEntryValuesStringArray[1]) {  // The light theme is selected.
+                // Turn off algorithmic darkening.
+                WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
+
+                // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
+                // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
+                nestedScrollWebView.visibility = View.VISIBLE
+            } else if (webViewTheme == webViewThemeEntryValuesStringArray[2]) {  // The dark theme is selected.
+                // Turn on algorithmic darkening.
+                WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
+            } else {  // The system default theme is selected.
+                // Get the current theme status.
+                val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
+
+                // Set the algorithmic darkening according to the current system theme status.
+                if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {  // The system is in day mode.
+                    // Turn off algorithmic darkening.
+                    WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
+
+                    // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
+                    // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
+                    nestedScrollWebView.visibility = View.VISIBLE
+                } else {  // The system is in night mode.
+                    // Turn on algorithmic darkening.
+                    WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
+                }
+            }
         }
-    }
 
-    // The view parameter cannot be removed because it is called from the layout onClick.
-    fun closeTab(@Suppress("UNUSED_PARAMETER")view: View?) {
-        // Run the command according to the number of tabs.
-        if (tabLayout.tabCount > 1)  // There is more than one tab open.
-            closeCurrentTab()
-        else  // There is only one tab open.
-            clearAndExit()
-    }
+        // Get a handle for the input method manager.
+        val inputMethodManager = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
 
-    private fun closeCurrentTab() {
-        // Get the current tab number.
-        val currentTabNumber = tabLayout.selectedTabPosition
+        // Set the app bar scrolling.
+        nestedScrollWebView.isNestedScrollingEnabled = scrollAppBar
 
-        // Delete the current tab.
-        tabLayout.removeTabAt(currentTabNumber)
+        // Allow pinch to zoom.
+        nestedScrollWebView.settings.builtInZoomControls = true
 
-        // Delete the current page.  If the selected page number did not change during the delete (because the newly selected tab has has same number as the previously deleted tab), it will return true,
-        // meaning that the current WebView must be reset.  Otherwise it will happen automatically as the selected tab number changes.
-        if (webViewPagerAdapter!!.deletePage(currentTabNumber, webViewPager))
-            setCurrentWebView(currentTabNumber)
-    }
+        // Hide zoom controls.
+        nestedScrollWebView.settings.displayZoomControls = false
 
-    private fun exitFullScreenVideo() {
-        // Re-enable the screen timeout.
-        fullScreenVideoFrameLayout.keepScreenOn = false
+        // Don't allow mixed content (HTTP and HTTPS) on the same website.
+        nestedScrollWebView.settings.mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW
 
-        // Unset the full screen video flag.
-        displayingFullScreenVideo = false
+        // Set the WebView to load in overview mode (zoomed out to the maximum width).
+        nestedScrollWebView.settings.loadWithOverviewMode = true
 
-        // Remove all the views from the full screen video frame layout.
-        fullScreenVideoFrameLayout.removeAllViews()
+        // Explicitly disable geolocation.
+        nestedScrollWebView.settings.setGeolocationEnabled(false)
 
-        // Hide the full screen video frame layout.
-        fullScreenVideoFrameLayout.visibility = View.GONE
+        // Allow loading of file:// URLs.  This is necessary for opening MHT web archives, which are copied into a temporary cache location.
+        nestedScrollWebView.settings.allowFileAccess = true
 
-        // Enable the sliding drawers.
-        drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED)
+        // Create a double-tap gesture detector to toggle full-screen mode.
+        val doubleTapGestureDetector = GestureDetector(this, object : GestureDetector.SimpleOnGestureListener() {
+            // Override `onDoubleTap()`.  All other events are handled using the default settings.
+            override fun onDoubleTap(motionEvent: MotionEvent): Boolean {
+                return if (fullScreenBrowsingModeEnabled) {  // Only process the double-tap if full screen browsing mode is enabled.
+                    // Toggle the full screen browsing mode tracker.
+                    inFullScreenBrowsingMode = !inFullScreenBrowsingMode
 
-        // Show the coordinator layout.
-        coordinatorLayout.visibility = View.VISIBLE
+                    // Toggle the full screen browsing mode.
+                    if (inFullScreenBrowsingMode) {  // Switch to full screen mode.
+                        // Hide the app bar if specified.
+                        if (hideAppBar) {  // App bar hiding is enabled.
+                            // Close the find on page bar if it is visible.
+                            closeFindOnPage(null)
 
-        // Apply the appropriate full screen mode flags.
-        if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {  // Privacy Browser is currently in full screen browsing mode.
-            // Hide the app bar if specified.
-            if (hideAppBar) {
-                // Hide the tab linear layout.
-                tabsLinearLayout.visibility = View.GONE
+                            // Hide the tab linear layout.
+                            tabsLinearLayout.visibility = View.GONE
 
-                // Hide the app bar.
-                appBar.hide()
-            }
+                            // Hide the app bar.
+                            appBar.hide()
 
-            /* Hide the system bars.
-             * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
-             * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
-             * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
-             * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
-             */
+                            // Set layout and scrolling parameters according to the position of the app bar.
+                            if (bottomAppBar) {  // The app bar is at the bottom.
+                                // Reset the WebView padding to fill the available space.
+                                swipeRefreshLayout.setPadding(0, 0, 0, 0)
+                            } else {  // The app bar is at the top.
+                                // Check to see if the app bar is normally scrolled.
+                                if (scrollAppBar) {  // The app bar is scrolled when it is displayed.
+                                    // Get the swipe refresh layout parameters.
+                                    val swipeRefreshLayoutParams = swipeRefreshLayout.layoutParams as CoordinatorLayout.LayoutParams
 
-            // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
-            @Suppress("DEPRECATION")
-            rootFrameLayout.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
-        } else {  // Switch to normal viewing mode.
-            // Remove the `SYSTEM_UI` flags from the root frame layout.  The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
-            @Suppress("DEPRECATION")
-            rootFrameLayout.systemUiVisibility = 0
-        }
-    }
+                                    // Remove the off-screen scrolling layout.
+                                    swipeRefreshLayoutParams.behavior = null
+                                } else {  // The app bar is not scrolled when it is displayed.
+                                    // Remove the padding from the top of the swipe refresh layout.
+                                    swipeRefreshLayout.setPadding(0, 0, 0, 0)
 
-    private fun clearAndExit() {
-        // Close the cursor and databases.  TODO:  Also domains cursor.
-        bookmarksCursor?.close()
-        bookmarksDatabaseHelper?.close()
-        domainsDatabaseHelper?.close()
+                                    // The swipe refresh circle must be moved above the now removed status bar location.
+                                    swipeRefreshLayout.setProgressViewOffset(false, -200, defaultProgressViewEndOffset)
+                                }
+                            }
+                        } else {  // App bar hiding is not enabled.
+                            // Adjust the UI for the bottom app bar.
+                            if (bottomAppBar) {
+                                // Adjust the UI according to the scrolling of the app bar.
+                                if (scrollAppBar) {
+                                    // Reset the WebView padding to fill the available space.
+                                    swipeRefreshLayout.setPadding(0, 0, 0, 0)
+                                } else {
+                                    // Move the WebView above the app bar layout.
+                                    swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
+                                }
+                            }
+                        }
 
-        // Get the status of the clear everything preference.
-        val clearEverything = sharedPreferences.getBoolean(getString(R.string.clear_everything_key), true)
+                        /* Hide the system bars.
+                         * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
+                         * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
+                         * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
+                         * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
+                         */
 
-        // Get a handle for the runtime.
-        val runtime = Runtime.getRuntime()
+                        // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
+                        @Suppress("DEPRECATION")
+                        rootFrameLayout.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
+                                View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
+                    } else {  // Switch to normal viewing mode.
+                        // Show the app bar if it was hidden.
+                        if (hideAppBar) {
+                            // Show the tab linear layout.
+                            tabsLinearLayout.visibility = View.VISIBLE
 
-        // 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`.
-        val privateDataDirectoryString = applicationInfo.dataDir
+                            // Show the app bar.
+                            appBar.show()
+                        }
+
+                        // Set layout and scrolling parameters according to the position of the app bar.
+                        if (bottomAppBar) {  // The app bar is at the bottom.
+                            // Adjust the UI.
+                            if (scrollAppBar) {
+                                // Reset the WebView padding to fill the available space.
+                                swipeRefreshLayout.setPadding(0, 0, 0, 0)
+                            } else {
+                                // Move the WebView above the app bar layout.
+                                swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
+                            }
+                        } else {  // The app bar is at the top.
+                            // Check to see if the app bar is normally scrolled.
+                            if (scrollAppBar) {  // The app bar is scrolled when it is displayed.
+                                // Get the swipe refresh layout parameters.
+                                val swipeRefreshLayoutParams = swipeRefreshLayout.layoutParams as CoordinatorLayout.LayoutParams
+
+                                // Add the off-screen scrolling layout.
+                                swipeRefreshLayoutParams.behavior = AppBarLayout.ScrollingViewBehavior()
+                            } else {  // The app bar is not scrolled when it is displayed.
+                                // The swipe refresh layout must be manually moved below the app bar layout.
+                                swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0)
+
+                                // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
+                                swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight)
+                            }
+                        }
+
+                        // Remove the `SYSTEM_UI` flags from the root frame layout.  The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
+                        @Suppress("DEPRECATION")
+                        rootFrameLayout.systemUiVisibility = 0
+                    }
+
+                    // Consume the double-tap.
+                    true
+                } else { // Do not consume the double-tap because full screen browsing mode is disabled.
+                    // Return false.
+                    false
+                }
+            }
 
-        // Clear cookies.
-        if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_cookies_key), true)) {
-            // Ass the cookie manager to delete all the cookies.
-            cookieManager.removeAllCookies(null)
+            override fun onFling(motionEvent1: MotionEvent, motionEvent2: MotionEvent, velocityX: Float, velocityY: Float): Boolean {
+                // Scroll the bottom app bar if enabled.
+                if (bottomAppBar && scrollAppBar && !objectAnimator.isRunning) {
+                    // Calculate the Y change.
+                    val motionY = motionEvent2.y - motionEvent1.y
 
-            // Ask the cookie manager to flush the cookie database.
-            cookieManager.flush()
+                    // Scroll the app bar if the change is greater than 50 pixels.
+                    if (motionY > 50) {
+                        // Animate the bottom app bar onto the screen.
+                        objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0f)
+                    } else if (motionY < -50) {
+                        // Animate the bottom app bar off the screen.
+                        objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", appBarLayout.height.toFloat())
+                    }
 
-            // Manually delete the cookies database, as the cookie manager sometimes will not flush its changes to disk before system exit is run.
-            try {
-                // Two commands must be used because `Runtime.exec()` does not like `*`.
-                val deleteCookiesProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/Cookies")
-                val deleteCookiesJournalProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/Cookies-journal")
+                    // Make it so.
+                    objectAnimator.start()
+                }
 
-                // Wait until the processes have finished.
-                deleteCookiesProcess.waitFor()
-                deleteCookiesJournalProcess.waitFor()
-            } catch (exception: Exception) {
-                // Do nothing if an error is thrown.
+                // Do not consume the event.
+                return false
             }
+        })
+
+        // Pass all touch events on the WebView through the double-tap gesture detector.
+        nestedScrollWebView.setOnTouchListener { view: View, motionEvent: MotionEvent? ->
+            // Call `performClick()` on the view, which is required for accessibility.
+            view.performClick()
+
+            // Check for double-taps.
+            doubleTapGestureDetector.onTouchEvent(motionEvent!!)
         }
 
-        // Clear DOM storage.
-        if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_dom_storage_key), true)) {
-            // Ask web storage to clear the DOM storage.
-            WebStorage.getInstance().deleteAllData()
+        // Register the WebView for a context menu.  This is used to see link targets and download images.
+        registerForContextMenu(nestedScrollWebView)
 
-            // Manually delete the DOM storage files and directories, as web storage sometimes will not flush its changes to disk before system exit is run.
-            try {
-                // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
-                val deleteLocalStorageProcess = runtime.exec(arrayOf("rm", "-rf", "$privateDataDirectoryString/app_webview/Local Storage/"))
+        // Allow the downloading of files.
+        nestedScrollWebView.setDownloadListener { downloadUrlString: String?, userAgent: String?, contentDisposition: String?, mimetype: String?, contentLength: Long ->
+            // Check the download preference.
+            if (downloadWithExternalApp) {  // Download with an external app.
+                downloadUrlWithExternalApp(downloadUrlString!!)
+            } else {  // Handle the download inside of Privacy Browser.
+                // Define a formatted file size string.
 
-                // Multiple commands must be used because `Runtime.exec()` does not like `*`.
-                val deleteIndexProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview/IndexedDB")
-                val deleteQuotaManagerProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/QuotaManager")
-                val deleteQuotaManagerJournalProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/QuotaManager-journal")
-                val deleteDatabaseProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview/databases")
+                // Process the content length if it contains data.
+                val formattedFileSizeString = if (contentLength > 0) {  // The content length is greater than 0.
+                    // Format the content length as a string.
+                    NumberFormat.getInstance().format(contentLength) + " " + getString(R.string.bytes)
+                } else {  // The content length is not greater than 0.
+                    // Set the formatted file size string to be `unknown size`.
+                    getString(R.string.unknown_size)
+                }
 
-                // Wait until the processes have finished.
-                deleteLocalStorageProcess.waitFor()
-                deleteIndexProcess.waitFor()
-                deleteQuotaManagerProcess.waitFor()
-                deleteQuotaManagerJournalProcess.waitFor()
-                deleteDatabaseProcess.waitFor()
-            } catch (exception: Exception) {
-                // Do nothing if an error is thrown.
+                // Get the file name from the content disposition.
+                val fileNameString = UrlHelper.getFileName(this, contentDisposition, mimetype, downloadUrlString!!)
+
+                // Instantiate the save dialog.
+                val saveDialogFragment = SaveDialog.saveUrl(downloadUrlString, fileNameString, formattedFileSizeString, userAgent!!, nestedScrollWebView.acceptCookies)
+
+                // Try to show the dialog.  The download listener continues to function even when the WebView is paused.  Attempting to display a dialog in that state leads to a crash.
+                try {
+                    // Show the save dialog.
+                    saveDialogFragment.show(supportFragmentManager, getString(R.string.save_dialog))
+                } catch (exception: Exception) {  // The dialog could not be shown.
+                    // Add the dialog to the pending dialog array list.  It will be displayed in `onStart()`.
+                    pendingDialogsArrayList.add(PendingDialogDataClass(saveDialogFragment, getString(R.string.save_dialog)))
+                }
             }
         }
 
-        // Clear form data if the API < 26.
-        if (Build.VERSION.SDK_INT < 26 && (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_form_data_key), true))) {
-            // Ask the WebView database to clear the form data.
-            @Suppress("DEPRECATION")
-            WebViewDatabase.getInstance(this).clearFormData()
+        // Update the find on page count.
+        nestedScrollWebView.setFindListener { activeMatchOrdinal, numberOfMatches, isDoneCounting ->
+            if (isDoneCounting && (numberOfMatches == 0)) {  // There are no matches.
+                // Set the find on page count text view to be `0/0`.
+                findOnPageCountTextView.setText(R.string.zero_of_zero)
+            } else if (isDoneCounting) {  // There are matches.
+                // The active match ordinal is zero-based.
+                val activeMatch = activeMatchOrdinal + 1
 
-            // Manually delete the form data database, as the WebView database sometimes will not flush its changes to disk before system exit is run.
-            try {
-                // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
-                val deleteWebDataProcess = runtime.exec(arrayOf("rm", "-f", "$privateDataDirectoryString/app_webview/Web Data"))
-                val deleteWebDataJournalProcess = runtime.exec(arrayOf("rm", "-f", "$privateDataDirectoryString/app_webview/Web Data-journal"))
+                // Build the match string.
+                val matchString = "$activeMatch/$numberOfMatches"
 
-                // Wait until the processes have finished.
-                deleteWebDataProcess.waitFor()
-                deleteWebDataJournalProcess.waitFor()
-            } catch (exception: Exception) {
-                // Do nothing if an error is thrown.
+                // Update the find on page count text view.
+                findOnPageCountTextView.text = matchString
             }
         }
 
-        // Clear the logcat.
-        if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_logcat_key), true)) {
-            try {
-                // Clear the logcat.  `-c` clears the logcat.  `-b all` clears all the buffers (instead of just crash, main, and system).
-                val process = Runtime.getRuntime().exec("logcat -b all -c")
+        // Process scroll changes.
+        nestedScrollWebView.setOnScrollChangeListener { _: View?, _: Int, _: Int, _: Int, _: Int ->
+            // Set the swipe to refresh status.
+            if (nestedScrollWebView.swipeToRefresh)  // Only enable swipe to refresh if the WebView is scrolled to the top.
+                swipeRefreshLayout.isEnabled = nestedScrollWebView.scrollY == 0
+            else  // Disable swipe to refresh.
+                swipeRefreshLayout.isEnabled = false
 
-                // Wait for the process to finish.
-                process.waitFor()
-            } catch (exception: IOException) {
-                // Do nothing.
-            } catch (exception: InterruptedException) {
-                // Do nothing.
+            // Reinforce the system UI visibility flags if in full screen browsing mode.
+            // This hides the status and navigation bars, which are displayed if other elements are shown, like dialog boxes, the options menu, or the keyboard.
+            if (inFullScreenBrowsingMode) {
+                /* Hide the system bars.
+                 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
+                 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
+                 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
+                 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
+                 */
+
+                // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
+                @Suppress("DEPRECATION")
+                rootFrameLayout.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
             }
         }
 
-        // Clear the cache.
-        if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_cache_key), true)) {
-            // Clear the cache from each WebView.
-            for (i in 0 until webViewPagerAdapter!!.count) {
-                // Get the WebView tab fragment.
-                val webViewTabFragment = webViewPagerAdapter!!.getPageFragment(i)
+        // Set the web chrome client.
+        nestedScrollWebView.webChromeClient = object : WebChromeClient() {
+            // Update the progress bar when a page is loading.
+            override fun onProgressChanged(view: WebView, progress: Int) {
+                // Update the progress bar.
+                progressBar.progress = progress
 
-                // Get the WebView fragment view.
-                val webViewFragmentView = webViewTabFragment.view
+                // Set the visibility of the progress bar.
+                if (progress < 100) {
+                    // Show the progress bar.
+                    progressBar.visibility = View.VISIBLE
+                } else {
+                    // Hide the progress bar.
+                    progressBar.visibility = View.GONE
 
-                // Only clear the cache if the WebView exists.
-                if (webViewFragmentView != null) {
-                    // Get the nested scroll WebView from the tab fragment.
-                    val nestedScrollWebView = webViewFragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
+                    //Stop the swipe to refresh indicator if it is running
+                    swipeRefreshLayout.isRefreshing = false
 
-                    // Clear the cache for this WebView.
-                    nestedScrollWebView.clearCache(true)
+                    // Make the current WebView visible.  If this is a new tab, the current WebView would have been created invisible in `webview_framelayout` to prevent a white background splash in night mode.
+                    nestedScrollWebView.visibility = View.VISIBLE
                 }
             }
 
-            // Manually delete the cache directories.
-            try {
-                // Delete the main cache directory.
-                val deleteCacheProcess = runtime.exec("rm -rf $privateDataDirectoryString/cache")
+            // Set the favorite icon when it changes.
+            override fun onReceivedIcon(view: WebView, icon: Bitmap) {
+                // Only update the favorite icon if the website has finished loading and the new favorite icon height is greater than the current favorite icon height.
+                // This prevents low resolution icons from replacing high resolution one.
+                // The check for the visibility of the progress bar can possibly be removed once https://redmine.stoutner.com/issues/747 is fixed.
+                if ((progressBar.visibility == View.GONE) && (icon.height > nestedScrollWebView.getFavoriteIconHeight())) {
+                    // Store the new favorite icon.
+                    nestedScrollWebView.setFavoriteIcon(icon)
 
-                // Delete the secondary `Service Worker` cache directory.
-                // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
-                val deleteServiceWorkerProcess = runtime.exec(arrayOf("rm", "-rf", "$privateDataDirectoryString/app_webview/Default/Service Worker/"))
+                    // Get the current page position.
+                    val currentPosition = webViewPagerAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
 
-                // Wait until the processes have finished.
-                deleteCacheProcess.waitFor()
-                deleteServiceWorkerProcess.waitFor()
-            } catch (exception: Exception) {
-                // Do nothing if an error is thrown.
-            }
-        }
+                    // Get the current tab.
+                    val tab = tabLayout.getTabAt(currentPosition)
 
-        // Wipe out each WebView.
-        for (i in 0 until webViewPagerAdapter!!.count) {
-            // Get the WebView tab fragment.
-            val webViewTabFragment = webViewPagerAdapter!!.getPageFragment(i)
+                    // Check to see if the tab has been populated.
+                    if (tab != null) {
+                        // Get the custom view from the tab.
+                        val tabView = tab.customView
 
-            // Get the WebView frame layout.
-            val webViewFrameLayout = webViewTabFragment.view as FrameLayout?
+                        // Check to see if the custom tab view has been populated.
+                        if (tabView != null) {
+                            // Get the favorite icon image view from the tab.
+                            val tabFavoriteIconImageView = tabView.findViewById<ImageView>(R.id.favorite_icon_imageview)
 
-            // Only wipe out the WebView if it exists.
-            if (webViewFrameLayout != null) {
-                // Get the nested scroll WebView from the tab fragment.
-                val nestedScrollWebView = webViewFrameLayout.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
+                            // Display the favorite icon in the tab.
+                            tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true))
+                        }
+                    }
+                }
+            }
 
-                // Clear SSL certificate preferences for this WebView.
-                nestedScrollWebView.clearSslPreferences()
+            // Save a copy of the title when it changes.
+            override fun onReceivedTitle(view: WebView, title: String) {
+                // Get the current page position.
+                val currentPosition = webViewPagerAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
 
-                // Clear the back/forward history for this WebView.
-                nestedScrollWebView.clearHistory()
+                // Get the current tab.
+                val tab = tabLayout.getTabAt(currentPosition)
 
-                // Remove all the views from the frame layout.
-                webViewFrameLayout.removeAllViews()
+                // Only populate the title text view if the tab has been fully created.
+                if (tab != null) {
+                    // Get the custom view from the tab.
+                    val tabView = tab.customView
+
+                    // Only populate the title text view if the tab view has been fully populated.
+                    if (tabView != null) {
+                        // Get the title text view from the tab.
+                        val tabTitleTextView = tabView.findViewById<TextView>(R.id.title_textview)
 
-                // Destroy the internal state of the WebView.
-                nestedScrollWebView.destroy()
+                        // Set the title according to the URL.
+                        if (title == "about:blank") {
+                            // Set the title to indicate a new tab.
+                            tabTitleTextView.setText(R.string.new_tab)
+                        } else {
+                            // Set the title as the tab text.
+                            tabTitleTextView.text = title
+                        }
+                    }
+                }
             }
-        }
 
-        // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
-        // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
-        if (clearEverything) {
-            try {
-                // Delete the folder.
-                val deleteAppWebviewProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview")
+            // Enter full screen video.
+            override fun onShowCustomView(video: View, callback: CustomViewCallback) {
+                // Set the full screen video flag.
+                displayingFullScreenVideo = true
 
-                // Wait until the process has finished.
-                deleteAppWebviewProcess.waitFor()
-            } catch (exception: Exception) {
-                // Do nothing if an error is thrown.
-            }
-        }
+                // Hide the keyboard.
+                inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.windowToken, 0)
 
-        // Close Privacy Browser.  `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
-        finishAndRemoveTask()
+                // Hide the coordinator layout.
+                coordinatorLayout.visibility = View.GONE
 
-        // Remove the terminated program from RAM.  The status code is `0`.
-        exitProcess(0)
-    }
+                /* Hide the system bars.
+                 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
+                 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
+                 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
+                 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
+                 */
 
-    // The view parameter cannot be removed because it is called from the layout onClick.
-    fun bookmarksBack(@Suppress("UNUSED_PARAMETER")view: View?) {
-        if (currentBookmarksFolder.isEmpty()) {  // The home folder is displayed.
-            // close the bookmarks drawer.
-            drawerLayout.closeDrawer(GravityCompat.END)
-        } else {  // A subfolder is displayed.
-            // Set the former parent folder as the current folder.
-            currentBookmarksFolder = bookmarksDatabaseHelper!!.getParentFolderName(currentBookmarksFolder)
+                // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
+                @Suppress("DEPRECATION")
+                rootFrameLayout.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
 
-            // Load the new folder.
-            loadBookmarksFolder()
-        }
-    }
+                // Disable the sliding drawers.
+                drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
 
-        // The view parameter cannot be removed because it is called from the layout onClick.
-    fun toggleBookmarksDrawerPinned(@Suppress("UNUSED_PARAMETER")view: View?) {
-        // Toggle the bookmarks drawer pinned tracker.
-        bookmarksDrawerPinned = !bookmarksDrawerPinned
+                // Add the video view to the full screen video frame layout.
+                fullScreenVideoFrameLayout.addView(video)
 
-        // Update the bookmarks drawer pinned image view.
-        updateBookmarksDrawerPinnedImageView()
-    }
+                // Show the full screen video frame layout.
+                fullScreenVideoFrameLayout.visibility = View.VISIBLE
 
-    private fun updateBookmarksDrawerPinnedImageView() {
-        // Set the current icon.
-        if (bookmarksDrawerPinned)
-            bookmarksDrawerPinnedImageView.setImageResource(R.drawable.pin_selected)
-        else
-            bookmarksDrawerPinnedImageView.setImageResource(R.drawable.pin)
-    }
+                // Disable the screen timeout while the video is playing.  YouTube does this automatically, but not all other videos do.
+                fullScreenVideoFrameLayout.keepScreenOn = true
+            }
 
-    private fun setCurrentWebView(pageNumber: Int) {
-        // Stop the swipe to refresh indicator if it is running
-        swipeRefreshLayout.isRefreshing = false
+            // Exit full screen video.
+            override fun onHideCustomView() {
+                // Exit the full screen video.
+                exitFullScreenVideo()
+            }
 
-        // Get the WebView tab fragment.
-        val webViewTabFragment = webViewPagerAdapter!!.getPageFragment(pageNumber)
+            // Upload files.
+            override fun onShowFileChooser(webView: WebView, filePathCallback: ValueCallback<Array<Uri>>, fileChooserParams: FileChooserParams): Boolean {
+                // Store the file path callback.
+                fileChooserCallback = filePathCallback
 
-        // Get the fragment view.
-        val webViewFragmentView = webViewTabFragment.view
+                // Create an intent to open a chooser based on the file chooser parameters.
+                val fileChooserIntent = fileChooserParams.createIntent()
 
-        // Set the current WebView if the fragment view is not null.
-        if (webViewFragmentView != null) {  // The fragment has been populated.
-            // Store the current WebView.
-            currentWebView = webViewFragmentView.findViewById(R.id.nestedscroll_webview)
+                // Check to see if the file chooser intent resolves to an installed package.
+                if (fileChooserIntent.resolveActivity(packageManager) != null) {  // The file chooser intent is fine.
+                    // Launch the file chooser intent.
+                    browseFileUploadActivityResultLauncher.launch(fileChooserIntent)
+                } else {  // The file chooser intent will cause a crash.
+                    // Create a generic intent to open a chooser.
+                    val genericFileChooserIntent = Intent(Intent.ACTION_GET_CONTENT)
 
-            // Update the status of swipe to refresh.
-            if (currentWebView!!.swipeToRefresh) {  // Swipe to refresh is enabled.
-                // Enable the swipe refresh layout if the WebView is scrolled all the way to the top.  It is updated every time the scroll changes.
-                swipeRefreshLayout.isEnabled = (currentWebView!!.scrollY == 0)
-            } else {  // Swipe to refresh is disabled.
-                // Disable the swipe refresh layout.
-                swipeRefreshLayout.isEnabled = false
-            }
+                    // Request an openable file.
+                    genericFileChooserIntent.addCategory(Intent.CATEGORY_OPENABLE)
 
-            // Set the cookie status.
-            cookieManager.setAcceptCookie(currentWebView!!.acceptCookies)
+                    // Set the file type to everything.
+                    genericFileChooserIntent.type = "*/*"
 
-            // Update the privacy icons.  `true` redraws the icons in the app bar.
-            updatePrivacyIcons(true)
+                    // Launch the generic file chooser intent.
+                    browseFileUploadActivityResultLauncher.launch(genericFileChooserIntent)
+                }
 
-            // Get a handle for the input method manager.
-            val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
+                // Handle the event.
+                return true
+            }
+        }
+        nestedScrollWebView.webViewClient = object : WebViewClient() {
+            // `shouldOverrideUrlLoading` makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
+            override fun shouldOverrideUrlLoading(view: WebView, webResourceRequest: WebResourceRequest): Boolean {
+                // Get the URL from the web resource request.
+                var requestUrlString = webResourceRequest.url.toString()
 
-            // Get the current URL.
-            val urlString = currentWebView!!.url
+                // Sanitize the url.
+                requestUrlString = sanitizeUrl(requestUrlString)
 
-            // Update the URL edit text if not loading a new intent.  Otherwise, this will be handled by `onPageStarted()` (if called) and `onPageFinished()`.
-            if (!loadingNewIntent) {  // A new intent is not being loaded.
-                if ((urlString == null) || (urlString == "about:blank")) {  // The WebView is blank.
-                    // Display the hint in the URL edit text.
-                    urlEditText.setText("")
+                // Handle the URL according to the type.
+                return if (requestUrlString.startsWith("http")) {  // Load the URL in Privacy Browser.
+                    // Load the URL.  By using `loadUrl()`, instead of `loadUrlFromBase()`, the Referer header will never be sent.
+                    loadUrl(nestedScrollWebView, requestUrlString)
 
-                    // Request focus for the URL text box.
-                    urlEditText.requestFocus()
+                    // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
+                    // Custom headers cannot be added if false is returned and the WebView handles the loading of the URL.
+                    true
+                } else if (requestUrlString.startsWith("mailto:")) {  // Load the email address in an external email program.
+                    // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
+                    val emailIntent = Intent(Intent.ACTION_SENDTO)
 
-                    // Display the keyboard.
-                    inputMethodManager.showSoftInput(urlEditText, 0)
-                } else {  // The WebView has a loaded URL.
-                    // Clear the focus from the URL text box.
-                    urlEditText.clearFocus()
+                    // Parse the url and set it as the data for the intent.
+                    emailIntent.data = Uri.parse(requestUrlString)
 
-                    // Hide the soft keyboard.
-                    inputMethodManager.hideSoftInputFromWindow(currentWebView!!.windowToken, 0)
+                    // Open the email program in a new task instead of as part of Privacy Browser.
+                    emailIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
 
-                    // Display the current URL in the URL text box.
-                    urlEditText.setText(urlString)
+                    try {
+                        // Make it so.
+                        startActivity(emailIntent)
+                    } catch (exception: ActivityNotFoundException) {
+                        // Display a snackbar.
+                        Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
+                    }
 
-                    // Highlight the URL syntax.
-                    UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
-                }
-            } else {  // A new intent is being loaded.
-                // Reset the loading new intent flag.
-                loadingNewIntent = false
-            }
+                    // Returning true indicates Privacy Browser is handling the URL by creating an intent.
+                    true
+                } else if (requestUrlString.startsWith("tel:")) {  // Load the phone number in the dialer.
+                    // Create a dial intent.
+                    val dialIntent = Intent(Intent.ACTION_DIAL)
 
-            // Set the background to indicate the domain settings status.
-            if (currentWebView!!.domainSettingsApplied) {
-                // Set a background on the URL relative layout to indicate that custom domain settings are being used.
-                urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.drawable.domain_settings_url_background)
-            } else {
-                // Remove any background on the URL relative layout.
-                urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.color.transparent)
-            }
-        } else if (pageNumber == savedTabPosition) {  // The app is being restored but the saved tab position fragment has not been populated yet.  Try again in 100 milliseconds.
-            // Create a handler to set the current WebView.
-            val setCurrentWebViewHandler = Handler(Looper.getMainLooper())
+                    // Add the phone number to the intent.
+                    dialIntent.data = Uri.parse(requestUrlString)
 
-            // Create a runnable to set the current WebView.
-            val setCurrentWebWebRunnable = Runnable {
-                // Set the current WebView.
-                setCurrentWebView(pageNumber)
-            }
+                    // Open the dialer in a new task instead of as part of Privacy Browser.
+                    dialIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
 
-            // Try setting the current WebView again after 100 milliseconds.
-            setCurrentWebViewHandler.postDelayed(setCurrentWebWebRunnable, 100)
-        }
-    }
+                    try {
+                        // Make it so.
+                        startActivity(dialIntent)
+                    } catch (exception: ActivityNotFoundException) {
+                        // Display a snackbar.
+                        Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
+                    }
 
-    @SuppressLint("ClickableViewAccessibility")
-    override fun initializeWebView(nestedScrollWebView: NestedScrollWebView, pageNumber: Int, progressBar: ProgressBar, urlString: String, restoringState: Boolean) {
-        // Get the WebView theme.
-        val webViewTheme = sharedPreferences.getString(getString(R.string.webview_theme_key), getString(R.string.webview_theme_default_value))
+                    // Returning true indicates Privacy Browser is handling the URL by creating an intent.
+                    true
+                } else {  // Load a system chooser to select an app that can handle the URL.
+                    // Create a generic intent to open an app.
+                    val genericIntent = Intent(Intent.ACTION_VIEW)
 
-        // Get the WebView theme entry values string array.
-        val webViewThemeEntryValuesStringArray = resources.getStringArray(R.array.webview_theme_entry_values)
+                    // Add the URL to the intent.
+                    genericIntent.data = Uri.parse(requestUrlString)
 
-        // Set the WebView theme if device is running API >= 29 and algorithmic darkening is supported.
-        if (Build.VERSION.SDK_INT >= 29 && WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {
-            // Set the WebView them.  A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
-            if (webViewTheme == webViewThemeEntryValuesStringArray[1]) {  // The light theme is selected.
-                // Turn off algorithmic darkening.
-                WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
+                    // List all apps that can handle the URL instead of just opening the first one.
+                    genericIntent.addCategory(Intent.CATEGORY_BROWSABLE)
 
-                // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
-                // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
-                nestedScrollWebView.visibility = View.VISIBLE
-            } else if (webViewTheme == webViewThemeEntryValuesStringArray[2]) {  // The dark theme is selected.
-                // Turn on algorithmic darkening.
-                WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
-            } else {  // The system default theme is selected.
-                // Get the current theme status.
-                val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
+                    // Open the app in a new task instead of as part of Privacy Browser.
+                    genericIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
 
-                // Set the algorithmic darkening according to the current system theme status.
-                if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {  // The system is in day mode.
-                    // Turn off algorithmic darkening.
-                    WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
+                    try {
+                        // Make it so.
+                        startActivity(genericIntent)
+                    } catch (exception: ActivityNotFoundException) {
+                        // Display a snackbar.
+                        Snackbar.make(nestedScrollWebView, getString(R.string.unrecognized_url, requestUrlString), Snackbar.LENGTH_SHORT).show()
+                    }
 
-                    // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
-                    // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
-                    nestedScrollWebView.visibility = View.VISIBLE
-                } else {  // The system is in night mode.
-                    // Turn on algorithmic darkening.
-                    WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
+                    // Returning true indicates Privacy Browser is handling the URL by creating an intent.
+                    true
                 }
             }
-        }
 
-        // Get a handle for the input method manager.
-        val inputMethodManager = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
+            // Check requests against the block lists.
+            override fun shouldInterceptRequest(view: WebView, webResourceRequest: WebResourceRequest): WebResourceResponse? {
+                // Get the URL.
+                val requestUrlString = webResourceRequest.url.toString()
 
-        // Instantiate the blocklist helper.  TODO.  Make a class instance.
-        val blocklistHelper = BlocklistHelper()
+                // Check to see if the resource request is for the main URL.
+                if (requestUrlString == nestedScrollWebView.currentUrl) {
+                    // `return null` loads the resource request, which should never be blocked if it is the main URL.
+                    return null
+                }
 
-        // Set the app bar scrolling.
-        nestedScrollWebView.isNestedScrollingEnabled = scrollAppBar
+                // 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.
+                while (ultraPrivacy == null) {
+                    try {
+                        // Check to see if the blocklists have been populated after 100 ms.
+                        Thread.sleep(100)
+                    } catch (exception: InterruptedException) {
+                        // Do nothing.
+                    }
+                }
 
-        // Allow pinch to zoom.
-        nestedScrollWebView.settings.builtInZoomControls = true
+                // Create an empty web resource response to be used if the resource request is blocked.
+                val emptyWebResourceResponse = WebResourceResponse("text/plain", "utf8", ByteArrayInputStream("".toByteArray()))
 
-        // Hide zoom controls.
-        nestedScrollWebView.settings.displayZoomControls = false
+                // Initialize the variables.
+                var whitelistResultStringArray: Array<String>? = null
+                var isThirdPartyRequest = false
 
-        // Don't allow mixed content (HTTP and HTTPS) on the same website.
-        nestedScrollWebView.settings.mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW
+                // Get the current URL.  `.getUrl()` throws an error because operations on the WebView cannot be made from this thread.
+                var currentBaseDomain = nestedScrollWebView.currentDomainName
 
-        // Set the WebView to load in overview mode (zoomed out to the maximum width).
-        nestedScrollWebView.settings.loadWithOverviewMode = true
+                // Store a copy of the current domain for use in later requests.
+                val currentDomain = currentBaseDomain
 
-        // Explicitly disable geolocation.
-        nestedScrollWebView.settings.setGeolocationEnabled(false)
+                // Get the request host name.
+                var requestBaseDomain = webResourceRequest.url.host
 
-        // Allow loading of file:// URLs.  This is necessary for opening MHT web archives, which are copied into a temporary cache location.
-        nestedScrollWebView.settings.allowFileAccess = true
+                // Only check for third-party requests if the current base domain is not empty and the request domain is not null.
+                if (currentBaseDomain.isNotEmpty() && (requestBaseDomain != null)) {
+                    // Determine the current base domain.
+                    while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) {  // There is at least one subdomain.
+                        // Remove the first subdomain.
+                        currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1)
+                    }
 
-        // Create a double-tap gesture detector to toggle full-screen mode.
-        val doubleTapGestureDetector = GestureDetector(this, object : GestureDetector.SimpleOnGestureListener() {
-            // Override `onDoubleTap()`.  All other events are handled using the default settings.
-            override fun onDoubleTap(motionEvent: MotionEvent): Boolean {
-                return if (fullScreenBrowsingModeEnabled) {  // Only process the double-tap if full screen browsing mode is enabled.
-                    // Toggle the full screen browsing mode tracker.
-                    inFullScreenBrowsingMode = !inFullScreenBrowsingMode
+                    // Determine the request base domain.
+                    while (requestBaseDomain!!.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) {  // There is at least one subdomain.
+                        // Remove the first subdomain.
+                        requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1)
+                    }
 
-                    // Toggle the full screen browsing mode.
-                    if (inFullScreenBrowsingMode) {  // Switch to full screen mode.
-                        // Hide the app bar if specified.
-                        if (hideAppBar) {  // App bar hiding is enabled.
-                            // Close the find on page bar if it is visible.
-                            closeFindOnPage(null)
+                    // Update the third party request tracker.
+                    isThirdPartyRequest = currentBaseDomain != requestBaseDomain
+                }
 
-                            // Hide the tab linear layout.
-                            tabsLinearLayout.visibility = View.GONE
+                // Get the current WebView page position.
+                val webViewPagePosition = webViewPagerAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
 
-                            // Hide the app bar.
-                            appBar.hide()
+                // Determine if the WebView is currently displayed.
+                val webViewDisplayed = webViewPagePosition == tabLayout.selectedTabPosition
 
-                            // Set layout and scrolling parameters according to the position of the app bar.
-                            if (bottomAppBar) {  // The app bar is at the bottom.
-                                // Reset the WebView padding to fill the available space.
-                                swipeRefreshLayout.setPadding(0, 0, 0, 0)
-                            } else {  // The app bar is at the top.
-                                // Check to see if the app bar is normally scrolled.
-                                if (scrollAppBar) {  // The app bar is scrolled when it is displayed.
-                                    // Get the swipe refresh layout parameters.
-                                    val swipeRefreshLayoutParams = swipeRefreshLayout.layoutParams as CoordinatorLayout.LayoutParams
+                // Block third-party requests if enabled.
+                if (isThirdPartyRequest && nestedScrollWebView.blockAllThirdPartyRequests) {
+                    // Add the result to the resource requests.
+                    nestedScrollWebView.addResourceRequest(arrayOf(REQUEST_THIRD_PARTY, requestUrlString))
 
-                                    // Remove the off-screen scrolling layout.
-                                    swipeRefreshLayoutParams.behavior = null
-                                } else {  // The app bar is not scrolled when it is displayed.
-                                    // Remove the padding from the top of the swipe refresh layout.
-                                    swipeRefreshLayout.setPadding(0, 0, 0, 0)
+                    // Increment the blocked requests counters.
+                    nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
+                    nestedScrollWebView.incrementRequestsCount(THIRD_PARTY_REQUESTS)
 
-                                    // The swipe refresh circle must be moved above the now removed status bar location.
-                                    swipeRefreshLayout.setProgressViewOffset(false, -200, defaultProgressViewEndOffset)
-                                }
-                            }
-                        } else {  // App bar hiding is not enabled.
-                            // Adjust the UI for the bottom app bar.
-                            if (bottomAppBar) {
-                                // Adjust the UI according to the scrolling of the app bar.
-                                if (scrollAppBar) {
-                                    // Reset the WebView padding to fill the available space.
-                                    swipeRefreshLayout.setPadding(0, 0, 0, 0)
-                                } else {
-                                    // Move the WebView above the app bar layout.
-                                    swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
-                                }
+                    // Update the titles of the blocklist menu items if the WebView is currently displayed.
+                    if (webViewDisplayed) {
+                        // Updating the UI must be run from the UI thread.
+                        runOnUiThread {
+                            // Update the menu item titles.
+                            navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
+
+                            // Update the options menu if it has been populated.
+                            if (optionsMenu != null) {
+                                optionsBlocklistsMenuItem.title = getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
+                                optionsBlockAllThirdPartyRequestsMenuItem.title =
+                                    nestedScrollWebView.getRequestsCount(THIRD_PARTY_REQUESTS).toString() + " - " + getString(R.string.block_all_third_party_requests)
                             }
                         }
+                    }
 
-                        /* Hide the system bars.
-                         * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
-                         * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
-                         * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
-                         * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
-                         */
+                    // The resource request was blocked.  Return an empty web resource response.
+                    return emptyWebResourceResponse
+                }
 
-                        // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
-                        @Suppress("DEPRECATION")
-                        rootFrameLayout.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
-                                View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
-                    } else {  // Switch to normal viewing mode.
-                        // Show the app bar if it was hidden.
-                        if (hideAppBar) {
-                            // Show the tab linear layout.
-                            tabsLinearLayout.visibility = View.VISIBLE
+                // Check UltraList if it is enabled.
+                if (nestedScrollWebView.ultraListEnabled) {
+                    // Check the URL against UltraList.
+                    val ultraListResults = checkBlocklistHelper.checkBlocklist(currentDomain, requestUrlString, isThirdPartyRequest, ultraList)
 
-                            // Show the app bar.
-                            appBar.show()
-                        }
+                    // Process the UltraList results.
+                    if (ultraListResults[0] == REQUEST_BLOCKED) {  // The resource request matched UltraList's blacklist.
+                        // Add the result to the resource requests.
+                        nestedScrollWebView.addResourceRequest(arrayOf(ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]))
 
-                        // Set layout and scrolling parameters according to the position of the app bar.
-                        if (bottomAppBar) {  // The app bar is at the bottom.
-                            // Adjust the UI.
-                            if (scrollAppBar) {
-                                // Reset the WebView padding to fill the available space.
-                                swipeRefreshLayout.setPadding(0, 0, 0, 0)
-                            } else {
-                                // Move the WebView above the app bar layout.
-                                swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
-                            }
-                        } else {  // The app bar is at the top.
-                            // Check to see if the app bar is normally scrolled.
-                            if (scrollAppBar) {  // The app bar is scrolled when it is displayed.
-                                // Get the swipe refresh layout parameters.
-                                val swipeRefreshLayoutParams = swipeRefreshLayout.layoutParams as CoordinatorLayout.LayoutParams
+                        // Increment the blocked requests counters.
+                        nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
+                        nestedScrollWebView.incrementRequestsCount(ULTRALIST)
 
-                                // Add the off-screen scrolling layout.
-                                swipeRefreshLayoutParams.behavior = AppBarLayout.ScrollingViewBehavior()
-                            } else {  // The app bar is not scrolled when it is displayed.
-                                // The swipe refresh layout must be manually moved below the app bar layout.
-                                swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0)
+                        // Update the titles of the blocklist menu items if the WebView is currently displayed.
+                        if (webViewDisplayed) {
+                            // Updating the UI must be run from the UI thread.
+                            runOnUiThread {
+                                // Update the menu item titles.
+                                navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
 
-                                // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
-                                swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight)
+                                // Update the options menu if it has been populated.
+                                if (optionsMenu != null) {
+                                    optionsBlocklistsMenuItem.title = getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
+                                    optionsUltraListMenuItem.title = nestedScrollWebView.getRequestsCount(ULTRALIST).toString() + " - " + getString(R.string.ultralist)
+                                }
                             }
                         }
 
-                        // Remove the `SYSTEM_UI` flags from the root frame layout.  The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
-                        @Suppress("DEPRECATION")
-                        rootFrameLayout.systemUiVisibility = 0
-                    }
-
-                    // Consume the double-tap.
-                    true
-                } else { // Do not consume the double-tap because full screen browsing mode is disabled.
-                    // Return false.
-                    false
-                }
-            }
-
-            override fun onFling(motionEvent1: MotionEvent, motionEvent2: MotionEvent, velocityX: Float, velocityY: Float): Boolean {
-                // Scroll the bottom app bar if enabled.
-                if (bottomAppBar && scrollAppBar && !objectAnimator.isRunning) {
-                    // Calculate the Y change.
-                    val motionY = motionEvent2.y - motionEvent1.y
+                        // The resource request was blocked.  Return an empty web resource response.
+                        return emptyWebResourceResponse
+                    } else if (ultraListResults[0] == REQUEST_ALLOWED) {  // The resource request matched UltraList's whitelist.
+                        // Add a whitelist entry to the resource requests array.
+                        nestedScrollWebView.addResourceRequest(arrayOf(ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]))
 
-                    // Scroll the app bar if the change is greater than 50 pixels.
-                    if (motionY > 50) {
-                        // Animate the bottom app bar onto the screen.
-                        objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0f)
-                    } else if (motionY < -50) {
-                        // Animate the bottom app bar off the screen.
-                        objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", appBarLayout.height.toFloat())
+                        // The resource request has been allowed by UltraPrivacy.  `return null` loads the requested resource.
+                        return null
                     }
-
-                    // Make it so.
-                    objectAnimator.start()
                 }
 
-                // Do not consume the event.
-                return false
-            }
-        })
+                // Check UltraPrivacy if it is enabled.
+                if (nestedScrollWebView.ultraPrivacyEnabled) {
+                    // Check the URL against UltraPrivacy.
+                    val ultraPrivacyResults = checkBlocklistHelper.checkBlocklist(currentDomain, requestUrlString, isThirdPartyRequest, ultraPrivacy!!)
+
+                    // Process the UltraPrivacy results.
+                    if (ultraPrivacyResults[0] == REQUEST_BLOCKED) {  // The resource request matched UltraPrivacy's blacklist.
+                        // Add the result to the resource requests.
+                        nestedScrollWebView.addResourceRequest(arrayOf(ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
+                            ultraPrivacyResults[5]))
 
-        // Pass all touch events on the WebView through the double-tap gesture detector.
-        nestedScrollWebView.setOnTouchListener { view: View, motionEvent: MotionEvent? ->
-            // Call `performClick()` on the view, which is required for accessibility.
-            view.performClick()
+                        // Increment the blocked requests counters.
+                        nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
+                        nestedScrollWebView.incrementRequestsCount(ULTRAPRIVACY)
 
-            // Check for double-taps.
-            doubleTapGestureDetector.onTouchEvent(motionEvent!!)
-        }
+                        // Update the titles of the blocklist menu items if the WebView is currently displayed.
+                        if (webViewDisplayed) {
+                            // Updating the UI must be run from the UI thread.
+                            runOnUiThread {
+                                // Update the menu item titles.
+                                navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
 
-        // Register the WebView for a context menu.  This is used to see link targets and download images.
-        registerForContextMenu(nestedScrollWebView)
+                                // Update the options menu if it has been populated.
+                                if (optionsMenu != null) {
+                                    optionsBlocklistsMenuItem.title = getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
+                                    optionsUltraPrivacyMenuItem.title = nestedScrollWebView.getRequestsCount(ULTRAPRIVACY).toString() + " - " + getString(R.string.ultraprivacy)
+                                }
+                            }
+                        }
 
-        // Allow the downloading of files.
-        nestedScrollWebView.setDownloadListener { downloadUrlString: String?, userAgent: String?, contentDisposition: String?, mimetype: String?, contentLength: Long ->
-            // Check the download preference.
-            if (downloadWithExternalApp) {  // Download with an external app.
-                downloadUrlWithExternalApp(downloadUrlString!!)
-            } else {  // Handle the download inside of Privacy Browser.
-                // Define a formatted file size string.
+                        // The resource request was blocked.  Return an empty web resource response.
+                        return emptyWebResourceResponse
+                    } else if (ultraPrivacyResults[0] == REQUEST_ALLOWED) {  // The resource request matched UltraPrivacy's whitelist.
+                        // Add a whitelist entry to the resource requests array.
+                        nestedScrollWebView.addResourceRequest(arrayOf(ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
+                            ultraPrivacyResults[5]))
 
-                // Process the content length if it contains data.
-                val formattedFileSizeString = if (contentLength > 0) {  // The content length is greater than 0.
-                    // Format the content length as a string.
-                    NumberFormat.getInstance().format(contentLength) + " " + getString(R.string.bytes)
-                } else {  // The content length is not greater than 0.
-                    // Set the formatted file size string to be `unknown size`.
-                    getString(R.string.unknown_size)
+                        // The resource request has been allowed by UltraPrivacy.  `return null` loads the requested resource.
+                        return null
+                    }
                 }
 
-                // Get the file name from the content disposition.
-                val fileNameString = UrlHelper.getFileName(this, contentDisposition, mimetype, downloadUrlString!!)
+                // Check EasyList if it is enabled.
+                if (nestedScrollWebView.easyListEnabled) {
+                    // Check the URL against EasyList.
+                    val easyListResults = checkBlocklistHelper.checkBlocklist(currentDomain, requestUrlString, isThirdPartyRequest, easyList)
 
-                // Instantiate the save dialog.
-                val saveDialogFragment = SaveDialog.saveUrl(downloadUrlString, fileNameString, formattedFileSizeString, userAgent!!, nestedScrollWebView.acceptCookies)
+                    // Process the EasyList results.
+                    if (easyListResults[0] == REQUEST_BLOCKED) {  // The resource request matched EasyList's blacklist.
+                        // Add the result to the resource requests.
+                        nestedScrollWebView.addResourceRequest(arrayOf(easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]))
 
-                // Try to show the dialog.  The download listener continues to function even when the WebView is paused.  Attempting to display a dialog in that state leads to a crash.
-                try {
-                    // Show the save dialog.
-                    saveDialogFragment.show(supportFragmentManager, getString(R.string.save_dialog))
-                } catch (exception: Exception) {  // The dialog could not be shown.
-                    // Add the dialog to the pending dialog array list.  It will be displayed in `onStart()`.
-                    pendingDialogsArrayList.add(PendingDialogDataClass(saveDialogFragment, getString(R.string.save_dialog)))
+                        // Increment the blocked requests counters.
+                        nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
+                        nestedScrollWebView.incrementRequestsCount(EASYLIST)
+
+                        // Update the titles of the blocklist menu items if the WebView is currently displayed.
+                        if (webViewDisplayed) {
+                            // Updating the UI must be run from the UI thread.
+                            runOnUiThread {
+                                // Update the menu item titles.
+                                navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
+
+                                // Update the options menu if it has been populated.
+                                if (optionsMenu != null) {
+                                    optionsBlocklistsMenuItem.title = getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
+                                    optionsEasyListMenuItem.title = nestedScrollWebView.getRequestsCount(EASYLIST).toString() + " - " + getString(R.string.easylist)
+                                }
+                            }
+                        }
+
+                        // The resource request was blocked.  Return an empty web resource response.
+                        return emptyWebResourceResponse
+                    } else if (easyListResults[0] == REQUEST_ALLOWED) {  // The resource request matched EasyList's whitelist.
+                        // Update the whitelist result string array tracker.
+                        whitelistResultStringArray = arrayOf(easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5])
+                    }
                 }
-            }
-        }
 
-        // Update the find on page count.
-        nestedScrollWebView.setFindListener { activeMatchOrdinal, numberOfMatches, isDoneCounting ->
-            if (isDoneCounting && (numberOfMatches == 0)) {  // There are no matches.
-                // Set the find on page count text view to be `0/0`.
-                findOnPageCountTextView.setText(R.string.zero_of_zero)
-            } else if (isDoneCounting) {  // There are matches.
-                // The active match ordinal is zero-based.
-                val activeMatch = activeMatchOrdinal + 1
+                // Check EasyPrivacy if it is enabled.
+                if (nestedScrollWebView.easyPrivacyEnabled) {
+                    // Check the URL against EasyPrivacy.
+                    val easyPrivacyResults = checkBlocklistHelper.checkBlocklist(currentDomain, requestUrlString, isThirdPartyRequest, easyPrivacy)
 
-                // Build the match string.
-                val matchString = "$activeMatch/$numberOfMatches"
+                    // Process the EasyPrivacy results.
+                    if (easyPrivacyResults[0] == REQUEST_BLOCKED) {  // The resource request matched EasyPrivacy's blacklist.
+                        // Add the result to the resource requests.
+                        nestedScrollWebView.addResourceRequest(arrayOf(easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5]))
 
-                // Update the find on page count text view.
-                findOnPageCountTextView.text = matchString
-            }
-        }
+                        // Increment the blocked requests counters.
+                        nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
+                        nestedScrollWebView.incrementRequestsCount(EASYPRIVACY)
 
-        // Process scroll changes.
-        nestedScrollWebView.setOnScrollChangeListener { _: View?, _: Int, _: Int, _: Int, _: Int ->
-            // Set the swipe to refresh status.
-            if (nestedScrollWebView.swipeToRefresh)  // Only enable swipe to refresh if the WebView is scrolled to the top.
-                swipeRefreshLayout.isEnabled = nestedScrollWebView.scrollY == 0
-            else  // Disable swipe to refresh.
-                swipeRefreshLayout.isEnabled = false
+                        // Update the titles of the blocklist menu items if the WebView is currently displayed.
+                        if (webViewDisplayed) {
+                            // Updating the UI must be run from the UI thread.
+                            runOnUiThread {
+                                // Update the menu item titles.
+                                navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
 
-            // Reinforce the system UI visibility flags if in full screen browsing mode.
-            // This hides the status and navigation bars, which are displayed if other elements are shown, like dialog boxes, the options menu, or the keyboard.
-            if (inFullScreenBrowsingMode) {
-                /* Hide the system bars.
-                 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
-                 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
-                 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
-                 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
-                 */
+                                // Update the options menu if it has been populated.
+                                if (optionsMenu != null) {
+                                    optionsBlocklistsMenuItem.title = getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
+                                    optionsEasyPrivacyMenuItem.title = nestedScrollWebView.getRequestsCount(EASYPRIVACY).toString() + " - " + getString(R.string.easyprivacy)
+                                }
+                            }
+                        }
 
-                // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
-                @Suppress("DEPRECATION")
-                rootFrameLayout.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
-            }
-        }
+                        // The resource request was blocked.  Return an empty web resource response.
+                        return emptyWebResourceResponse
+                    } else if (easyPrivacyResults[0] == REQUEST_ALLOWED) {  // The resource request matched EasyPrivacy's whitelist.
+                        // Update the whitelist result string array tracker.
+                        whitelistResultStringArray = arrayOf(easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5])
+                    }
+                }
 
-        // Set the web chrome client.
-        nestedScrollWebView.webChromeClient = object : WebChromeClient() {
-            // Update the progress bar when a page is loading.
-            override fun onProgressChanged(view: WebView, progress: Int) {
-                // Update the progress bar.
-                progressBar.progress = progress
+                // Check Fanboy’s Annoyance List if it is enabled.
+                if (nestedScrollWebView.fanboysAnnoyanceListEnabled) {
+                    // Check the URL against Fanboy's Annoyance List.
+                    val fanboysAnnoyanceListResults = checkBlocklistHelper.checkBlocklist(currentDomain, requestUrlString, isThirdPartyRequest, fanboysAnnoyanceList)
 
-                // Set the visibility of the progress bar.
-                if (progress < 100) {
-                    // Show the progress bar.
-                    progressBar.visibility = View.VISIBLE
-                } else {
-                    // Hide the progress bar.
-                    progressBar.visibility = View.GONE
+                    // Process the Fanboy's Annoyance List results.
+                    if (fanboysAnnoyanceListResults[0] == REQUEST_BLOCKED) {  // The resource request matched Fanboy's Annoyance List's blacklist.
+                        // Add the result to the resource requests.
+                        nestedScrollWebView.addResourceRequest(arrayOf(fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
+                            fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]))
 
-                    //Stop the swipe to refresh indicator if it is running
-                    swipeRefreshLayout.isRefreshing = false
+                        // Increment the blocked requests counters.
+                        nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
+                        nestedScrollWebView.incrementRequestsCount(FANBOYS_ANNOYANCE_LIST)
 
-                    // Make the current WebView visible.  If this is a new tab, the current WebView would have been created invisible in `webview_framelayout` to prevent a white background splash in night mode.
-                    nestedScrollWebView.visibility = View.VISIBLE
-                }
-            }
+                        // Update the titles of the blocklist menu items if the WebView is currently displayed.
+                        if (webViewDisplayed) {
+                            // Updating the UI must be run from the UI thread.
+                            runOnUiThread {
+                                // Update the menu item titles.
+                                navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
 
-            // Set the favorite icon when it changes.
-            override fun onReceivedIcon(view: WebView, icon: Bitmap) {
-                // Only update the favorite icon if the website has finished loading and the new favorite icon height is greater than the current favorite icon height.
-                // This prevents low resolution icons from replacing high resolution one.
-                // The check for the visibility of the progress bar can possibly be removed once https://redmine.stoutner.com/issues/747 is fixed.
-                if ((progressBar.visibility == View.GONE) && (icon.height > nestedScrollWebView.getFavoriteIconHeight())) {
-                    // Store the new favorite icon.
-                    nestedScrollWebView.setFavoriteIcon(icon)
+                                // Update the options menu if it has been populated.
+                                if (optionsMenu != null) {
+                                    optionsBlocklistsMenuItem.title = getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
+                                    optionsFanboysAnnoyanceListMenuItem.title = nestedScrollWebView.getRequestsCount(FANBOYS_ANNOYANCE_LIST).toString() + " - " + getString(R.string.fanboys_annoyance_list)
+                                }
+                            }
+                        }
 
-                    // Get the current page position.
-                    val currentPosition = webViewPagerAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
+                        // The resource request was blocked.  Return an empty web resource response.
+                        return emptyWebResourceResponse
+                    } else if (fanboysAnnoyanceListResults[0] == REQUEST_ALLOWED) {  // The resource request matched Fanboy's Annoyance List's whitelist.
+                        // Update the whitelist result string array tracker.
+                        whitelistResultStringArray = arrayOf(fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
+                            fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5])
+                    }
+                } else if (nestedScrollWebView.fanboysSocialBlockingListEnabled) {  // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
+                    // Check the URL against Fanboy's Annoyance List.
+                    val fanboysSocialListResults = checkBlocklistHelper.checkBlocklist(currentDomain, requestUrlString, isThirdPartyRequest, fanboysSocialList)
 
-                    // Get the current tab.
-                    val tab = tabLayout.getTabAt(currentPosition)
+                    // Process the Fanboy's Social Blocking List results.
+                    if (fanboysSocialListResults[0] == REQUEST_BLOCKED) {  // The resource request matched Fanboy's Social Blocking List's blacklist.
+                        // Add the result to the resource requests.
+                        nestedScrollWebView.addResourceRequest(arrayOf(fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
+                            fanboysSocialListResults[4], fanboysSocialListResults[5]))
 
-                    // Check to see if the tab has been populated.
-                    if (tab != null) {
-                        // Get the custom view from the tab.
-                        val tabView = tab.customView
+                        // Increment the blocked requests counters.
+                        nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
+                        nestedScrollWebView.incrementRequestsCount(FANBOYS_SOCIAL_BLOCKING_LIST)
 
-                        // Check to see if the custom tab view has been populated.
-                        if (tabView != null) {
-                            // Get the favorite icon image view from the tab.
-                            val tabFavoriteIconImageView = tabView.findViewById<ImageView>(R.id.favorite_icon_imageview)
+                        // Update the titles of the blocklist menu items if the WebView is currently displayed.
+                        if (webViewDisplayed) {
+                            // Updating the UI must be run from the UI thread.
+                            runOnUiThread {
+                                // Update the menu item titles.
+                                navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
 
-                            // Display the favorite icon in the tab.
-                            tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true))
+                                // Update the options menu if it has been populated.
+                                if (optionsMenu != null) {
+                                    optionsBlocklistsMenuItem.title = getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
+                                    optionsFanboysSocialBlockingListMenuItem.title =
+                                        nestedScrollWebView.getRequestsCount(FANBOYS_SOCIAL_BLOCKING_LIST).toString() + " - " + getString(R.string.fanboys_social_blocking_list)
+                                }
+                            }
                         }
+
+                        // The resource request was blocked.  Return an empty web resource response.
+                        return emptyWebResourceResponse
+                    } else if (fanboysSocialListResults[0] == REQUEST_ALLOWED) {  // The resource request matched Fanboy's Social Blocking List's whitelist.
+                        // Update the whitelist result string array tracker.
+                        whitelistResultStringArray = arrayOf(fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3], fanboysSocialListResults[4],
+                            fanboysSocialListResults[5])
                     }
                 }
-            }
-
-            // Save a copy of the title when it changes.
-            override fun onReceivedTitle(view: WebView, title: String) {
-                // Get the current page position.
-                val currentPosition = webViewPagerAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
 
-                // Get the current tab.
-                val tab = tabLayout.getTabAt(currentPosition)
+                // Add the request to the log because it hasn't been processed by any of the previous checks.
+                if (whitelistResultStringArray != null) {  // The request was processed by a whitelist.
+                    nestedScrollWebView.addResourceRequest(whitelistResultStringArray)
+                } else {  // The request didn't match any blocklist entry.  Log it as a default request.
+                    nestedScrollWebView.addResourceRequest(arrayOf(REQUEST_DEFAULT, requestUrlString))
+                }
+
+                // The resource request has not been blocked.  `return null` loads the requested resource.
+                return null
+            }
 
-                // Only populate the title text view if the tab has been fully created.
-                if (tab != null) {
-                    // Get the custom view from the tab.
-                    val tabView = tab.customView
+            // Handle HTTP authentication requests.
+            override fun onReceivedHttpAuthRequest(view: WebView, handler: HttpAuthHandler, host: String, realm: String) {
+                // Store the handler.
+                nestedScrollWebView.httpAuthHandler = handler
 
-                    // Only populate the title text view if the tab view has been fully populated.
-                    if (tabView != null) {
-                        // Get the title text view from the tab.
-                        val tabTitleTextView = tabView.findViewById<TextView>(R.id.title_textview)
+                // Instantiate an HTTP authentication dialog.
+                val httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm, nestedScrollWebView.webViewFragmentId)
 
-                        // Set the title according to the URL.
-                        if (title == "about:blank") {
-                            // Set the title to indicate a new tab.
-                            tabTitleTextView.setText(R.string.new_tab)
-                        } else {
-                            // Set the title as the tab text.
-                            tabTitleTextView.text = title
-                        }
-                    }
-                }
+                // Show the HTTP authentication dialog.
+                httpAuthenticationDialogFragment.show(supportFragmentManager, getString(R.string.http_authentication))
             }
 
-            // Enter full screen video.
-            override fun onShowCustomView(video: View, callback: CustomViewCallback) {
-                // Set the full screen video flag.
-                displayingFullScreenVideo = true
+            override fun onPageStarted(webView: WebView, url: String, favicon: Bitmap?) {
+                // Get the app bar layout height.  This can't be done in `applyAppSettings()` because the app bar is not yet populated there.
+                // This should only be populated if it is greater than 0 because otherwise it will be reset to 0 if the app bar is hidden in full screen browsing mode.
+                if (appBarLayout.height > 0)
+                    appBarHeight = appBarLayout.height
 
-                // Hide the keyboard.
-                inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.windowToken, 0)
+                // Set the padding and layout settings according to the position of the app bar.
+                if (bottomAppBar) {  // The app bar is on the bottom.
+                    // Adjust the UI.
+                    if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) {  // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
+                        // Reset the WebView padding to fill the available space.
+                        swipeRefreshLayout.setPadding(0, 0, 0, 0)
+                    } else {  // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
+                        // Move the WebView above the app bar layout.
+                        swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
+                    }
+                } else {  // The app bar is on the top.
+                    // Set the top padding of the swipe refresh layout according to the app bar scrolling preference.  This can't be done in `appAppSettings()` because the app bar is not yet populated there.
+                    if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) {  // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
+                        // No padding is needed because it will automatically be placed below the app bar layout due to the scrolling layout behavior.
+                        swipeRefreshLayout.setPadding(0, 0, 0, 0)
 
-                // Hide the coordinator layout.
-                coordinatorLayout.visibility = View.GONE
+                        // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
+                        swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10, defaultProgressViewEndOffset)
+                    } else {  // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
+                        // The swipe refresh layout must be manually moved below the app bar layout.
+                        swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0)
 
-                /* Hide the system bars.
-                 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
-                 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
-                 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
-                 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
-                 */
+                        // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
+                        swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight)
+                    }
+                }
 
-                // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
-                @Suppress("DEPRECATION")
-                rootFrameLayout.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
+                // Reset the list of resource requests.
+                nestedScrollWebView.clearResourceRequests()
 
-                // Disable the sliding drawers.
-                drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
+                // Reset the requests counters.
+                nestedScrollWebView.resetRequestsCounters()
 
-                // Add the video view to the full screen video frame layout.
-                fullScreenVideoFrameLayout.addView(video)
+                // Get the current page position.
+                val currentPagePosition = webViewPagerAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
 
-                // Show the full screen video frame layout.
-                fullScreenVideoFrameLayout.visibility = View.VISIBLE
+                // Update the URL text bar if the page is currently selected and the URL edit text is not currently being edited.
+                if ((tabLayout.selectedTabPosition == currentPagePosition) && !urlEditText.hasFocus()) {
+                    // Display the formatted URL text.
+                    urlEditText.setText(url)
 
-                // Disable the screen timeout while the video is playing.  YouTube does this automatically, but not all other videos do.
-                fullScreenVideoFrameLayout.keepScreenOn = true
-            }
+                    // Highlight the URL syntax.
+                    UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
 
-            // Exit full screen video.
-            override fun onHideCustomView() {
-                // Exit the full screen video.
-                exitFullScreenVideo()
-            }
+                    // Hide the keyboard.
+                    inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.windowToken, 0)
+                }
 
-            // Upload files.
-            override fun onShowFileChooser(webView: WebView, filePathCallback: ValueCallback<Array<Uri>>, fileChooserParams: FileChooserParams): Boolean {
-                // Store the file path callback.
-                fileChooserCallback = filePathCallback
+                // Reset the list of host IP addresses.
+                nestedScrollWebView.currentIpAddresses = ""
 
-                // Create an intent to open a chooser based on the file chooser parameters.
-                val fileChooserIntent = fileChooserParams.createIntent()
+                // Get a URI for the current URL.
+                val currentUri = Uri.parse(url)
 
-                // Check to see if the file chooser intent resolves to an installed package.
-                if (fileChooserIntent.resolveActivity(packageManager) != null) {  // The file chooser intent is fine.
-                    // Launch the file chooser intent.
-                    browseFileUploadActivityResultLauncher.launch(fileChooserIntent)
-                } else {  // The file chooser intent will cause a crash.
-                    // Create a generic intent to open a chooser.
-                    val genericFileChooserIntent = Intent(Intent.ACTION_GET_CONTENT)
+                // Get the current domain name.
+                val currentDomainName = currentUri.host
 
-                    // Request an openable file.
-                    genericFileChooserIntent.addCategory(Intent.CATEGORY_OPENABLE)
+                // Get the IP addresses for the current domain.
+                if ((currentDomainName != null) && currentDomainName.isNotEmpty())
+                    GetHostIpAddressesCoroutine.checkPinnedMismatch(currentDomainName, nestedScrollWebView, supportFragmentManager, getString(R.string.pinned_mismatch))
 
-                    // Set the file type to everything.
-                    genericFileChooserIntent.type = "*/*"
+                // Replace Refresh with Stop if the options menu has been created and the WebView is currently displayed.  (The first WebView typically begins loading before the menu items are instantiated.)
+                if ((optionsMenu != null) && (webView == currentWebView)) {
+                    // Set the title.
+                    optionsRefreshMenuItem.setTitle(R.string.stop)
 
-                    // Launch the generic file chooser intent.
-                    browseFileUploadActivityResultLauncher.launch(genericFileChooserIntent)
+                    // Set the icon if it is displayed in the AppBar.
+                    if (displayAdditionalAppBarIcons)
+                        optionsRefreshMenuItem.setIcon(R.drawable.close_blue)
                 }
-
-                // Handle the event.
-                return true
             }
-        }
-        nestedScrollWebView.webViewClient = object : WebViewClient() {
-            // `shouldOverrideUrlLoading` makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
-            override fun shouldOverrideUrlLoading(view: WebView, webResourceRequest: WebResourceRequest): Boolean {
-                // Get the URL from the web resource request.
-                var requestUrlString = webResourceRequest.url.toString()
 
-                // Sanitize the url.
-                requestUrlString = sanitizeUrl(requestUrlString)
+            override fun onPageFinished(webView: WebView, url: String) {
+                // Flush any cookies to persistent storage.  The cookie manager has become very lazy about flushing cookies in recent versions.
+                if (nestedScrollWebView.acceptCookies)
+                    cookieManager.flush()
 
-                // Handle the URL according to the type.
-                return if (requestUrlString.startsWith("http")) {  // Load the URL in Privacy Browser.
-                    // Load the URL.  By using `loadUrl()`, instead of `loadUrlFromBase()`, the Referer header will never be sent.
-                    loadUrl(nestedScrollWebView, requestUrlString)
+                // Update the Refresh menu item if the options menu has been created and the WebView is currently displayed.
+                if (optionsMenu != null && (webView == currentWebView)) {
+                    // Reset the Refresh title.
+                    optionsRefreshMenuItem.setTitle(R.string.refresh)
 
-                    // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
-                    // Custom headers cannot be added if false is returned and the WebView handles the loading of the URL.
-                    true
-                } else if (requestUrlString.startsWith("mailto:")) {  // Load the email address in an external email program.
-                    // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
-                    val emailIntent = Intent(Intent.ACTION_SENDTO)
+                    // Reset the icon if it is displayed in the app bar.
+                    if (displayAdditionalAppBarIcons)
+                        optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled)
+                }
 
-                    // Parse the url and set it as the data for the intent.
-                    emailIntent.data = Uri.parse(requestUrlString)
+                // 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`.
+                val privateDataDirectoryString = applicationInfo.dataDir
 
-                    // Open the email program in a new task instead of as part of Privacy Browser.
-                    emailIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
+                // Clear the cache, history, and logcat if Incognito Mode is enabled.
+                if (incognitoModeEnabled) {
+                    // Clear the cache.  `true` includes disk files.
+                    nestedScrollWebView.clearCache(true)
+
+                    // Clear the back/forward history.
+                    nestedScrollWebView.clearHistory()
 
+                    // Manually delete cache folders.
                     try {
-                        // Make it so.
-                        startActivity(emailIntent)
-                    } catch (exception: ActivityNotFoundException) {
-                        // Display a snackbar.
-                        Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
+                        // Delete the main cache directory.
+                        Runtime.getRuntime().exec("rm -rf $privateDataDirectoryString/cache")
+                    } catch (exception: IOException) {
+                        // Do nothing if an error is thrown.
                     }
 
-                    // Returning true indicates Privacy Browser is handling the URL by creating an intent.
-                    true
-                } else if (requestUrlString.startsWith("tel:")) {  // Load the phone number in the dialer.
-                    // Create a dial intent.
-                    val dialIntent = Intent(Intent.ACTION_DIAL)
+                    // Clear the logcat.
+                    try {
+                        // Clear the logcat.  `-c` clears the logcat.  `-b all` clears all the buffers (instead of just crash, main, and system).
+                        Runtime.getRuntime().exec("logcat -b all -c")
+                    } catch (exception: IOException) {
+                        // Do nothing.
+                    }
+                }
 
-                    // Add the phone number to the intent.
-                    dialIntent.data = Uri.parse(requestUrlString)
+                // Clear the `Service Worker` directory.
+                try {
+                    // A string array must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
+                    Runtime.getRuntime().exec(arrayOf("rm", "-rf", "$privateDataDirectoryString/app_webview/Default/Service Worker/"))
+                } catch (exception: IOException) {
+                    // Do nothing.
+                }
 
-                    // Open the dialer in a new task instead of as part of Privacy Browser.
-                    dialIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
+                // Get the current page position.
+                val currentPagePosition = webViewPagerAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
 
-                    try {
-                        // Make it so.
-                        startActivity(dialIntent)
-                    } catch (exception: ActivityNotFoundException) {
-                        // Display a snackbar.
-                        Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
-                    }
+                // 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.
+                val currentUrl = nestedScrollWebView.url
+
+                // Get the current tab.
+                val tab = tabLayout.getTabAt(currentPagePosition)
+
+                // Update the URL text bar if the page is currently selected and the user is not currently typing in the URL edit text.
+                // Crash records show that, in some crazy way, it is possible for the current URL to be blank at this point.
+                // Probably some sort of race condition when Privacy Browser is being resumed.
+                if ((tabLayout.selectedTabPosition == currentPagePosition) && !urlEditText.hasFocus() && (currentUrl != null)) {
+                    // Check to see if the URL is `about:blank`.
+                    if (currentUrl == "about:blank") {  // The WebView is blank.
+                        // Display the hint in the URL edit text.
+                        urlEditText.setText("")
+
+                        // Request focus for the URL text box.
+                        urlEditText.requestFocus()
 
-                    // Returning true indicates Privacy Browser is handling the URL by creating an intent.
-                    true
-                } else {  // Load a system chooser to select an app that can handle the URL.
-                    // Create a generic intent to open an app.
-                    val genericIntent = Intent(Intent.ACTION_VIEW)
+                        // Display the keyboard.
+                        inputMethodManager.showSoftInput(urlEditText, 0)
 
-                    // Add the URL to the intent.
-                    genericIntent.data = Uri.parse(requestUrlString)
+                        // Apply the domain settings.  This clears any settings from the previous domain.
+                        applyDomainSettings(nestedScrollWebView, "", resetTab = true, reloadWebsite = false, loadUrl = false)
 
-                    // List all apps that can handle the URL instead of just opening the first one.
-                    genericIntent.addCategory(Intent.CATEGORY_BROWSABLE)
+                        // Only populate the title text view if the tab has been fully created.
+                        if (tab != null) {
+                            // Get the custom view from the tab.
+                            val tabView = tab.customView!!
 
-                    // Open the app in a new task instead of as part of Privacy Browser.
-                    genericIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
+                            // Get the title text view from the tab.
+                            val tabTitleTextView = tabView.findViewById<TextView>(R.id.title_textview)
 
-                    try {
-                        // Make it so.
-                        startActivity(genericIntent)
-                    } catch (exception: ActivityNotFoundException) {
-                        // Display a snackbar.
-                        Snackbar.make(nestedScrollWebView, getString(R.string.unrecognized_url, requestUrlString), Snackbar.LENGTH_SHORT).show()
-                    }
+                            // Set the title as the tab text.
+                            tabTitleTextView.setText(R.string.new_tab)
+                        }
+                    } else {  // The WebView has loaded a webpage.
+                        // Update the URL edit text if it is not currently being edited.
+                        if (!urlEditText.hasFocus()) {
+                            // 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.
+                            val sanitizedUrl = sanitizeUrl(currentUrl)
 
-                    // Returning true indicates Privacy Browser is handling the URL by creating an intent.
-                    true
-                }
-            }
+                            // Display the final URL.  Getting the URL from the WebView instead of using the one provided by `onPageFinished()` makes websites like YouTube function correctly.
+                            urlEditText.setText(sanitizedUrl)
 
-            // Check requests against the block lists.
-            override fun shouldInterceptRequest(view: WebView, webResourceRequest: WebResourceRequest): WebResourceResponse? {
-                // Get the URL.
-                val requestUrlString = webResourceRequest.url.toString()
+                            // Highlight the URL syntax.
+                            UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
+                        }
 
-                // Check to see if the resource request is for the main URL.
-                if (requestUrlString == nestedScrollWebView.currentUrl) {
-                    // `return null` loads the resource request, which should never be blocked if it is the main URL.
-                    return null
-                }
+                        // Only populate the title text view if the tab has been fully created.
+                        if (tab != null) {
+                            // Get the custom view from the tab.
+                            val tabView = tab.customView!!
 
-                // 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.
-                while (ultraPrivacy == null) {
-                    try {
-                        // Check to see if the blocklists have been populated after 100 ms.
-                        Thread.sleep(100)
-                    } catch (exception: InterruptedException) {
-                        // Do nothing.
+                            // Get the title text view from the tab.
+                            val tabTitleTextView = tabView.findViewById<TextView>(R.id.title_textview)
+
+                            // Set the title as the tab text.  Sometimes `onReceivedTitle()` is not called, especially when navigating history.
+                            tabTitleTextView.text = nestedScrollWebView.title
+                        }
                     }
                 }
+            }
 
-                // Create an empty web resource response to be used if the resource request is blocked.
-                val emptyWebResourceResponse = WebResourceResponse("text/plain", "utf8", ByteArrayInputStream("".toByteArray()))
+            // Handle SSL Certificate errors.  Suppress the lint warning that ignoring the error might be dangerous.
+            @SuppressLint("WebViewClientOnReceivedSslError")
+            override fun onReceivedSslError(view: WebView, handler: SslErrorHandler, error: SslError) {
+                // Get the current website SSL certificate.
+                val currentWebsiteSslCertificate = error.certificate
 
-                // Initialize the variables.
-                var whitelistResultStringArray: Array<String>? = null
-                var isThirdPartyRequest = false
+                // Extract the individual pieces of information from the current website SSL certificate.
+                val currentWebsiteIssuedToCName = currentWebsiteSslCertificate.issuedTo.cName
+                val currentWebsiteIssuedToOName = currentWebsiteSslCertificate.issuedTo.oName
+                val currentWebsiteIssuedToUName = currentWebsiteSslCertificate.issuedTo.uName
+                val currentWebsiteIssuedByCName = currentWebsiteSslCertificate.issuedBy.cName
+                val currentWebsiteIssuedByOName = currentWebsiteSslCertificate.issuedBy.oName
+                val currentWebsiteIssuedByUName = currentWebsiteSslCertificate.issuedBy.uName
+                val currentWebsiteSslStartDate = currentWebsiteSslCertificate.validNotBeforeDate
+                val currentWebsiteSslEndDate = currentWebsiteSslCertificate.validNotAfterDate
 
-                // Get the current URL.  `.getUrl()` throws an error because operations on the WebView cannot be made from this thread.
-                var currentBaseDomain = nestedScrollWebView.currentDomainName
+                // Get the pinned SSL certificate.
+                val (pinnedSslCertificateStringArray, pinnedSslCertificateDateArray) = nestedScrollWebView.getPinnedSslCertificate()
 
-                // Store a copy of the current domain for use in later requests.
-                val currentDomain = currentBaseDomain
+                // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
+                if (nestedScrollWebView.hasPinnedSslCertificate() &&
+                    (currentWebsiteIssuedToCName == pinnedSslCertificateStringArray[0]) &&
+                    (currentWebsiteIssuedToOName == pinnedSslCertificateStringArray[1]) &&
+                    (currentWebsiteIssuedToUName == pinnedSslCertificateStringArray[2]) &&
+                    (currentWebsiteIssuedByCName == pinnedSslCertificateStringArray[3]) &&
+                    (currentWebsiteIssuedByOName == pinnedSslCertificateStringArray[4]) &&
+                    (currentWebsiteIssuedByUName == pinnedSslCertificateStringArray[5]) &&
+                    (currentWebsiteSslStartDate == pinnedSslCertificateDateArray[0]) &&
+                    (currentWebsiteSslEndDate == pinnedSslCertificateDateArray[1])) {
 
-                // Get the request host name.
-                var requestBaseDomain = webResourceRequest.url.host
+                    // An SSL certificate is pinned and matches the current domain certificate.  Proceed to the website without displaying an error.
+                    handler.proceed()
+                } else {  // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
+                    // Store the SSL error handler.
+                    nestedScrollWebView.sslErrorHandler = handler
 
-                // Only check for third-party requests if the current base domain is not empty and the request domain is not null.
-                if (currentBaseDomain.isNotEmpty() && (requestBaseDomain != null)) {
-                    // Determine the current base domain.
-                    while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) {  // There is at least one subdomain.
-                        // Remove the first subdomain.
-                        currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1)
-                    }
+                    // Instantiate an SSL certificate error alert dialog.
+                    val sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error, nestedScrollWebView.webViewFragmentId)
 
-                    // Determine the request base domain.
-                    while (requestBaseDomain!!.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) {  // There is at least one subdomain.
-                        // Remove the first subdomain.
-                        requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1)
+                    // Try to show the dialog.  The SSL error handler continues to function even when the WebView is paused.  Attempting to display a dialog in that state leads to a crash.
+                    try {
+                        // Show the SSL certificate error dialog.
+                        sslCertificateErrorDialogFragment.show(supportFragmentManager, getString(R.string.ssl_certificate_error))
+                    } catch (exception: Exception) {
+                        // Add the dialog to the pending dialog array list.  It will be displayed in `onStart()`.
+                        pendingDialogsArrayList.add(PendingDialogDataClass(sslCertificateErrorDialogFragment, getString(R.string.ssl_certificate_error)))
                     }
-
-                    // Update the third party request tracker.
-                    isThirdPartyRequest = currentBaseDomain != requestBaseDomain
                 }
+            }
+        }
 
-                // Get the current WebView page position.
-                val webViewPagePosition = webViewPagerAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
-
-                // Determine if the WebView is currently displayed.
-                val webViewDisplayed = webViewPagePosition == tabLayout.selectedTabPosition
-
-                // Block third-party requests if enabled.
-                if (isThirdPartyRequest && nestedScrollWebView.blockAllThirdPartyRequests) {
-                    // Add the result to the resource requests.
-                    nestedScrollWebView.addResourceRequest(arrayOf(BlocklistHelper.REQUEST_THIRD_PARTY, requestUrlString))
+        // Check to see if the state is being restored.
+        if (restoringState) {  // The state is being restored.
+            // Resume the nested scroll WebView JavaScript timers.
+            nestedScrollWebView.resumeTimers()
+        } else if (pageNumber == 0) {  // The first page is being loaded.
+            // Set this nested scroll WebView as the current WebView.
+            currentWebView = nestedScrollWebView
 
-                    // Increment the blocked requests counters.
-                    nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
-                    nestedScrollWebView.incrementRequestsCount(THIRD_PARTY_REQUESTS)
+            // Get the intent that started the app.
+            val launchingIntent = intent
 
-                    // Update the titles of the blocklist menu items if the WebView is currently displayed.
-                    if (webViewDisplayed) {
-                        // Updating the UI must be run from the UI thread.
-                        runOnUiThread {
-                            // Update the menu item titles.
-                            navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
+            // Reset the intent.  This prevents a duplicate tab from being created on restart.
+            intent = Intent()
 
-                            // Update the options menu if it has been populated.
-                            if (optionsMenu != null) {
-                                optionsBlocklistsMenuItem.title = getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
-                                optionsBlockAllThirdPartyRequestsMenuItem.title =
-                                    nestedScrollWebView.getRequestsCount(THIRD_PARTY_REQUESTS).toString() + " - " + getString(R.string.block_all_third_party_requests)
-                            }
-                        }
-                    }
+            // Get the information from the intent.
+            val launchingIntentAction = launchingIntent.action
+            val launchingIntentUriData = launchingIntent.data
+            val launchingIntentStringExtra = launchingIntent.getStringExtra(Intent.EXTRA_TEXT)
 
-                    // The resource request was blocked.  Return an empty web resource response.
-                    return emptyWebResourceResponse
+            // Parse the launching intent URL.  Suppress the suggestions of using elvis expressions as they make the logic very difficult to follow.
+            @Suppress("IfThenToElvis") val urlToLoadString = if ((launchingIntentAction != null) && (launchingIntentAction == Intent.ACTION_WEB_SEARCH)) {  // The intent contains a search string.
+                // Sanitize the search input and convert it to a search.
+                val encodedSearchString = try {
+                    URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8")
+                } catch (exception: UnsupportedEncodingException) {
+                    ""
                 }
 
-                // Check UltraList if it is enabled.
-                if (nestedScrollWebView.ultraListEnabled) {
-                    // Check the URL against UltraList.
-                    val ultraListResults = blocklistHelper.checkBlocklist(currentDomain, requestUrlString, isThirdPartyRequest, ultraList)
-
-                    // Process the UltraList results.
-                    if (ultraListResults[0] == BlocklistHelper.REQUEST_BLOCKED) {  // The resource request matched UltraList's blacklist.
-                        // Add the result to the resource requests.
-                        nestedScrollWebView.addResourceRequest(arrayOf(ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]))
+                // Add the search URL to the encodedSearchString
+                searchURL + encodedSearchString
+            } else if (launchingIntentUriData != null) {  // The launching intent contains a URL formatted as a URI.
+                // Get the URL from the URI.
+                launchingIntentUriData.toString()
+            } else if (launchingIntentStringExtra != null) {  // The launching intent contains text that might be a URL.
+                // Get the URL from the string extra.
+                launchingIntentStringExtra
+            } else if (urlString != "") {  // The activity has been restarted.
+                // Load the saved URL.
+                urlString
+            } else {  // The is no saved URL and there is no URL in the intent.
+                // Load the homepage.
+                sharedPreferences.getString("homepage", getString(R.string.homepage_default_value))
+            }
 
-                        // Increment the blocked requests counters.
-                        nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
-                        nestedScrollWebView.incrementRequestsCount(ULTRALIST)
+            // Load the website if not waiting for the proxy.
+            if (waitingForProxy) {  // Store the URL to be loaded in the Nested Scroll WebView.
+                nestedScrollWebView.waitingForProxyUrlString = urlToLoadString!!
+            } else {  // Load the URL.
+                loadUrl(nestedScrollWebView, urlToLoadString!!)
+            }
 
-                        // Update the titles of the blocklist menu items if the WebView is currently displayed.
-                        if (webViewDisplayed) {
-                            // Updating the UI must be run from the UI thread.
-                            runOnUiThread {
-                                // Update the menu item titles.
-                                navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
+            // Reset the intent.  This prevents a duplicate tab from being created on a subsequent restart if loading an link from a new intent on restart.
+            // For example, this prevents a duplicate tab if a link is loaded from the Guide after changing the theme in the guide and then changing the theme again in the main activity.
+            intent = Intent()
+        } else {  // This is not the first tab.
+            // Load the URL.
+            loadUrl(nestedScrollWebView, urlString)
 
-                                // Update the options menu if it has been populated.
-                                if (optionsMenu != null) {
-                                    optionsBlocklistsMenuItem.title = getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
-                                    optionsUltraListMenuItem.title = nestedScrollWebView.getRequestsCount(ULTRALIST).toString() + " - " + getString(R.string.ultralist)
-                                }
-                            }
-                        }
+            // Set the focus and display the keyboard if the URL is blank.
+            if (urlString == "") {
+                // Request focus for the URL text box.
+                urlEditText.requestFocus()
 
-                        // The resource request was blocked.  Return an empty web resource response.
-                        return emptyWebResourceResponse
-                    } else if (ultraListResults[0] == BlocklistHelper.REQUEST_ALLOWED) {  // The resource request matched UltraList's whitelist.
-                        // Add a whitelist entry to the resource requests array.
-                        nestedScrollWebView.addResourceRequest(arrayOf(ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]))
+                // Create a display keyboard handler.
+                val displayKeyboardHandler = Handler(Looper.getMainLooper())
 
-                        // The resource request has been allowed by UltraPrivacy.  `return null` loads the requested resource.
-                        return null
-                    }
+                // Create a display keyboard runnable.
+                val displayKeyboardRunnable = Runnable {
+                    // Display the keyboard.
+                    inputMethodManager.showSoftInput(urlEditText, 0)
                 }
 
-                // Check UltraPrivacy if it is enabled.
-                if (nestedScrollWebView.ultraPrivacyEnabled) {
-                    // Check the URL against UltraPrivacy.
-                    val ultraPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, requestUrlString, isThirdPartyRequest, ultraPrivacy!!)
+                // Display the keyboard after 100 milliseconds, which leaves enough time for the tab to transition.
+                displayKeyboardHandler.postDelayed(displayKeyboardRunnable, 100)
+            }
+        }
+    }
 
-                    // Process the UltraPrivacy results.
-                    if (ultraPrivacyResults[0] == BlocklistHelper.REQUEST_BLOCKED) {  // The resource request matched UltraPrivacy's blacklist.
-                        // Add the result to the resource requests.
-                        nestedScrollWebView.addResourceRequest(arrayOf(ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
-                            ultraPrivacyResults[5]))
+    private fun loadBookmarksFolder() {
+        // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
+        bookmarksCursor = bookmarksDatabaseHelper!!.getBookmarksByDisplayOrder(currentBookmarksFolder)
 
-                        // Increment the blocked requests counters.
-                        nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
-                        nestedScrollWebView.incrementRequestsCount(ULTRAPRIVACY)
+        // Populate the bookmarks cursor adapter.
+        bookmarksCursorAdapter = object : CursorAdapter(this, bookmarksCursor, false) {
+            override fun newView(context: Context, cursor: Cursor, parent: ViewGroup): View {
+                // Inflate the individual item layout.
+                return layoutInflater.inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false)
+            }
 
-                        // Update the titles of the blocklist menu items if the WebView is currently displayed.
-                        if (webViewDisplayed) {
-                            // Updating the UI must be run from the UI thread.
-                            runOnUiThread {
-                                // Update the menu item titles.
-                                navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
+            override fun bindView(view: View, context: Context, cursor: Cursor) {
+                // Get handles for the views.
+                val bookmarkFavoriteIcon = view.findViewById<ImageView>(R.id.bookmark_favorite_icon)
+                val bookmarkNameTextView = view.findViewById<TextView>(R.id.bookmark_name)
 
-                                // Update the options menu if it has been populated.
-                                if (optionsMenu != null) {
-                                    optionsBlocklistsMenuItem.title = getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
-                                    optionsUltraPrivacyMenuItem.title = nestedScrollWebView.getRequestsCount(ULTRAPRIVACY).toString() + " - " + getString(R.string.ultraprivacy)
-                                }
-                            }
-                        }
+                // Get the favorite icon byte array from the cursor.
+                val favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.FAVORITE_ICON))
 
-                        // The resource request was blocked.  Return an empty web resource response.
-                        return emptyWebResourceResponse
-                    } else if (ultraPrivacyResults[0] == BlocklistHelper.REQUEST_ALLOWED) {  // The resource request matched UltraPrivacy's whitelist.
-                        // Add a whitelist entry to the resource requests array.
-                        nestedScrollWebView.addResourceRequest(arrayOf(ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
-                            ultraPrivacyResults[5]))
+                // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
+                val favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.size)
 
-                        // The resource request has been allowed by UltraPrivacy.  `return null` loads the requested resource.
-                        return null
-                    }
-                }
+                // Display the bitmap in the bookmark favorite icon.
+                bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap)
 
-                // Check EasyList if it is enabled.
-                if (nestedScrollWebView.easyListEnabled) {
-                    // Check the URL against EasyList.
-                    val easyListResults = blocklistHelper.checkBlocklist(currentDomain, requestUrlString, isThirdPartyRequest, easyList)
+                // Display the bookmark name from the cursor in the bookmark name text view.
+                bookmarkNameTextView.text = cursor.getString(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME))
 
-                    // Process the EasyList results.
-                    if (easyListResults[0] == BlocklistHelper.REQUEST_BLOCKED) {  // The resource request matched EasyList's blacklist.
-                        // Add the result to the resource requests.
-                        nestedScrollWebView.addResourceRequest(arrayOf(easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]))
+                // Make the font bold for folders.
+                if (cursor.getInt(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.IS_FOLDER)) == 1)
+                    bookmarkNameTextView.typeface = Typeface.DEFAULT_BOLD
+                else  // Reset the font to default for normal bookmarks.
+                    bookmarkNameTextView.typeface = Typeface.DEFAULT
+            }
+        }
 
-                        // Increment the blocked requests counters.
-                        nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
-                        nestedScrollWebView.incrementRequestsCount(EASYLIST)
+        // Populate the list view with the adapter.
+        bookmarksListView.adapter = bookmarksCursorAdapter
 
-                        // Update the titles of the blocklist menu items if the WebView is currently displayed.
-                        if (webViewDisplayed) {
-                            // Updating the UI must be run from the UI thread.
-                            runOnUiThread {
-                                // Update the menu item titles.
-                                navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
+        // Set the bookmarks drawer title.
+        if (currentBookmarksFolder.isEmpty())
+            bookmarksTitleTextView.setText(R.string.bookmarks)
+        else
+            bookmarksTitleTextView.text = currentBookmarksFolder
+    }
 
-                                // Update the options menu if it has been populated.
-                                if (optionsMenu != null) {
-                                    optionsBlocklistsMenuItem.title = getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
-                                    optionsEasyListMenuItem.title = nestedScrollWebView.getRequestsCount(EASYLIST).toString() + " - " + getString(R.string.easylist)
-                                }
-                            }
-                        }
+    private fun loadUrl(nestedScrollWebView: NestedScrollWebView, url: String) {
+        // Sanitize the URL.
+        val urlString = sanitizeUrl(url)
 
-                        // The resource request was blocked.  Return an empty web resource response.
-                        return emptyWebResourceResponse
-                    } else if (easyListResults[0] == BlocklistHelper.REQUEST_ALLOWED) {  // The resource request matched EasyList's whitelist.
-                        // Update the whitelist result string array tracker.
-                        whitelistResultStringArray = arrayOf(easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5])
-                    }
-                }
+        // Apply the domain settings and load the URL.
+        applyDomainSettings(nestedScrollWebView, urlString, resetTab = true, reloadWebsite = false, loadUrl = true)
+    }
 
-                // Check EasyPrivacy if it is enabled.
-                if (nestedScrollWebView.easyPrivacyEnabled) {
-                    // Check the URL against EasyPrivacy.
-                    val easyPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, requestUrlString, isThirdPartyRequest, easyPrivacy)
+    private fun loadUrlFromTextBox() {
+        // Get the text from URL text box and convert it to a string.  trim() removes white spaces from the beginning and end of the string.
+        var unformattedUrlString = urlEditText.text.toString().trim { it <= ' ' }
 
-                    // Process the EasyPrivacy results.
-                    if (easyPrivacyResults[0] == BlocklistHelper.REQUEST_BLOCKED) {  // The resource request matched EasyPrivacy's blacklist.
-                        // Add the result to the resource requests.
-                        nestedScrollWebView.addResourceRequest(arrayOf(easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5]))
+        // Create the formatted URL string.
+        var urlString = ""
 
-                        // Increment the blocked requests counters.
-                        nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
-                        nestedScrollWebView.incrementRequestsCount(EASYPRIVACY)
+        // Check to see if the unformatted URL string is a valid URL.  Otherwise, convert it into a search.
+        if (unformattedUrlString.startsWith("content://")) {  // This is a content URL.
+            // Load the entire content URL.
+            urlString = unformattedUrlString
+        } else if (Patterns.WEB_URL.matcher(unformattedUrlString).matches() || unformattedUrlString.startsWith("http://") || unformattedUrlString.startsWith("https://") ||
+            unformattedUrlString.startsWith("file://")) {  // This is a standard URL.
 
-                        // Update the titles of the blocklist menu items if the WebView is currently displayed.
-                        if (webViewDisplayed) {
-                            // Updating the UI must be run from the UI thread.
-                            runOnUiThread {
-                                // Update the menu item titles.
-                                navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
+            // Add `https://` at the beginning if there is no protocol.  Otherwise the app will segfault.
+            if (!unformattedUrlString.startsWith("http") && !unformattedUrlString.startsWith("file://"))
+                unformattedUrlString = "https://$unformattedUrlString"
 
-                                // Update the options menu if it has been populated.
-                                if (optionsMenu != null) {
-                                    optionsBlocklistsMenuItem.title = getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
-                                    optionsEasyPrivacyMenuItem.title = nestedScrollWebView.getRequestsCount(EASYPRIVACY).toString() + " - " + getString(R.string.easyprivacy)
-                                }
-                            }
-                        }
+            // Initialize the unformatted URL.
+            var unformattedUrl: URL? = null
 
-                        // The resource request was blocked.  Return an empty web resource response.
-                        return emptyWebResourceResponse
-                    } else if (easyPrivacyResults[0] == BlocklistHelper.REQUEST_ALLOWED) {  // The resource request matched EasyPrivacy's whitelist.
-                        // Update the whitelist result string array tracker.
-                        whitelistResultStringArray = arrayOf(easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5])
-                    }
-                }
+            // Convert the unformatted URL string to a URL.
+            try {
+                unformattedUrl = URL(unformattedUrlString)
+            } catch (exception: MalformedURLException) {
+                exception.printStackTrace()
+            }
 
-                // Check Fanboy’s Annoyance List if it is enabled.
-                if (nestedScrollWebView.fanboysAnnoyanceListEnabled) {
-                    // Check the URL against Fanboy's Annoyance List.
-                    val fanboysAnnoyanceListResults = blocklistHelper.checkBlocklist(currentDomain, requestUrlString, isThirdPartyRequest, fanboysAnnoyanceList)
+            // Get the components of the URL.
+            val scheme = unformattedUrl?.protocol
+            val authority = unformattedUrl?.authority
+            val path = unformattedUrl?.path
+            val query = unformattedUrl?.query
+            val fragment = unformattedUrl?.ref
 
-                    // Process the Fanboy's Annoyance List results.
-                    if (fanboysAnnoyanceListResults[0] == BlocklistHelper.REQUEST_BLOCKED) {  // The resource request matched Fanboy's Annoyance List's blacklist.
-                        // Add the result to the resource requests.
-                        nestedScrollWebView.addResourceRequest(arrayOf(fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
-                                fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]))
+            // Create a URI.
+            val uri = Uri.Builder()
 
-                        // Increment the blocked requests counters.
-                        nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
-                        nestedScrollWebView.incrementRequestsCount(FANBOYS_ANNOYANCE_LIST)
+            // Build the URI from the components of the URL.
+            uri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment)
 
-                        // Update the titles of the blocklist menu items if the WebView is currently displayed.
-                        if (webViewDisplayed) {
-                            // Updating the UI must be run from the UI thread.
-                            runOnUiThread {
-                                // Update the menu item titles.
-                                navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
+            // Decode the URI as a UTF-8 string in.
+            try {
+                urlString = URLDecoder.decode(uri.build().toString(), "UTF-8")
+            } catch (exception: UnsupportedEncodingException) {
+                // Do nothing.  The formatted URL string will remain blank.
+            }
+        } else if (unformattedUrlString.isNotEmpty()) {  // This is not a URL, but rather a search string.
+            // Sanitize the search input.
+            val encodedSearchString = try {
+                URLEncoder.encode(unformattedUrlString, "UTF-8")
+            } catch (exception: UnsupportedEncodingException) {
+                ""
+            }
 
-                                // Update the options menu if it has been populated.
-                                if (optionsMenu != null) {
-                                    optionsBlocklistsMenuItem.title = getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
-                                    optionsFanboysAnnoyanceListMenuItem.title = nestedScrollWebView.getRequestsCount(FANBOYS_ANNOYANCE_LIST).toString() + " - " + getString(R.string.fanboys_annoyance_list)
-                                }
-                            }
-                        }
+            // Add the base search URL.
+            urlString = searchURL + encodedSearchString
+        }
 
-                        // The resource request was blocked.  Return an empty web resource response.
-                        return emptyWebResourceResponse
-                    } else if (fanboysAnnoyanceListResults[0] == BlocklistHelper.REQUEST_ALLOWED) {  // The resource request matched Fanboy's Annoyance List's whitelist.
-                        // Update the whitelist result string array tracker.
-                        whitelistResultStringArray = arrayOf(fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
-                            fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5])
-                    }
-                } else if (nestedScrollWebView.fanboysSocialBlockingListEnabled) {  // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
-                    // Check the URL against Fanboy's Annoyance List.
-                    val fanboysSocialListResults = blocklistHelper.checkBlocklist(currentDomain, requestUrlString, isThirdPartyRequest, fanboysSocialList)
+        // 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.
+        urlEditText.clearFocus()
 
-                    // Process the Fanboy's Social Blocking List results.
-                    if (fanboysSocialListResults[0] == BlocklistHelper.REQUEST_BLOCKED) {  // The resource request matched Fanboy's Social Blocking List's blacklist.
-                        // Add the result to the resource requests.
-                        nestedScrollWebView.addResourceRequest(arrayOf(fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
-                            fanboysSocialListResults[4], fanboysSocialListResults[5]))
+        // Make it so.
+        loadUrl(currentWebView!!, urlString)
+    }
 
-                        // Increment the blocked requests counters.
-                        nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
-                        nestedScrollWebView.incrementRequestsCount(FANBOYS_SOCIAL_BLOCKING_LIST)
+    override fun navigateHistory(url: String, steps: Int) {
+        // Apply the domain settings.
+        applyDomainSettings(currentWebView!!, url, resetTab = false, reloadWebsite = false, loadUrl = false)
 
-                        // Update the titles of the blocklist menu items if the WebView is currently displayed.
-                        if (webViewDisplayed) {
-                            // Updating the UI must be run from the UI thread.
-                            runOnUiThread {
-                                // Update the menu item titles.
-                                navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
+        // Load the history entry.
+        currentWebView!!.goBackOrForward(steps)
+    }
 
-                                // Update the options menu if it has been populated.
-                                if (optionsMenu != null) {
-                                    optionsBlocklistsMenuItem.title = getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
-                                    optionsFanboysSocialBlockingListMenuItem.title =
-                                        nestedScrollWebView.getRequestsCount(FANBOYS_SOCIAL_BLOCKING_LIST).toString() + " - " + getString(R.string.fanboys_social_blocking_list)
-                                }
-                            }
-                        }
+    override fun openFile(dialogFragment: DialogFragment) {
+        // Get the dialog.
+        val dialog = dialogFragment.dialog!!
 
-                        // The resource request was blocked.  Return an empty web resource response.
-                        return emptyWebResourceResponse
-                    } else if (fanboysSocialListResults[0] == BlocklistHelper.REQUEST_ALLOWED) {  // The resource request matched Fanboy's Social Blocking List's whitelist.
-                        // Update the whitelist result string array tracker.
-                        whitelistResultStringArray = arrayOf(fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3], fanboysSocialListResults[4],
-                            fanboysSocialListResults[5])
-                    }
-                }
+        // Get handles for the views.
+        val fileNameEditText = dialog.findViewById<EditText>(R.id.file_name_edittext)
+        val mhtCheckBox = dialog.findViewById<CheckBox>(R.id.mht_checkbox)
 
-                // Add the request to the log because it hasn't been processed by any of the previous checks.
-                if (whitelistResultStringArray != null) {  // The request was processed by a whitelist.
-                    nestedScrollWebView.addResourceRequest(whitelistResultStringArray)
-                } else {  // The request didn't match any blocklist entry.  Log it as a default request.
-                    nestedScrollWebView.addResourceRequest(arrayOf(BlocklistHelper.REQUEST_DEFAULT, requestUrlString))
-                }
+        // Get the file path string.
+        val openFilePath = fileNameEditText.text.toString()
 
-                // The resource request has not been blocked.  `return null` loads the requested resource.
-                return null
-            }
+        // Apply the domain settings.  This resets the favorite icon and removes any domain settings.
+        applyDomainSettings(currentWebView!!, openFilePath, resetTab = true, reloadWebsite = false, loadUrl = false)
 
-            // Handle HTTP authentication requests.
-            override fun onReceivedHttpAuthRequest(view: WebView, handler: HttpAuthHandler, host: String, realm: String) {
-                // Store the handler.
-                nestedScrollWebView.httpAuthHandler = handler
+        // Open the file according to the type.
+        if (mhtCheckBox.isChecked) {  // Force opening of an MHT file.
+            try {
+                // Get the MHT file input stream.
+                val mhtFileInputStream = contentResolver.openInputStream(Uri.parse(openFilePath))
 
-                // Instantiate an HTTP authentication dialog.
-                val httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm, nestedScrollWebView.webViewFragmentId)
+                // Create a temporary MHT file.
+                val temporaryMhtFile = File.createTempFile(TEMPORARY_MHT_FILE, ".mht", cacheDir)
 
-                // Show the HTTP authentication dialog.
-                httpAuthenticationDialogFragment.show(supportFragmentManager, getString(R.string.http_authentication))
-            }
+                // Get a file output stream for the temporary MHT file.
+                val temporaryMhtFileOutputStream = FileOutputStream(temporaryMhtFile)
 
-            override fun onPageStarted(webView: WebView, url: String, favicon: Bitmap?) {
-                // Get the app bar layout height.  This can't be done in `applyAppSettings()` because the app bar is not yet populated there.
-                // This should only be populated if it is greater than 0 because otherwise it will be reset to 0 if the app bar is hidden in full screen browsing mode.
-                if (appBarLayout.height > 0)
-                    appBarHeight = appBarLayout.height
+                // Create a transfer byte array.
+                val transferByteArray = ByteArray(1024)
 
-                // Set the padding and layout settings according to the position of the app bar.
-                if (bottomAppBar) {  // The app bar is on the bottom.
-                    // Adjust the UI.
-                    if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) {  // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
-                        // Reset the WebView padding to fill the available space.
-                        swipeRefreshLayout.setPadding(0, 0, 0, 0)
-                    } else {  // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
-                        // Move the WebView above the app bar layout.
-                        swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
-                    }
-                } else {  // The app bar is on the top.
-                    // Set the top padding of the swipe refresh layout according to the app bar scrolling preference.  This can't be done in `appAppSettings()` because the app bar is not yet populated there.
-                    if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) {  // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
-                        // No padding is needed because it will automatically be placed below the app bar layout due to the scrolling layout behavior.
-                        swipeRefreshLayout.setPadding(0, 0, 0, 0)
+                // Create an integer to track the number of bytes read.
+                var bytesRead: Int
 
-                        // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
-                        swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10, defaultProgressViewEndOffset)
-                    } else {  // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
-                        // The swipe refresh layout must be manually moved below the app bar layout.
-                        swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0)
+                // Copy the temporary MHT file input stream to the MHT output stream.
+                while (mhtFileInputStream!!.read(transferByteArray).also { bytesRead = it } > 0)
+                    temporaryMhtFileOutputStream.write(transferByteArray, 0, bytesRead)
 
-                        // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
-                        swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight)
-                    }
-                }
+                // Flush the temporary MHT file output stream.
+                temporaryMhtFileOutputStream.flush()
 
-                // Reset the list of resource requests.
-                nestedScrollWebView.clearResourceRequests()
+                // Close the streams.
+                temporaryMhtFileOutputStream.close()
+                mhtFileInputStream.close()
 
-                // Reset the requests counters.
-                nestedScrollWebView.resetRequestsCounters()
+                // Load the temporary MHT file.
+                currentWebView!!.loadUrl(temporaryMhtFile.toString())
+            } catch (exception: Exception) {
+                // Display a snackbar.
+                Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
+            }
+        } else {  // Let the WebView handle opening of the file.
+            // Open the file.
+            currentWebView!!.loadUrl(openFilePath)
+        }
+    }
 
-                // Get the current page position.
-                val currentPagePosition = webViewPagerAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
+    private fun openWithApp(url: String) {
+        // Create an open with app intent with `ACTION_VIEW`.
+        val openWithAppIntent = Intent(Intent.ACTION_VIEW)
 
-                // Update the URL text bar if the page is currently selected and the URL edit text is not currently being edited.
-                if ((tabLayout.selectedTabPosition == currentPagePosition) && !urlEditText.hasFocus()) {
-                    // Display the formatted URL text.
-                    urlEditText.setText(url)
+        // Set the URI but not the MIME type.  This should open all available apps.
+        openWithAppIntent.data = Uri.parse(url)
 
-                    // Highlight the URL syntax.
-                    UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
+        // Flag the intent to open in a new task.
+        openWithAppIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
 
-                    // Hide the keyboard.
-                    inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.windowToken, 0)
-                }
+        // Try the intent.
+        try {
+            // Show the chooser.
+            startActivity(openWithAppIntent)
+        } catch (exception: ActivityNotFoundException) {  // There are no apps available to open the URL.
+            // Show a snackbar with the error.
+            Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
+        }
+    }
 
-                // Reset the list of host IP addresses.
-                nestedScrollWebView.currentIpAddresses = ""
+    private fun openWithBrowser(url: String) {
 
-                // Get a URI for the current URL.
-                val currentUri = Uri.parse(url)
+        // Create an open with browser intent with `ACTION_VIEW`.
+        val openWithBrowserIntent = Intent(Intent.ACTION_VIEW)
 
-                // Get the current domain name.
-                val currentDomainName = currentUri.host
+        // Set the URI and the MIME type.  `"text/html"` should load browser options.
+        openWithBrowserIntent.setDataAndType(Uri.parse(url), "text/html")
 
-                // Get the IP addresses for the current domain.
-                if ((currentDomainName != null) && currentDomainName.isNotEmpty())
-                    GetHostIpAddressesCoroutine.checkPinnedMismatch(currentDomainName, nestedScrollWebView, supportFragmentManager, getString(R.string.pinned_mismatch))
+        // Flag the intent to open in a new task.
+        openWithBrowserIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
 
-                // Replace Refresh with Stop if the options menu has been created and the WebView is currently displayed.  (The first WebView typically begins loading before the menu items are instantiated.)
-                if ((optionsMenu != null) && (webView == currentWebView)) {
-                    // Set the title.
-                    optionsRefreshMenuItem.setTitle(R.string.stop)
+        // Try the intent.
+        try {
+            // Show the chooser.
+            startActivity(openWithBrowserIntent)
+        } catch (exception: ActivityNotFoundException) {  // There are no browsers available to open the URL.
+            // Show a snackbar with the error.
+            Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
+        }
+    }
 
-                    // Set the icon if it is displayed in the AppBar.
-                    if (displayAdditionalAppBarIcons)
-                        optionsRefreshMenuItem.setIcon(R.drawable.close_blue)
-                }
-            }
+    override fun pinnedErrorGoBack() {
+        // Get the current web back forward list.
+        val webBackForwardList = currentWebView!!.copyBackForwardList()
 
-            override fun onPageFinished(webView: WebView, url: String) {
-                // Flush any cookies to persistent storage.  The cookie manager has become very lazy about flushing cookies in recent versions.
-                if (nestedScrollWebView.acceptCookies)
-                    cookieManager.flush()
+        // Get the previous entry URL.
+        val previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex - 1).url
 
-                // Update the Refresh menu item if the options menu has been created and the WebView is currently displayed.
-                if (optionsMenu != null && (webView == currentWebView)) {
-                    // Reset the Refresh title.
-                    optionsRefreshMenuItem.setTitle(R.string.refresh)
+        // Apply the domain settings.
+        applyDomainSettings(currentWebView!!, previousUrl, resetTab = false, reloadWebsite = false, loadUrl = false)
 
-                    // Reset the icon if it is displayed in the app bar.
-                    if (displayAdditionalAppBarIcons)
-                        optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled)
-                }
+        // Go back.
+        currentWebView!!.goBack()
+    }
 
-                // 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`.
-                val privateDataDirectoryString = applicationInfo.dataDir
+    private fun sanitizeUrl(urlString: String): String {
+        // Initialize a sanitized URL string.
+        var sanitizedUrlString = urlString
 
-                // Clear the cache, history, and logcat if Incognito Mode is enabled.
-                if (incognitoModeEnabled) {
-                    // Clear the cache.  `true` includes disk files.
-                    nestedScrollWebView.clearCache(true)
+        // Sanitize tracking queries.
+        if (sanitizeTrackingQueries)
+            sanitizedUrlString = SanitizeUrlHelper.sanitizeTrackingQueries(sanitizedUrlString)
 
-                    // Clear the back/forward history.
-                    nestedScrollWebView.clearHistory()
+        // Sanitize AMP redirects.
+        if (sanitizeAmpRedirects)
+            sanitizedUrlString = SanitizeUrlHelper.sanitizeAmpRedirects(sanitizedUrlString)
 
-                    // Manually delete cache folders.
-                    try {
-                        // Delete the main cache directory.
-                        Runtime.getRuntime().exec("rm -rf $privateDataDirectoryString/cache")
-                    } catch (exception: IOException) {
-                        // Do nothing if an error is thrown.
-                    }
+        // Return the sanitized URL string.
+        return sanitizedUrlString
+    }
 
-                    // Clear the logcat.
-                    try {
-                        // Clear the logcat.  `-c` clears the logcat.  `-b all` clears all the buffers (instead of just crash, main, and system).
-                        Runtime.getRuntime().exec("logcat -b all -c")
-                    } catch (exception: IOException) {
-                        // Do nothing.
-                    }
-                }
+    override fun saveUrl(originalUrlString: String, fileNameString: String, dialogFragment: DialogFragment) {
+        // Store the URL.  This will be used in the save URL activity result launcher.
+        saveUrlString = if (originalUrlString.startsWith("data:")) {
+            // Save the original URL.
+            originalUrlString
+        } else {
+            // Get the dialog.
+            val dialog = dialogFragment.dialog!!
 
-                // Clear the `Service Worker` directory.
-                try {
-                    // A string array must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
-                    Runtime.getRuntime().exec(arrayOf("rm", "-rf", "$privateDataDirectoryString/app_webview/Default/Service Worker/"))
-                } catch (exception: IOException) {
-                    // Do nothing.
-                }
+            // Get a handle for the dialog URL edit text.
+            val dialogUrlEditText = dialog.findViewById<EditText>(R.id.url_edittext)
 
-                // Get the current page position.
-                val currentPagePosition = webViewPagerAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
+            // Get the URL from the edit text, which may have been modified.
+            dialogUrlEditText.text.toString()
+        }
 
-                // 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.
-                val currentUrl = nestedScrollWebView.url
+        // Open the file picker.
+        saveUrlActivityResultLauncher.launch(fileNameString)
+    }
 
-                // Get the current tab.
-                val tab = tabLayout.getTabAt(currentPagePosition)
+    private fun setCurrentWebView(pageNumber: Int) {
+        // Stop the swipe to refresh indicator if it is running
+        swipeRefreshLayout.isRefreshing = false
 
-                // Update the URL text bar if the page is currently selected and the user is not currently typing in the URL edit text.
-                // Crash records show that, in some crazy way, it is possible for the current URL to be blank at this point.
-                // Probably some sort of race condition when Privacy Browser is being resumed.
-                if ((tabLayout.selectedTabPosition == currentPagePosition) && !urlEditText.hasFocus() && (currentUrl != null)) {
-                    // Check to see if the URL is `about:blank`.
-                    if (currentUrl == "about:blank") {  // The WebView is blank.
-                        // Display the hint in the URL edit text.
-                        urlEditText.setText("")
+        // Get the WebView tab fragment.
+        val webViewTabFragment = webViewPagerAdapter!!.getPageFragment(pageNumber)
 
-                        // Request focus for the URL text box.
-                        urlEditText.requestFocus()
+        // Get the fragment view.
+        val webViewFragmentView = webViewTabFragment.view
+
+        // Set the current WebView if the fragment view is not null.
+        if (webViewFragmentView != null) {  // The fragment has been populated.
+            // Store the current WebView.
+            currentWebView = webViewFragmentView.findViewById(R.id.nestedscroll_webview)
 
-                        // Display the keyboard.
-                        inputMethodManager.showSoftInput(urlEditText, 0)
+            // Update the status of swipe to refresh.
+            if (currentWebView!!.swipeToRefresh) {  // Swipe to refresh is enabled.
+                // Enable the swipe refresh layout if the WebView is scrolled all the way to the top.  It is updated every time the scroll changes.
+                swipeRefreshLayout.isEnabled = (currentWebView!!.scrollY == 0)
+            } else {  // Swipe to refresh is disabled.
+                // Disable the swipe refresh layout.
+                swipeRefreshLayout.isEnabled = false
+            }
 
-                        // Apply the domain settings.  This clears any settings from the previous domain.
-                        applyDomainSettings(nestedScrollWebView, "", resetTab = true, reloadWebsite = false, loadUrl = false)
+            // Set the cookie status.
+            cookieManager.setAcceptCookie(currentWebView!!.acceptCookies)
 
-                        // Only populate the title text view if the tab has been fully created.
-                        if (tab != null) {
-                            // Get the custom view from the tab.
-                            val tabView = tab.customView!!
+            // Update the privacy icons.  `true` redraws the icons in the app bar.
+            updatePrivacyIcons(true)
 
-                            // Get the title text view from the tab.
-                            val tabTitleTextView = tabView.findViewById<TextView>(R.id.title_textview)
+            // Get a handle for the input method manager.
+            val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
 
-                            // Set the title as the tab text.
-                            tabTitleTextView.setText(R.string.new_tab)
-                        }
-                    } else {  // The WebView has loaded a webpage.
-                        // Update the URL edit text if it is not currently being edited.
-                        if (!urlEditText.hasFocus()) {
-                            // 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.
-                            val sanitizedUrl = sanitizeUrl(currentUrl)
+            // Get the current URL.
+            val urlString = currentWebView!!.url
 
-                            // Display the final URL.  Getting the URL from the WebView instead of using the one provided by `onPageFinished()` makes websites like YouTube function correctly.
-                            urlEditText.setText(sanitizedUrl)
+            // Update the URL edit text if not loading a new intent.  Otherwise, this will be handled by `onPageStarted()` (if called) and `onPageFinished()`.
+            if (!loadingNewIntent) {  // A new intent is not being loaded.
+                if ((urlString == null) || (urlString == "about:blank")) {  // The WebView is blank.
+                    // Display the hint in the URL edit text.
+                    urlEditText.setText("")
 
-                            // Highlight the URL syntax.
-                            UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
-                        }
+                    // Request focus for the URL text box.
+                    urlEditText.requestFocus()
 
-                        // Only populate the title text view if the tab has been fully created.
-                        if (tab != null) {
-                            // Get the custom view from the tab.
-                            val tabView = tab.customView!!
+                    // Display the keyboard.
+                    inputMethodManager.showSoftInput(urlEditText, 0)
+                } else {  // The WebView has a loaded URL.
+                    // Clear the focus from the URL text box.
+                    urlEditText.clearFocus()
 
-                            // Get the title text view from the tab.
-                            val tabTitleTextView = tabView.findViewById<TextView>(R.id.title_textview)
+                    // Hide the soft keyboard.
+                    inputMethodManager.hideSoftInputFromWindow(currentWebView!!.windowToken, 0)
 
-                            // Set the title as the tab text.  Sometimes `onReceivedTitle()` is not called, especially when navigating history.
-                            tabTitleTextView.text = nestedScrollWebView.title
-                        }
-                    }
+                    // Display the current URL in the URL text box.
+                    urlEditText.setText(urlString)
+
+                    // Highlight the URL syntax.
+                    UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
                 }
+            } else {  // A new intent is being loaded.
+                // Reset the loading new intent flag.
+                loadingNewIntent = false
             }
 
-            // Handle SSL Certificate errors.  Suppress the lint warning that ignoring the error might be dangerous.
-            @SuppressLint("WebViewClientOnReceivedSslError")
-            override fun onReceivedSslError(view: WebView, handler: SslErrorHandler, error: SslError) {
-                // Get the current website SSL certificate.
-                val currentWebsiteSslCertificate = error.certificate
+            // Set the background to indicate the domain settings status.
+            if (currentWebView!!.domainSettingsApplied) {
+                // Set a background on the URL relative layout to indicate that custom domain settings are being used.
+                urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.drawable.domain_settings_url_background)
+            } else {
+                // Remove any background on the URL relative layout.
+                urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.color.transparent)
+            }
+        } else if (pageNumber == savedTabPosition) {  // The app is being restored but the saved tab position fragment has not been populated yet.  Try again in 100 milliseconds.
+            // Create a handler to set the current WebView.
+            val setCurrentWebViewHandler = Handler(Looper.getMainLooper())
 
-                // Extract the individual pieces of information from the current website SSL certificate.
-                val currentWebsiteIssuedToCName = currentWebsiteSslCertificate.issuedTo.cName
-                val currentWebsiteIssuedToOName = currentWebsiteSslCertificate.issuedTo.oName
-                val currentWebsiteIssuedToUName = currentWebsiteSslCertificate.issuedTo.uName
-                val currentWebsiteIssuedByCName = currentWebsiteSslCertificate.issuedBy.cName
-                val currentWebsiteIssuedByOName = currentWebsiteSslCertificate.issuedBy.oName
-                val currentWebsiteIssuedByUName = currentWebsiteSslCertificate.issuedBy.uName
-                val currentWebsiteSslStartDate = currentWebsiteSslCertificate.validNotBeforeDate
-                val currentWebsiteSslEndDate = currentWebsiteSslCertificate.validNotAfterDate
+            // Create a runnable to set the current WebView.
+            val setCurrentWebWebRunnable = Runnable {
+                // Set the current WebView.
+                setCurrentWebView(pageNumber)
+            }
 
-                // Get the pinned SSL certificate.
-                val (pinnedSslCertificateStringArray, pinnedSslCertificateDateArray) = nestedScrollWebView.getPinnedSslCertificate()
+            // Try setting the current WebView again after 100 milliseconds.
+            setCurrentWebViewHandler.postDelayed(setCurrentWebWebRunnable, 100)
+        }
+    }
 
-                // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
-                if (nestedScrollWebView.hasPinnedSslCertificate() &&
-                    (currentWebsiteIssuedToCName == pinnedSslCertificateStringArray[0]) &&
-                    (currentWebsiteIssuedToOName == pinnedSslCertificateStringArray[1]) &&
-                    (currentWebsiteIssuedToUName == pinnedSslCertificateStringArray[2]) &&
-                    (currentWebsiteIssuedByCName == pinnedSslCertificateStringArray[3]) &&
-                    (currentWebsiteIssuedByOName == pinnedSslCertificateStringArray[4]) &&
-                    (currentWebsiteIssuedByUName == pinnedSslCertificateStringArray[5]) &&
-                    (currentWebsiteSslStartDate == pinnedSslCertificateDateArray[0]) &&
-                    (currentWebsiteSslEndDate == pinnedSslCertificateDateArray[1])) {
+    // The view parameter cannot be removed because it is called from the layout onClick.
+    fun toggleBookmarksDrawerPinned(@Suppress("UNUSED_PARAMETER")view: View?) {
+        // Toggle the bookmarks drawer pinned tracker.
+        bookmarksDrawerPinned = !bookmarksDrawerPinned
 
-                    // An SSL certificate is pinned and matches the current domain certificate.  Proceed to the website without displaying an error.
-                    handler.proceed()
-                } else {  // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
-                    // Store the SSL error handler.
-                    nestedScrollWebView.sslErrorHandler = handler
+        // Update the bookmarks drawer pinned image view.
+        updateBookmarksDrawerPinnedImageView()
+    }
 
-                    // Instantiate an SSL certificate error alert dialog.
-                    val sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error, nestedScrollWebView.webViewFragmentId)
+    private fun updateBookmarksDrawerPinnedImageView() {
+        // Set the current icon.
+        if (bookmarksDrawerPinned)
+            bookmarksDrawerPinnedImageView.setImageResource(R.drawable.pin_selected)
+        else
+            bookmarksDrawerPinnedImageView.setImageResource(R.drawable.pin)
+    }
 
-                    // Try to show the dialog.  The SSL error handler continues to function even when the WebView is paused.  Attempting to display a dialog in that state leads to a crash.
-                    try {
-                        // Show the SSL certificate error dialog.
-                        sslCertificateErrorDialogFragment.show(supportFragmentManager, getString(R.string.ssl_certificate_error))
-                    } catch (exception: Exception) {
-                        // Add the dialog to the pending dialog array list.  It will be displayed in `onStart()`.
-                        pendingDialogsArrayList.add(PendingDialogDataClass(sslCertificateErrorDialogFragment, getString(R.string.ssl_certificate_error)))
-                    }
-                }
-            }
-        }
+    private fun updateDomainsSettingsSet() {
+        // Reset the domains settings set.
+        domainsSettingsSet = HashSet()
 
-        // Check to see if the state is being restored.
-        if (restoringState) {  // The state is being restored.
-            // Resume the nested scroll WebView JavaScript timers.
-            nestedScrollWebView.resumeTimers()
-        } else if (pageNumber == 0) {  // The first page is being loaded.
-            // Set this nested scroll WebView as the current WebView.
-            currentWebView = nestedScrollWebView
+        // Get a domains cursor.
+        val domainsCursor = domainsDatabaseHelper!!.domainNameCursorOrderedByDomain
 
-            // Get the intent that started the app.
-            val launchingIntent = intent
+        // Get the current count of domains.
+        val domainsCount = domainsCursor.count
 
-            // Reset the intent.  This prevents a duplicate tab from being created on restart.
-            intent = Intent()
+        // Get the domain name column index.
+        val domainNameColumnIndex = domainsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.DOMAIN_NAME)
 
-            // Get the information from the intent.
-            val launchingIntentAction = launchingIntent.action
-            val launchingIntentUriData = launchingIntent.data
-            val launchingIntentStringExtra = launchingIntent.getStringExtra(Intent.EXTRA_TEXT)
+        // Populate the domain settings set.
+        for (i in 0 until domainsCount) {
+            // Move the domains cursor to the current row.
+            domainsCursor.moveToPosition(i)
 
-            // Parse the launching intent URL.  Suppress the suggestions of using elvis expressions as they make the logic very difficult to follow.
-            @Suppress("IfThenToElvis") val urlToLoadString = if ((launchingIntentAction != null) && (launchingIntentAction == Intent.ACTION_WEB_SEARCH)) {  // The intent contains a search string.
-                // Sanitize the search input and convert it to a search.
-                val encodedSearchString = try {
-                    URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8")
-                } catch (exception: UnsupportedEncodingException) {
-                    ""
-                }
+            // Store the domain name in the domain settings set.
+            domainsSettingsSet.add(domainsCursor.getString(domainNameColumnIndex))
+        }
 
-                // Add the search URL to the encodedSearchString
-                searchURL + encodedSearchString
-            } else if (launchingIntentUriData != null) {  // The launching intent contains a URL formatted as a URI.
-                // Get the URL from the URI.
-                launchingIntentUriData.toString()
-            } else if (launchingIntentStringExtra != null) {  // The launching intent contains text that might be a URL.
-                // Get the URL from the string extra.
-                launchingIntentStringExtra
-            } else if (urlString != "") {  // The activity has been restarted.
-                // Load the saved URL.
-                urlString
-            } else {  // The is no saved URL and there is no URL in the intent.
-                // Load the homepage.
-                sharedPreferences.getString("homepage", getString(R.string.homepage_default_value))
-            }
+        // Close the domains cursor.
+        domainsCursor.close()
+    }
 
-            // Load the website if not waiting for the proxy.
-            if (waitingForProxy) {  // Store the URL to be loaded in the Nested Scroll WebView.
-                nestedScrollWebView.waitingForProxyUrlString = urlToLoadString!!
-            } else {  // Load the URL.
-                loadUrl(nestedScrollWebView, urlToLoadString!!)
-            }
+    override fun updateFontSize(dialogFragment: DialogFragment) {
+        // Get the dialog.
+        val dialog = dialogFragment.dialog!!
 
-            // Reset the intent.  This prevents a duplicate tab from being created on a subsequent restart if loading an link from a new intent on restart.
-            // For example, this prevents a duplicate tab if a link is loaded from the Guide after changing the theme in the guide and then changing the theme again in the main activity.
-            intent = Intent()
-        } else {  // This is not the first tab.
-            // Load the URL.
-            loadUrl(nestedScrollWebView, urlString)
+        // Get a handle for the font size edit text.
+        val fontSizeEditText = dialog.findViewById<EditText>(R.id.font_size_edittext)
 
-            // Set the focus and display the keyboard if the URL is blank.
-            if (urlString == "") {
-                // Request focus for the URL text box.
-                urlEditText.requestFocus()
+        // Initialize the new font size variable with the current font size.
+        var newFontSize = currentWebView!!.settings.textZoom
 
-                // Create a display keyboard handler.
-                val displayKeyboardHandler = Handler(Looper.getMainLooper())
+        // Get the font size from the edit text.
+        try {
+            newFontSize = fontSizeEditText.text.toString().toInt()
+        } catch (exception: Exception) {
+            // If the edit text does not contain a valid font size do nothing.
+        }
 
-                // Create a display keyboard runnable.
-                val displayKeyboardRunnable = Runnable {
-                    // Display the keyboard.
-                    inputMethodManager.showSoftInput(urlEditText, 0)
-                }
+        // Apply the new font size.
+        currentWebView!!.settings.textZoom = newFontSize
+    }
 
-                // Display the keyboard after 100 milliseconds, which leaves enough time for the tab to transition.
-                displayKeyboardHandler.postDelayed(displayKeyboardRunnable, 100)
-            }
+    private fun updatePrivacyIcons(runInvalidateOptionsMenu: Boolean) {
+        // Only update the privacy icons if the options menu and the current WebView have already been populated.
+        if ((optionsMenu != null) && (currentWebView != null)) {
+            // Update the privacy icon.
+            if (currentWebView!!.settings.javaScriptEnabled)  // JavaScript is enabled.
+                optionsPrivacyMenuItem.setIcon(R.drawable.javascript_enabled)
+            else if (currentWebView!!.acceptCookies)  // JavaScript is disabled but cookies are enabled.
+                optionsPrivacyMenuItem.setIcon(R.drawable.warning)
+            else  // All the dangerous features are disabled.
+                optionsPrivacyMenuItem.setIcon(R.drawable.privacy_mode)
+
+            // Update the cookies icon.
+            if (currentWebView!!.acceptCookies)
+                optionsCookiesMenuItem.setIcon(R.drawable.cookies_enabled)
+            else
+                optionsCookiesMenuItem.setIcon(R.drawable.cookies_disabled)
+
+            // Update the refresh icon.
+            if (optionsRefreshMenuItem.title == getString(R.string.refresh))  // The refresh icon is displayed.
+                optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled)
+            else  // The stop icon is displayed.
+                optionsRefreshMenuItem.setIcon(R.drawable.close_blue)
+
+            // `invalidateOptionsMenu()` calls `onPrepareOptionsMenu()` and redraws the icons in the app bar.
+            if (runInvalidateOptionsMenu)
+                invalidateOptionsMenu()
         }
     }
 }