]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blobdiff - app/src/main/java/com/stoutner/privacybrowser/activities/MainWebViewActivity.kt
Add an option to display under the camera cutouts. https://redmine.stoutner.com...
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / activities / MainWebViewActivity.kt
index fc14e997ab704a375f4904bb169e2473215b7b52..44304593978d31e828d206d9416703c2b1c00d59 100644 (file)
@@ -99,13 +99,16 @@ import androidx.appcompat.app.AppCompatDelegate
 import androidx.appcompat.content.res.AppCompatResources
 import androidx.appcompat.widget.Toolbar
 import androidx.coordinatorlayout.widget.CoordinatorLayout
+import androidx.core.content.ContextCompat
 import androidx.core.view.GravityCompat
 import androidx.cursoradapter.widget.CursorAdapter
 import androidx.drawerlayout.widget.DrawerLayout
 import androidx.fragment.app.DialogFragment
 import androidx.preference.PreferenceManager
+import androidx.recyclerview.widget.LinearLayoutManager
+import androidx.recyclerview.widget.RecyclerView
 import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
-import androidx.viewpager.widget.ViewPager
+import androidx.viewpager2.widget.ViewPager2
 import androidx.webkit.WebSettingsCompat
 import androidx.webkit.WebViewFeature
 
@@ -116,9 +119,9 @@ import com.google.android.material.snackbar.Snackbar
 import com.google.android.material.tabs.TabLayout
 
 import com.stoutner.privacybrowser.R
-import com.stoutner.privacybrowser.adapters.WebViewPagerAdapter
+import com.stoutner.privacybrowser.adapters.WebViewStateAdapter
 import com.stoutner.privacybrowser.coroutines.GetHostIpAddressesCoroutine
-import com.stoutner.privacybrowser.coroutines.PopulateBlocklistsCoroutine
+import com.stoutner.privacybrowser.coroutines.PopulateFilterListsCoroutine
 import com.stoutner.privacybrowser.coroutines.PrepareSaveDialogCoroutine
 import com.stoutner.privacybrowser.coroutines.SaveUrlCoroutine
 import com.stoutner.privacybrowser.coroutines.SaveWebpageImageCoroutine
@@ -137,8 +140,47 @@ 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.BOOKMARK_NAME
+import com.stoutner.privacybrowser.helpers.BOOKMARK_URL
+import com.stoutner.privacybrowser.helpers.COOKIES
+import com.stoutner.privacybrowser.helpers.DARK_THEME
+import com.stoutner.privacybrowser.helpers.DISABLED
+import com.stoutner.privacybrowser.helpers.DISPLAY_IMAGES
+import com.stoutner.privacybrowser.helpers.DOMAIN_NAME
+import com.stoutner.privacybrowser.helpers.ENABLE_DOM_STORAGE
+import com.stoutner.privacybrowser.helpers.ENABLE_EASYLIST
+import com.stoutner.privacybrowser.helpers.ENABLE_EASYPRIVACY
+import com.stoutner.privacybrowser.helpers.ENABLE_FANBOYS_ANNOYANCE_LIST
+import com.stoutner.privacybrowser.helpers.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST
+import com.stoutner.privacybrowser.helpers.ENABLE_FORM_DATA
+import com.stoutner.privacybrowser.helpers.ENABLE_JAVASCRIPT
+import com.stoutner.privacybrowser.helpers.ENABLE_ULTRAPRIVACY
+import com.stoutner.privacybrowser.helpers.ENABLED
+import com.stoutner.privacybrowser.helpers.FAVORITE_ICON
+import com.stoutner.privacybrowser.helpers.FOLDER_ID
+import com.stoutner.privacybrowser.helpers.FONT_SIZE
+import com.stoutner.privacybrowser.helpers.ID
+import com.stoutner.privacybrowser.helpers.IP_ADDRESSES
+import com.stoutner.privacybrowser.helpers.IS_FOLDER
+import com.stoutner.privacybrowser.helpers.LIGHT_THEME
+import com.stoutner.privacybrowser.helpers.PINNED_IP_ADDRESSES
+import com.stoutner.privacybrowser.helpers.PINNED_SSL_CERTIFICATE
+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.SSL_ISSUED_BY_COMMON_NAME
+import com.stoutner.privacybrowser.helpers.SSL_ISSUED_BY_ORGANIZATION
+import com.stoutner.privacybrowser.helpers.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT
+import com.stoutner.privacybrowser.helpers.SSL_ISSUED_TO_COMMON_NAME
+import com.stoutner.privacybrowser.helpers.SSL_ISSUED_TO_ORGANIZATION
+import com.stoutner.privacybrowser.helpers.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT
+import com.stoutner.privacybrowser.helpers.SWIPE_TO_REFRESH
+import com.stoutner.privacybrowser.helpers.SYSTEM_DEFAULT
+import com.stoutner.privacybrowser.helpers.WEBVIEW_THEME
+import com.stoutner.privacybrowser.helpers.WIDE_VIEWPORT
 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper
+import com.stoutner.privacybrowser.helpers.CheckFilterListHelper
 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper
 import com.stoutner.privacybrowser.helpers.ProxyHelper
 import com.stoutner.privacybrowser.helpers.SanitizeUrlHelper
@@ -149,7 +191,6 @@ import com.stoutner.privacybrowser.views.EASYPRIVACY
 import com.stoutner.privacybrowser.views.FANBOYS_ANNOYANCE_LIST
 import com.stoutner.privacybrowser.views.FANBOYS_SOCIAL_BLOCKING_LIST
 import com.stoutner.privacybrowser.views.THIRD_PARTY_REQUESTS
-import com.stoutner.privacybrowser.views.ULTRALIST
 import com.stoutner.privacybrowser.views.ULTRAPRIVACY
 import com.stoutner.privacybrowser.views.NestedScrollWebView
 
@@ -195,21 +236,19 @@ 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,
+    NavigationView.OnNavigationItemSelectedListener, OpenDialog.OpenListener, PinnedMismatchDialog.PinnedMismatchListener, PopulateFilterListsCoroutine.PopulateFilterListsListener, SaveDialog.SaveListener,
     UrlHistoryDialog.NavigateHistoryListener, WebViewTabFragment.NewTabListener {
 
     companion object {
         // Define the public static variables.
-        var currentBookmarksFolder = ""
+        var currentBookmarksFolderId = 0L
         val executorService = Executors.newFixedThreadPool(4)!!
         var orbotStatus = "unknown"
         val pendingDialogsArrayList = ArrayList<PendingDialogDataClass>()
         var proxyMode = ProxyHelper.NONE
         var restartFromBookmarksActivity = false
-        var webViewPagerAdapter: WebViewPagerAdapter? = null
+        var webViewStateAdapter: WebViewStateAdapter? = null
 
         // Declare the public static variables.
         lateinit var appBarLayout: AppBarLayout
@@ -217,13 +256,16 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
 
     // Declare the class variables.
     private lateinit var appBar: ActionBar
-    private lateinit var blocklistHelper: BlocklistHelper
+    private lateinit var checkFilterListHelper: CheckFilterListHelper
     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 defaultFontSizeString: String
+    private lateinit var defaultUserAgentName: String
+    private lateinit var defaultWebViewTheme: String
     private lateinit var domainsSettingsSet: MutableSet<String>
     private lateinit var drawerLayout: DrawerLayout
     private lateinit var easyList: ArrayList<List<Array<String>>>
@@ -241,9 +283,10 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
     private lateinit var navigationForwardMenuItem: MenuItem
     private lateinit var navigationHistoryMenuItem: MenuItem
     private lateinit var navigationRequestsMenuItem: MenuItem
+    private lateinit var navigationScrollToBottomMenuItem: MenuItem
+    private lateinit var navigationView: NavigationView
     private lateinit var optionsAddOrEditDomainMenuItem: MenuItem
     private lateinit var optionsBlockAllThirdPartyRequestsMenuItem: MenuItem
-    private lateinit var optionsBlocklistsMenuItem: MenuItem
     private lateinit var optionsClearCookiesMenuItem: MenuItem
     private lateinit var optionsClearDataMenuItem: MenuItem
     private lateinit var optionsClearDomStorageMenuItem: MenuItem
@@ -256,6 +299,7 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
     private lateinit var optionsEasyPrivacyMenuItem: MenuItem
     private lateinit var optionsFanboysAnnoyanceListMenuItem: MenuItem
     private lateinit var optionsFanboysSocialBlockingListMenuItem: MenuItem
+    private lateinit var optionsFilterListsMenuItem: MenuItem
     private lateinit var optionsFontSizeMenuItem: MenuItem
     private lateinit var optionsPrivacyMenuItem: MenuItem
     private lateinit var optionsProxyCustomMenuItem: MenuItem
@@ -276,12 +320,12 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
     private lateinit var optionsUserAgentFirefoxOnAndroidMenuItem: MenuItem
     private lateinit var optionsUserAgentFirefoxOnLinuxMenuItem: MenuItem
     private lateinit var optionsUserAgentFirefoxOnWindowsMenuItem: MenuItem
-    private lateinit var optionsUserAgentInternetExplorerOnWindowsMenuItem: MenuItem
     private lateinit var optionsUserAgentMenuItem: MenuItem
     private lateinit var optionsUserAgentPrivacyBrowserMenuItem: MenuItem
     private lateinit var optionsUserAgentSafariOnIosMenuItem: MenuItem
     private lateinit var optionsUserAgentSafariOnMacosMenuItem: MenuItem
     private lateinit var optionsUserAgentWebViewDefaultMenuItem: MenuItem
+    private lateinit var optionsViewSourceMenuItem: MenuItem
     private lateinit var optionsWideViewportMenuItem: MenuItem
     private lateinit var proxyHelper: ProxyHelper
     private lateinit var redColorSpan: ForegroundColorSpan
@@ -294,10 +338,15 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
     private lateinit var tabsLinearLayout: LinearLayout
     private lateinit var toolbar: Toolbar
     private lateinit var webViewDefaultUserAgent: String
-    private lateinit var webViewPager: ViewPager
+    private lateinit var webViewThemeEntryValuesStringArray: Array<String>
+    private lateinit var webViewViewPager2: ViewPager2
     private lateinit var ultraList: ArrayList<List<Array<String>>>
     private lateinit var urlEditText: EditText
     private lateinit var urlRelativeLayout: RelativeLayout
+    private lateinit var userAgentDataArray: Array<String>
+    private lateinit var userAgentNamesArray: Array<String>
+    private lateinit var userAgentDataArrayAdapter: ArrayAdapter<CharSequence>
+    private lateinit var userAgentNamesArrayAdapter: ArrayAdapter<CharSequence>
 
     // Define the class variables.
     private var actionBarDrawerToggle: ActionBarDrawerToggle? = null
@@ -307,17 +356,32 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
     private var bookmarksDrawerPinned = false
     private var bottomAppBar = false
     private var currentWebView: NestedScrollWebView? = null
+    private var defaultBlockAllThirdPartyRequests = false
+    private var defaultCookies = false
+    private var defaultDisplayWebpageImages = true
+    private var defaultDomStorage = false
+    private var defaultEasyList = true
+    private var defaultEasyPrivacy = true
+    private var defaultFanboysAnnoyanceList = true
+    private var defaultFanboysSocialBlockingList = true
+    private var defaultFormData = false  // Form data can be removed once the minimum API >= 26.
     private var defaultProgressViewEndOffset = 0
     private var defaultProgressViewStartOffset = 0
+    private var defaultJavaScript = false
+    private var defaultSwipeToRefresh = true
+    private var defaultUltraList = true
+    private var defaultUltraPrivacy = true
+    private var defaultWideViewport = true
     private var displayAdditionalAppBarIcons = false
     private var displayingFullScreenVideo = false
     private var domainsDatabaseHelper: DomainsDatabaseHelper? = null
     private var downloadWithExternalApp = false
     private var fullScreenBrowsingModeEnabled = false
-    private var hideAppBar = false
+    private var hideAppBar = true
     private var inFullScreenBrowsingMode = false
     private var incognitoModeEnabled = false
     private var loadingNewIntent = false
+    private var navigationDrawerFirstView = true
     private var objectAnimator = ObjectAnimator()
     private var optionsMenu: Menu? = null
     private var orbotStatusBroadcastReceiver: BroadcastReceiver? = null
@@ -333,6 +397,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.
@@ -439,12 +509,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)
@@ -460,6 +524,15 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
         val allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false)
         bottomAppBar = sharedPreferences.getBoolean(getString(R.string.bottom_app_bar_key), false)
         displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false)
+        val displayUnderCutouts = sharedPreferences.getBoolean(getString(R.string.display_under_cutouts_key), false)
+
+        // Display under cutouts if specified.  This must be done here as it doesn't appear to work correctly if handled after the app is fully initialized.
+        if (displayUnderCutouts) {
+            if (Build.VERSION.SDK_INT >= 30)
+                window.attributes.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS
+            else if (Build.VERSION.SDK_INT >= 28)
+                window.attributes.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
+        }
 
         // Get the theme entry values string array.
         val appThemeEntryValuesStringArray = resources.getStringArray(R.array.app_theme_entry_values)
@@ -486,7 +559,7 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
 
         // Do not continue if the app theme is different than the OS theme.  The app always initially starts in the OS theme.
         // If the user has specified the opposite theme should be used, the app will restart in that mode after the above `setDefaultNightMode()` code processes.  However, the restart is delayed.
-        // If the blacklist coroutine starts below it will continue to run during the restart, which leads to indeterminate behavior, with the system often not knowing how many tabs exist.
+        // If the filter list coroutine starts below it will continue to run during the restart, which leads to indeterminate behavior, with the system often not knowing how many tabs exist.
         // See https://redmine.stoutner.com/issues/952.
         if ((appTheme == appThemeEntryValuesStringArray[0]) ||  // The system default theme is used.
             ((appTheme == appThemeEntryValuesStringArray[1]) && (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO)) ||  // The app is running in day theme as desired.
@@ -530,8 +603,8 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
             tabsLinearLayout = findViewById(R.id.tabs_linearlayout)
             tabLayout = findViewById(R.id.tablayout)
             swipeRefreshLayout = findViewById(R.id.swiperefreshlayout)
-            webViewPager = findViewById(R.id.webviewpager)
-            val navigationView = findViewById<NavigationView>(R.id.navigationview)
+            webViewViewPager2 = findViewById(R.id.webview_viewpager2)
+            navigationView = findViewById(R.id.navigationview)
             bookmarksListView = findViewById(R.id.bookmarks_drawer_listview)
             bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview)
             bookmarksDrawerPinnedImageView = findViewById(R.id.bookmarks_drawer_pinned_imageview)
@@ -543,6 +616,7 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
             // Get handles for the navigation menu items.
             navigationBackMenuItem = navigationMenu.findItem(R.id.back)
             navigationForwardMenuItem = navigationMenu.findItem(R.id.forward)
+            navigationScrollToBottomMenuItem = navigationMenu.findItem(R.id.scroll_to_bottom)
             navigationHistoryMenuItem = navigationMenu.findItem(R.id.history)
             navigationRequestsMenuItem = navigationMenu.findItem(R.id.requests)
 
@@ -568,20 +642,23 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
             // Create the hamburger icon at the start of the AppBar.
             actionBarDrawerToggle = ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer)
 
-            // Initially disable the sliding drawers.  They will be enabled once the blocklists are loaded.
+            // Initially disable the sliding drawers.  They will be enabled once the filter lists are loaded.
             drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
 
-            // Initially hide the user interface so that only the blocklist loading screen is shown (if reloading).
+            // Initially hide the user interface so that only the filter list loading screen is shown (if reloading).
             drawerLayout.visibility = View.GONE
 
-            // Initialize the WebView pager adapter.
-            webViewPagerAdapter = WebViewPagerAdapter(supportFragmentManager)
+            // Initialize the WebView state adapter.
+            webViewStateAdapter = WebViewStateAdapter(this)
 
             // Set the pager adapter on the web view pager.
-            webViewPager.adapter = webViewPagerAdapter
+            webViewViewPager2.adapter = webViewStateAdapter
 
             // Store up to 100 tabs in memory.
-            webViewPager.offscreenPageLimit = 100
+            webViewViewPager2.offscreenPageLimit = 100
+
+            // Disable swiping between pages in the view pager.
+            webViewViewPager2.isUserInputEnabled = false
 
             // Get a handle for the cookie manager.
             cookieManager = CookieManager.getInstance()
@@ -626,12 +703,12 @@ 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()
+
+                        // Update the URL edit text after a delay.
+                        updateUrlEditTextAfterDelay()
+                    } else {  // Close the current tab.
+                        // A view is required because the method is also called by an XML `onClick`.
+                        closeTab(null)
                     }
                 }
             }
@@ -639,18 +716,35 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
             // Register the on back pressed callback.
             onBackPressedDispatcher.addCallback(this, onBackPressedCallback)
 
-            // Instantiate the populate blocklists coroutine.
-            val populateBlocklistsCoroutine = PopulateBlocklistsCoroutine(this)
+            // Instantiate the populate filter lists coroutine.
+            val populateFilterListsCoroutine = PopulateFilterListsCoroutine(this)
 
-            // Populate the blocklists.
-            populateBlocklistsCoroutine.populateBlocklists(this)
+            // Populate the filter lists.
+            populateFilterListsCoroutine.populateFilterLists(this)
         }
     }
 
+    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)
 
+        // Close the navigation drawer if it is open.
+        if (drawerLayout.isDrawerVisible(GravityCompat.START))
+            drawerLayout.closeDrawer(GravityCompat.START)
+
+        // Close the bookmarks drawer if it is open.
+        if (drawerLayout.isDrawerVisible(GravityCompat.END))
+            drawerLayout.closeDrawer(GravityCompat.END)
+
         // Get the information from the intent.
         val intentAction = intent.action
         val intentUriData = intent.data
@@ -693,26 +787,13 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
                     loadingNewIntent = true
 
                     // Add a new tab.
-                    addNewTab(url!!, true)
+                    addNewTab(url!!, adjacent = false, moveToTab = true)
                 } else {  // Load the URL in the current tab.
                     // Make it so.
                     loadUrl(currentWebView!!, url!!)
                 }
-
-                // Close the navigation drawer if it is open.
-                if (drawerLayout.isDrawerVisible(GravityCompat.START))
-                    drawerLayout.closeDrawer(GravityCompat.START)
-
-                // Close the bookmarks drawer if it is open.
-                if (drawerLayout.isDrawerVisible(GravityCompat.END))
-                    drawerLayout.closeDrawer(GravityCompat.END)
             }
         } else {  // The app has been restarted.
-            // If the new intent will open a new tab, set the saved tab position to be the size of the saved state array list.
-            // The tab position is 0 based, meaning the at the new tab will be the tab position that is restored.
-            if ((intentUriData != null) || (intentStringExtra != null) || isWebSearch)
-                savedTabPosition = savedStateArrayList!!.size
-
             // Replace the intent that started the app with this one.  This will load the tab after the others have been restored.
             setIntent(intent)
         }
@@ -740,9 +821,9 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
             updateDomainsSettingsSet()
 
             // Reapply the domain settings for each tab.
-            for (i in 0 until webViewPagerAdapter!!.count) {
+            for (i in 0 until webViewStateAdapter!!.itemCount) {
                 // Get the WebView tab fragment.
-                val webViewTabFragment = webViewPagerAdapter!!.getPageFragment(i)
+                val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
 
                 // Get the fragment view.
                 val fragmentView = webViewTabFragment.view
@@ -783,11 +864,11 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
         // Run the default commands.
         super.onStart()
 
-        // Resume any WebViews if the pager adapter exists.  If the app is restarting to change the initial app theme it won't have been populated yet.
-        if (webViewPagerAdapter != null) {
-            for (i in 0 until webViewPagerAdapter!!.count) {
+        // Resume any WebViews if the state adapter exists.  If the app is restarting to change the initial app theme it won't have been populated yet.
+        if (webViewStateAdapter != null) {
+            for (i in 0 until webViewStateAdapter!!.itemCount) {
                 // Get the WebView tab fragment.
-                val webViewTabFragment = webViewPagerAdapter!!.getPageFragment(i)
+                val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
 
                 // Get the fragment view.
                 val fragmentView = webViewTabFragment.view
@@ -838,51 +919,20 @@ 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)
 
-        // Only save the instance state if the WebView pager adapter is not null, which will be the case if the app is restarting to change the initial app theme.
-        if (webViewPagerAdapter != null) {
+        // Only save the instance state if the WebView state adapter is not null, which will be the case if the app is restarting to change the initial app theme.
+        if (webViewStateAdapter != null) {
             // Initialize the saved state array lists.
             savedStateArrayList = ArrayList<Bundle>()
             savedNestedScrollWebViewStateArrayList = ArrayList<Bundle>()
 
             // Get the URLs from each tab.
-            for (i in 0 until webViewPagerAdapter!!.count) {
+            for (i in 0 until webViewStateAdapter!!.itemCount) {
                 // Get the WebView tab fragment.
-                val webViewTabFragment = webViewPagerAdapter!!.getPageFragment(i)
+                val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
 
                 // Get the fragment view.
                 val fragmentView = webViewTabFragment.view
@@ -917,6 +967,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 state adapter is not null, which is the case if the app is restarting to change the initial app theme.
+        if (webViewStateAdapter != null) {
+            // Pause each web view.
+            for (i in 0 until webViewStateAdapter!!.itemCount) {
+                // Get the WebView tab fragment.
+                val webViewTabFragment = webViewStateAdapter!!.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) {
@@ -934,6 +1015,29 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
         super.onDestroy()
     }
 
+    override fun onConfigurationChanged(newConfig: Configuration) {
+        // Run the default commands.
+        super.onConfigurationChanged(newConfig)
+
+        // Reset the navigation drawer first view flag.
+        navigationDrawerFirstView = true
+
+        // Get the current page.
+        val currentPage = webViewViewPager2.currentItem
+
+        // Toggle the pages if there is more than one so that the view pager will recalculate their size.
+        if (currentPage > 0) {
+            // Switch to the previous page after 25 milliseconds.
+            webViewViewPager2.postDelayed ({ webViewViewPager2.currentItem = (currentPage - 1) }, 25)
+
+            // Switch back to the current page after the view pager has quiesced (which we are deciding should be 25 milliseconds).
+            webViewViewPager2.postDelayed ({ webViewViewPager2.currentItem = currentPage }, 25)
+        }
+
+        // Scroll to the current tab position after 25 milliseconds.
+        tabLayout.postDelayed ({ tabLayout.setScrollPosition(currentPage, 0F, false, false) }, 25)
+    }
+
     override fun onCreateOptionsMenu(menu: Menu): Boolean {
         // Inflate the menu.  This adds items to the app bar if it is present.
         menuInflater.inflate(R.menu.webview_options_menu, menu)
@@ -949,11 +1053,11 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
         optionsClearCookiesMenuItem = menu.findItem(R.id.clear_cookies)
         optionsClearDomStorageMenuItem = menu.findItem(R.id.clear_dom_storage)
         optionsClearFormDataMenuItem = menu.findItem(R.id.clear_form_data) // Form data can be removed once the minimum API >= 26.
-        optionsBlocklistsMenuItem = menu.findItem(R.id.blocklists)
         optionsEasyListMenuItem = menu.findItem(R.id.easylist)
         optionsEasyPrivacyMenuItem = menu.findItem(R.id.easyprivacy)
         optionsFanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list)
         optionsFanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list)
+        optionsFilterListsMenuItem = menu.findItem(R.id.filterlists)
         optionsUltraListMenuItem = menu.findItem(R.id.ultralist)
         optionsUltraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy)
         optionsBlockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests)
@@ -973,7 +1077,6 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
         optionsUserAgentFirefoxOnWindowsMenuItem = menu.findItem(R.id.user_agent_firefox_on_windows)
         optionsUserAgentChromeOnWindowsMenuItem = menu.findItem(R.id.user_agent_chrome_on_windows)
         optionsUserAgentEdgeOnWindowsMenuItem = menu.findItem(R.id.user_agent_edge_on_windows)
-        optionsUserAgentInternetExplorerOnWindowsMenuItem = menu.findItem(R.id.user_agent_internet_explorer_on_windows)
         optionsUserAgentSafariOnMacosMenuItem = menu.findItem(R.id.user_agent_safari_on_macos)
         optionsUserAgentCustomMenuItem = menu.findItem(R.id.user_agent_custom)
         optionsSwipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh)
@@ -981,6 +1084,7 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
         optionsDisplayImagesMenuItem = menu.findItem(R.id.display_images)
         optionsDarkWebViewMenuItem = menu.findItem(R.id.dark_webview)
         optionsFontSizeMenuItem = menu.findItem(R.id.font_size)
+        optionsViewSourceMenuItem = menu.findItem(R.id.view_source)
         optionsAddOrEditDomainMenuItem = menu.findItem(R.id.add_or_edit_domain)
 
         // Set the initial status of the privacy icons.  `false` does not call `invalidateOptionsMenu` as the last step.
@@ -993,9 +1097,6 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
         // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
         optionsClearFormDataMenuItem.isEnabled = Build.VERSION.SDK_INT < 26
 
-        // Only display the dark WebView menu item if the API >= 29.
-        optionsDarkWebViewMenuItem.isVisible = Build.VERSION.SDK_INT >= 29
-
         // Set the status of the additional app bar icons.  Setting the refresh menu item to `SHOW_AS_ACTION_ALWAYS` makes it appear even on small devices like phones.
         if (displayAdditionalAppBarIcons) {  // Display the additional icons.
             optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
@@ -1046,7 +1147,7 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
             // Set the status of the menu item checkboxes.
             optionsDomStorageMenuItem.isChecked = currentWebView!!.settings.domStorageEnabled
             @Suppress("DEPRECATION")
-            optionsSaveFormDataMenuItem.isChecked = currentWebView!!.settings.saveFormData // Form data can be removed once the minimum API >= 26.
+            optionsSaveFormDataMenuItem.isChecked = currentWebView!!.settings.saveFormData  // Form data can be removed once the minimum API >= 26.
             optionsEasyListMenuItem.isChecked = currentWebView!!.easyListEnabled
             optionsEasyPrivacyMenuItem.isChecked = currentWebView!!.easyPrivacyEnabled
             optionsFanboysAnnoyanceListMenuItem.isChecked = currentWebView!!.fanboysAnnoyanceListEnabled
@@ -1058,13 +1159,13 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
             optionsWideViewportMenuItem.isChecked = currentWebView!!.settings.useWideViewPort
             optionsDisplayImagesMenuItem.isChecked = currentWebView!!.settings.loadsImagesAutomatically
 
-            // Initialize the display names for the blocklists with the number of blocked requests.
-            optionsBlocklistsMenuItem.title = getString(R.string.blocklists) + " - " + currentWebView!!.getRequestsCount(BLOCKED_REQUESTS)
+            // Set the display names for the filter lists with the number of blocked requests.
+            optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + currentWebView!!.getRequestsCount(BLOCKED_REQUESTS)
             optionsEasyListMenuItem.title = currentWebView!!.getRequestsCount(EASYLIST).toString() + " - " + getString(R.string.easylist)
             optionsEasyPrivacyMenuItem.title = currentWebView!!.getRequestsCount(EASYPRIVACY).toString() + " - " + getString(R.string.easyprivacy)
             optionsFanboysAnnoyanceListMenuItem.title = currentWebView!!.getRequestsCount(FANBOYS_ANNOYANCE_LIST).toString() + " - " + getString(R.string.fanboys_annoyance_list)
             optionsFanboysSocialBlockingListMenuItem.title = currentWebView!!.getRequestsCount(FANBOYS_SOCIAL_BLOCKING_LIST).toString() + " - " + getString(R.string.fanboys_social_blocking_list)
-            optionsUltraListMenuItem.title = currentWebView!!.getRequestsCount(ULTRALIST).toString() + " - " + getString(R.string.ultralist)
+            optionsUltraListMenuItem.title = currentWebView!!.getRequestsCount(com.stoutner.privacybrowser.views.ULTRALIST).toString() + " - " + getString(R.string.ultralist)
             optionsUltraPrivacyMenuItem.title = currentWebView!!.getRequestsCount(ULTRAPRIVACY).toString() + " - " + getString(R.string.ultraprivacy)
             optionsBlockAllThirdPartyRequestsMenuItem.title = currentWebView!!.getRequestsCount(THIRD_PARTY_REQUESTS).toString() + " - " + getString(R.string.block_all_third_party_requests)
 
@@ -1077,9 +1178,15 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
             // Enable dark WebView if night mode is enabled.
             optionsDarkWebViewMenuItem.isEnabled = (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES)
 
-            // Set the checkbox status for dark WebView 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 checkbox status for dark WebView if algorithmic darkening is supported.
+            if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING))
                 optionsDarkWebViewMenuItem.isChecked = WebSettingsCompat.isAlgorithmicDarkeningAllowed(currentWebView!!.settings)
+
+            // Set the view source title according to the current URL.
+            if (currentWebView!!.currentUrl.startsWith("view-source:"))
+                optionsViewSourceMenuItem.title = getString(R.string.view_rendered_website)
+            else
+                optionsViewSourceMenuItem.title = getString(R.string.view_source)
         }
 
         // Set the cookies menu item checked status.
@@ -1243,15 +1350,7 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
                 optionsUserAgentEdgeOnWindowsMenuItem.isChecked = true
             }
 
-            resources.getStringArray(R.array.user_agent_data)[10] -> {  // Internet Explorer on Windows.
-                // Update the user agent menu item title.
-                optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_internet_explorer_on_windows)
-
-                // Select the Internet on Windows radio box.
-                optionsUserAgentInternetExplorerOnWindowsMenuItem.isChecked = true
-            }
-
-            resources.getStringArray(R.array.user_agent_data)[11] -> {  // Safari on macOS.
+            resources.getStringArray(R.array.user_agent_data)[10] -> {  // Safari on macOS.
                 // Update the user agent menu item title.
                 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_macos)
 
@@ -1290,11 +1389,11 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
 
                 // Display a snackbar.
                 if (currentWebView!!.settings.javaScriptEnabled)  // JavaScrip is enabled.
-                    Snackbar.make(webViewPager, R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show()
+                    Snackbar.make(webViewViewPager2, R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show()
                 else if (cookieManager.acceptCookie())  // JavaScript is disabled, but cookies are enabled.
-                    Snackbar.make(webViewPager, R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show()
+                    Snackbar.make(webViewViewPager2, R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show()
                 else  // Privacy mode.
-                    Snackbar.make(webViewPager, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show()
+                    Snackbar.make(webViewViewPager2, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show()
 
                 // Reload the current WebView.
                 currentWebView!!.reload()
@@ -1337,11 +1436,11 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
 
                 // Display a snackbar.
                 if (cookieManager.acceptCookie())  // Cookies are enabled.
-                    Snackbar.make(webViewPager, R.string.cookies_enabled, Snackbar.LENGTH_SHORT).show()
+                    Snackbar.make(webViewViewPager2, R.string.cookies_enabled, Snackbar.LENGTH_SHORT).show()
                 else if (currentWebView!!.settings.javaScriptEnabled)  // JavaScript is still enabled.
-                    Snackbar.make(webViewPager, R.string.cookies_disabled, Snackbar.LENGTH_SHORT).show()
+                    Snackbar.make(webViewViewPager2, R.string.cookies_disabled, Snackbar.LENGTH_SHORT).show()
                 else  // Privacy mode.
-                    Snackbar.make(webViewPager, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show()
+                    Snackbar.make(webViewViewPager2, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show()
 
                 // Reload the current WebView.
                 currentWebView!!.reload()
@@ -1362,9 +1461,9 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
 
                 // Display a snackbar.
                 if (currentWebView!!.settings.domStorageEnabled)
-                    Snackbar.make(webViewPager, R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show()
+                    Snackbar.make(webViewViewPager2, R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show()
                 else
-                    Snackbar.make(webViewPager, R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show()
+                    Snackbar.make(webViewViewPager2, R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show()
 
                 // Reload the current WebView.
                 currentWebView!!.reload()
@@ -1385,9 +1484,9 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
                 // Display a snackbar.
                 @Suppress("DEPRECATION")
                 if (currentWebView!!.settings.saveFormData)
-                    Snackbar.make(webViewPager, R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show()
+                    Snackbar.make(webViewViewPager2, R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show()
                 else
-                    Snackbar.make(webViewPager, R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show()
+                    Snackbar.make(webViewViewPager2, R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show()
 
                 // Update the privacy icon.
                 updatePrivacyIcons(true)
@@ -1401,7 +1500,7 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
 
             R.id.clear_cookies -> {  // Clear cookies.
                 // Create a snackbar.
-                Snackbar.make(webViewPager, R.string.cookies_deleted, Snackbar.LENGTH_LONG)
+                Snackbar.make(webViewViewPager2, R.string.cookies_deleted, Snackbar.LENGTH_LONG)
                     .setAction(R.string.undo) {}  // Everything will be handled by `onDismissed()` below.
                     .addCallback(object : Snackbar.Callback() {
                         override fun onDismissed(snackbar: Snackbar, event: Int) {
@@ -1419,7 +1518,7 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
 
             R.id.clear_dom_storage -> {  // Clear DOM storage.
                 // Create a snackbar.
-                Snackbar.make(webViewPager, R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
+                Snackbar.make(webViewViewPager2, R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
                     .setAction(R.string.undo) {}  // Everything will be handled by `onDismissed()` below.
                     .addCallback(object : Snackbar.Callback() {
                         override fun onDismissed(snackbar: Snackbar, event: Int) {
@@ -1476,7 +1575,7 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
 
             R.id.clear_form_data -> {  // Clear form data.  This can be remove once the minimum API >= 26.
                 // Create a snackbar.
-                Snackbar.make(webViewPager, R.string.form_data_deleted, Snackbar.LENGTH_LONG)
+                Snackbar.make(webViewViewPager2, R.string.form_data_deleted, Snackbar.LENGTH_LONG)
                     .setAction(R.string.undo) {}  // Everything will be handled by `onDismissed()` below.
                     .addCallback(object : Snackbar.Callback() {
                         override fun onDismissed(snackbar: Snackbar, event: Int) {
@@ -1751,20 +1850,9 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
                 true
             }
 
-            R.id.user_agent_internet_explorer_on_windows -> {  // User Agent - Internet Explorer on Windows.
-                // Update the user agent.
-                currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[10]
-
-                // Reload the current WebView.
-                currentWebView!!.reload()
-
-                // Consume the event.
-                true
-            }
-
             R.id.user_agent_safari_on_macos -> {  // User Agent - Safari on macOS.
                 // Update the user agent.
-                currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[11]
+                currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[10]
 
                 // Reload the current WebView.
                 currentWebView!!.reload()
@@ -1836,7 +1924,7 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
 
             R.id.dark_webview -> {  // Dark WebView.
                 // Toggle dark WebView if supported.
-                if ((Build.VERSION.SDK_INT >= 29) && WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING))
+                if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING))
                     WebSettingsCompat.setAlgorithmicDarkeningAllowed(currentWebView!!.settings, !WebSettingsCompat.isAlgorithmicDarkeningAllowed(currentWebView!!.settings)
                 )
 
@@ -1924,15 +2012,29 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
             }
 
             R.id.view_source -> {  // View source.
-                // Create an intent to launch the view source activity.
-                val viewSourceIntent = Intent(this, ViewSourceActivity::class.java)
+                // Open a new tab according to the current URL.
+                if (currentWebView!!.currentUrl.startsWith("view-source:")) {  // The source is currently viewed.
+                    // Open the rendered website in a new tab.
+                    addNewTab(currentWebView!!.currentUrl.substring(12, currentWebView!!.currentUrl.length), true, moveToTab = true)
+                } else {  // The rendered website is currently viewed.
+                    // Open the source in a new tab.
+                    addNewTab("view-source:${currentWebView!!.currentUrl}", adjacent = true, moveToTab = true)
+                }
+
+                // Consume the event.
+                true
+            }
+
+            R.id.view_headers -> {  // View headers.
+                // Create an intent to launch the view headers activity.
+                val viewHeadersIntent = Intent(this, ViewHeadersActivity::class.java)
 
                 // Add the variables to the intent.
-                viewSourceIntent.putExtra(CURRENT_URL, currentWebView!!.url)
-                viewSourceIntent.putExtra(USER_AGENT, currentWebView!!.settings.userAgentString)
+                viewHeadersIntent.putExtra(CURRENT_URL, currentWebView!!.url)
+                viewHeadersIntent.putExtra(USER_AGENT, currentWebView!!.settings.userAgentString)
 
                 // Make it so.
-                startActivity(viewSourceIntent)
+                startActivity(viewHeadersIntent)
 
                 // Consume the event.
                 true
@@ -2001,7 +2103,7 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
             }
 
             R.id.add_or_edit_domain -> {  // Add or edit domain.
-                // Reapply the domain settings on returning to `MainWebViewActivity`.
+                // Reapply the domain settings on returning to the main WebView activity.
                 reapplyDomainSettingsOnRestart = true
 
                 // Check if domain settings are currently applied.
@@ -2050,8 +2152,118 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
                     // Get the current domain from the URI.  Use an empty string if it is null.
                     val currentDomain = currentUri.host?: ""
 
+                    // Get the current settings status.
+                    val javaScriptInt = calculateSettingsInt(currentWebView!!.settings.javaScriptEnabled, sharedPreferences.getBoolean(getString(R.string.javascript_key), false))
+                    val cookiesInt = calculateSettingsInt(currentWebView!!.acceptCookies, sharedPreferences.getBoolean(getString(R.string.cookies_key), false))
+                    val domStorageInt = calculateSettingsInt(currentWebView!!.settings.domStorageEnabled, sharedPreferences.getBoolean(getString(R.string.dom_storage_key), false))
+                    val easyListInt = calculateSettingsInt(currentWebView!!.easyListEnabled, sharedPreferences.getBoolean(getString(R.string.easylist_key), true))
+                    val easyPrivacyInt = calculateSettingsInt(currentWebView!!.easyPrivacyEnabled, sharedPreferences.getBoolean(getString(R.string.easyprivacy_key), true))
+                    val fanboysAnnoyanceListInt = calculateSettingsInt(currentWebView!!.fanboysAnnoyanceListEnabled, sharedPreferences.getBoolean(getString(R.string.fanboys_annoyance_list_key), true))
+                    val fanboysSocialBlockingListInt = calculateSettingsInt(currentWebView!!.fanboysSocialBlockingListEnabled, sharedPreferences.getBoolean(getString(R.string.fanboys_social_blocking_list_key), true))
+                    val ultraListInt = calculateSettingsInt(currentWebView!!.ultraListEnabled, sharedPreferences.getBoolean(getString(R.string.ultralist_key), true))
+                    val ultraPrivacyInt = calculateSettingsInt(currentWebView!!.ultraPrivacyEnabled, sharedPreferences.getBoolean(getString(R.string.ultraprivacy_key), true))
+                    val blockAllThirdPartyRequestsInt = calculateSettingsInt(currentWebView!!.blockAllThirdPartyRequests, sharedPreferences.getBoolean(getString(R.string.block_all_third_party_requests_key), true))
+                    val swipeToRefreshInt = calculateSettingsInt(currentWebView!!.swipeToRefresh, sharedPreferences.getBoolean(getString(R.string.swipe_to_refresh_key), true))
+                    val wideViewportInt = calculateSettingsInt(currentWebView!!.settings.useWideViewPort, sharedPreferences.getBoolean(getString(R.string.wide_viewport_key), true))
+                    val displayImagesInt = calculateSettingsInt(currentWebView!!.settings.loadsImagesAutomatically, sharedPreferences.getBoolean(getString(R.string.display_webpage_images_key), true))
+
+                    // Initialize the form data int.
+                    var formDataInt = SYSTEM_DEFAULT
+
+                    // Set the form data int, which can be removed once the minimum API >= 26.
+                    @Suppress("DEPRECATION")
+                    if (Build.VERSION.SDK_INT < 26) {
+                        // Get the form data status.
+                        val formDataEnabled = currentWebView!!.settings.saveFormData
+
+                        // Calculate the form data Int.
+                        formDataInt = calculateSettingsInt(formDataEnabled, sharedPreferences.getBoolean(getString(R.string.save_form_data_key), false))
+                    }
+
+                    // Get the current user agent string.
+                    val currentUserAgentString = currentWebView!!.settings.userAgentString
+
+                    // Get the user agent string array position.
+                    val userAgentStringArrayPosition = userAgentDataArrayAdapter.getPosition(currentUserAgentString)
+
+                    // Set the user agent name.
+                    val userAgentName = if ((userAgentStringArrayPosition >= 0) && (defaultUserAgentName == userAgentNamesArray[userAgentStringArrayPosition])) {  // The system default user agent is in use.
+                        getString(R.string.system_default_user_agent)
+                    } else {  // An on-the-fly user agent is being used (or the WebView default user agent is applied).
+                        when (userAgentStringArrayPosition) {
+                            UNRECOGNIZED_USER_AGENT -> { // The user agent is unrecognized.
+                                if (currentUserAgentString == webViewDefaultUserAgent) {  // The WebView default user agent is being used.
+                                    if (defaultUserAgentName == getString(R.string.webview_default)) {  // The WebView default user agent is the system default.
+                                        // Set the user agent name to be the system default.
+                                        getString(R.string.system_default_user_agent)
+                                    } else {  // The WebView default user agent is set as an on-the-fly setting.
+                                        // Set the default user agent name.
+                                        getString(R.string.webview_default)
+                                    }
+                                } else {  // A custom user agent is being used.
+                                    if (defaultUserAgentName == getString(R.string.custom_user_agent_non_translatable)) {  // The system custom user agent is in use.
+                                        // Set the user agent name to be the system default.
+                                        getString(R.string.system_default_user_agent)
+                                    } else {  // An on-the-fly custom user agent is in use.
+                                        // Store the user agent as currently applied.
+                                        currentUserAgentString
+                                    }
+                                }
+                            }
+
+                            else ->  // Store the standard user agent name.
+                                userAgentNamesArray[userAgentStringArrayPosition]
+                        }
+                    }
+
+                    // Get the current text zoom integer.
+                    val textZoomInt = currentWebView!!.settings.textZoom
+
+                    // Set the font size integer.
+                    val fontSizeInt = if (textZoomInt == defaultFontSizeString.toInt())  // The current system default is used, which is encoded as a zoom of `0`.
+                        0
+                    else  // A custom font size is used.
+                        textZoomInt
+
+                    // Get the current WebView dark theme status.
+                    val webViewDarkThemeCurrentlyEnabled = if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING))  // Algorithmic darkening is supported.
+                        WebSettingsCompat.isAlgorithmicDarkeningAllowed(currentWebView!!.settings)
+                    else  // Algorithmic darkening is not supported.
+                        false
+
+                    // Get the default WebView dark theme setting.
+                    val defaultWebViewDarkThemeEnabled = if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {  // Algorithmic darkening is supported.
+                        when (defaultWebViewTheme) {
+                            webViewThemeEntryValuesStringArray[1] ->  // The dark theme is disabled by default.
+                                false
+
+                            webViewThemeEntryValuesStringArray[2] ->  // The dark theme is enabled by default.
+                                true
+
+                            else -> {  // The system default theme is selected.
+                                // Get the current app theme status.
+                                val currentAppThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
+
+                                // Check if the current app theme is dark.
+                                currentAppThemeStatus == Configuration.UI_MODE_NIGHT_YES
+                            }
+                        }
+                    } else {  // Algorithmic darkening is not supported.
+                        false
+                    }
+
+                    // Set the WebView theme int.
+                    val webViewThemeInt = if (webViewDarkThemeCurrentlyEnabled == defaultWebViewDarkThemeEnabled)  // The current WebView theme matches the default.
+                        SYSTEM_DEFAULT
+                    else if (webViewDarkThemeCurrentlyEnabled)  // The current WebView theme is dark and that is not the default.
+                        DARK_THEME
+                    else  // The current WebView theme is light and that is not the default.
+                        LIGHT_THEME
+
                     // Create the domain and store the database ID.
-                    val newDomainDatabaseId = domainsDatabaseHelper!!.addDomain(currentDomain)
+                    val newDomainDatabaseId = domainsDatabaseHelper!!.addDomain(currentDomain, javaScriptInt, cookiesInt, domStorageInt, formDataInt, userAgentName, easyListInt, easyPrivacyInt,
+                                                                                fanboysAnnoyanceListInt, fanboysSocialBlockingListInt, ultraListInt, ultraPrivacyInt, blockAllThirdPartyRequestsInt, fontSizeInt,
+                                                                                swipeToRefreshInt, webViewThemeInt, wideViewportInt, displayImagesInt)
 
                     // Create an intent to launch the domains activity.
                     val domainsIntent = Intent(this, DomainsActivity::class.java)
@@ -2130,6 +2342,9 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
 
                     // Load the previous website in the history.
                     currentWebView!!.goBack()
+
+                    // Update the URL edit text after a delay.
+                    updateUrlEditTextAfterDelay()
                 }
             }
 
@@ -2147,6 +2362,18 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
 
                     // Load the next website in the history.
                     currentWebView!!.goForward()
+
+                    // Update the URL edit text after a delay.
+                    updateUrlEditTextAfterDelay()
+                }
+            }
+
+            R.id.scroll_to_bottom -> {  // Scroll to Bottom.
+                // Check if the WebView is scrolled to the top.
+                if (currentWebView!!.scrollY == 0) {  // The WebView is at the top; scroll to the bottom.  Using a large Y number is more efficient than trying to calculate the exact WebView length.
+                    currentWebView!!.scrollTo(0, 1_000_000_000)
+                } else {  // The WebView is not at the top; scroll to the top.
+                    currentWebView!!.scrollTo(0, 0)
                 }
             }
 
@@ -2319,11 +2546,11 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
                 // Create an intent to launch the about activity.
                 val aboutIntent = Intent(this, AboutActivity::class.java)
 
-                // Create a string array for the blocklist versions.
-                val blocklistVersions = arrayOf(easyList[0][0][0], easyPrivacy[0][0][0], fanboysAnnoyanceList[0][0][0], fanboysSocialList[0][0][0], ultraList[0][0][0], ultraPrivacy!![0][0][0])
+                // Create a string array for the filter list versions.
+                val filterListVersions = arrayOf(easyList[0][0][0], easyPrivacy[0][0][0], fanboysAnnoyanceList[0][0][0], fanboysSocialList[0][0][0], ultraList[0][0][0], ultraPrivacy!![0][0][0])
 
-                // Add the blocklist versions to the intent.
-                aboutIntent.putExtra(AboutActivity.BLOCKLIST_VERSIONS, blocklistVersions)
+                // Add the filter list versions to the intent.
+                aboutIntent.putExtra(FILTERLIST_VERSIONS, filterListVersions)
 
                 // Make it so.
                 startActivity(aboutIntent)
@@ -2337,15 +2564,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
@@ -2370,7 +2588,7 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
                 // Add an open in new tab entry.
                 contextMenu.add(R.string.open_in_new_tab).setOnMenuItemClickListener {
                     // Load the link URL in a new tab and move to it.
-                    addNewTab(linkUrl, true)
+                    addNewTab(linkUrl, adjacent = true, moveToTab = true)
 
                     // Consume the event.
                     true
@@ -2379,7 +2597,7 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
                 // Add an open in background entry.
                 contextMenu.add(R.string.open_in_background).setOnMenuItemClickListener {
                     // Load the link URL in a new tab but do not move to it.
-                    addNewTab(linkUrl, false)
+                    addNewTab(linkUrl, adjacent = true, moveToTab = false)
 
                     // Consume the event.
                     true
@@ -2427,6 +2645,27 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
                     true
                 }
 
+                // Add a Share URL entry.
+                contextMenu.add(R.string.share_url).setOnMenuItemClickListener {
+                    // Create the share intent.
+                    val shareUrlIntent = Intent(Intent.ACTION_SEND)
+
+                    // Add the URL to the intent.
+                    shareUrlIntent.putExtra(Intent.EXTRA_TEXT, linkUrl)
+
+                    // Set the MIME type.
+                    shareUrlIntent.type = "text/plain"
+
+                    // Set the intent to open in a new task.
+                    shareUrlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+
+                    //Make it so.
+                    startActivity(Intent.createChooser(shareUrlIntent, getString(R.string.share_url)))
+
+                    // Consume the event.
+                    true
+                }
+
                 // Add an empty cancel entry, which by default closes the context menu.
                 contextMenu.add(R.string.cancel)
             }
@@ -2445,7 +2684,7 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
                 // Add an open in new tab entry.
                 contextMenu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener {
                     // Load the image in a new tab.
-                    addNewTab(imageUrl, true)
+                    addNewTab(imageUrl, adjacent = true, moveToTab = true)
 
                     // Consume the event.
                     true
@@ -2503,6 +2742,27 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
                     true
                 }
 
+                // Add a Share URL entry.
+                contextMenu.add(R.string.share_url).setOnMenuItemClickListener {
+                    // Create the share intent.
+                    val shareUrlIntent = Intent(Intent.ACTION_SEND)
+
+                    // Add the URL to the intent.
+                    shareUrlIntent.putExtra(Intent.EXTRA_TEXT, imageUrl)
+
+                    // Set the MIME type.
+                    shareUrlIntent.type = "text/plain"
+
+                    // Set the intent to open in a new task.
+                    shareUrlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+
+                    //Make it so.
+                    startActivity(Intent.createChooser(shareUrlIntent, getString(R.string.share_url)))
+
+                    // Consume the event.
+                    true
+                }
+
                 // Add an empty cancel entry, which by default closes the context menu.
                 contextMenu.add(R.string.cancel)
             }
@@ -2530,7 +2790,7 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
                 // Add an open in new tab entry.
                 contextMenu.add(R.string.open_in_new_tab).setOnMenuItemClickListener {
                     // Load the link URL in a new tab and move to it.
-                    addNewTab(linkUrl, true)
+                    addNewTab(linkUrl, adjacent = true, moveToTab = true)
 
                     // Consume the event.
                     true
@@ -2539,7 +2799,7 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
                 // Add an open in background entry.
                 contextMenu.add(R.string.open_in_background).setOnMenuItemClickListener {
                     // Lod the link URL in a new tab but do not move to it.
-                    addNewTab(linkUrl, false)
+                    addNewTab(linkUrl, adjacent = true, moveToTab = false)
 
                     // Consume the event.
                     true
@@ -2548,7 +2808,7 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
                 // Add an open image in new tab entry.
                 contextMenu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener {
                     // Load the image in a new tab and move to it.
-                    addNewTab(imageUrl, true)
+                    addNewTab(imageUrl, adjacent = true, moveToTab = true)
 
                     // Consume the event.
                     true
@@ -2593,6 +2853,27 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
                     true
                 }
 
+                // Add a Share Image entry.
+                contextMenu.add(R.string.share_image).setOnMenuItemClickListener {
+                    // Create the share intent.
+                    val shareUrlIntent = Intent(Intent.ACTION_SEND)
+
+                    // Add the URL to the intent.
+                    shareUrlIntent.putExtra(Intent.EXTRA_TEXT, imageUrl)
+
+                    // Set the MIME type.
+                    shareUrlIntent.type = "text/plain"
+
+                    // Set the intent to open in a new task.
+                    shareUrlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+
+                    //Make it so.
+                    startActivity(Intent.createChooser(shareUrlIntent, getString(R.string.share_url)))
+
+                    // Consume the event.
+                    true
+                }
+
                 // Add a copy URL entry.
                 contextMenu.add(R.string.copy_url).setOnMenuItemClickListener {
                     // Save the link URL in a clip data.
@@ -2617,6 +2898,27 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
                     true
                 }
 
+                // Add a Share URL entry.
+                contextMenu.add(R.string.share_url).setOnMenuItemClickListener {
+                    // Create the share intent.
+                    val shareUrlIntent = Intent(Intent.ACTION_SEND)
+
+                    // Add the URL to the intent.
+                    shareUrlIntent.putExtra(Intent.EXTRA_TEXT, linkUrl)
+
+                    // Set the MIME type.
+                    shareUrlIntent.type = "text/plain"
+
+                    // Set the intent to open in a new task.
+                    shareUrlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+
+                    //Make it so.
+                    startActivity(Intent.createChooser(shareUrlIntent, getString(R.string.share_url)))
+
+                    // Consume the event.
+                    true
+                }
+
                 // Add an empty cancel entry, which by default closes the context menu.
                 contextMenu.add(R.string.cancel)
             }
@@ -2669,2063 +2971,1767 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
         }
     }
 
-    override fun onCreateBookmark(dialogFragment: DialogFragment, favoriteIconBitmap: Bitmap) {
-        // Get the dialog.
-        val dialog = dialogFragment.dialog!!
+    // 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(urlString = "", adjacent = true, moveToTab = true)
+    }
 
-        // 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)
+    private fun addNewTab(urlString: String, adjacent: Boolean, 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()
 
-        // Extract the strings from the edit texts.
-        val bookmarkNameString = createBookmarkNameEditText.text.toString()
-        val bookmarkUrlString = createBookmarkUrlEditText.text.toString()
+        // Get the new tab position.
+        val newTabPosition = if (adjacent)  // The new tab position is immediately to the right of the current tab position.
+            tabLayout.selectedTabPosition + 1
+        else  // The new tab position is at the end.  The tab positions are 0 indexed, so the new page number will match the current count.
+            tabLayout.tabCount
 
-        // Create a favorite icon byte array output stream.
-        val favoriteIconByteArrayOutputStream = ByteArrayOutputStream()
+        // Add the new WebView page.
+        webViewStateAdapter!!.addPage(newTabPosition, urlString)
 
-        // 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)
+        // Create a new tab.
+        val newTab = tabLayout.newTab()
 
-        // Convert the favorite icon byte array stream to a byte array.
-        val favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray()
+        // Set a custom view on the new tab.
+        newTab.setCustomView(R.layout.tab_custom_view)
 
-        // Display the new bookmark below the current items in the (0 indexed) list.
-        val newBookmarkDisplayOrder = bookmarksListView.count
+        // Add the new tab.
+        tabLayout.addTab(newTab, newTabPosition, moveToTab)
 
-        // Create the bookmark.
-        bookmarksDatabaseHelper!!.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray)
+        // Select the new tab if it is the first one.  For some odd reason, Android doesn't select the first tab if it is the only one, which causes problems with the new tab position logic above.
+        if (newTabPosition == 0)
+            tabLayout.selectTab(newTab)
 
-        // Update the bookmarks cursor with the current contents of this folder.
-        bookmarksCursor = bookmarksDatabaseHelper!!.getBookmarksByDisplayOrder(currentBookmarksFolder)
+        // Scroll to the new tab position if moving to the new tab.
+        if (moveToTab)
+            tabLayout.post {
+                tabLayout.setScrollPosition(newTabPosition, 0F, false, false)
+            }
 
-        // 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!!
-
-        // 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)
+    private fun applyAppSettings() {
+        // Store the default preferences used in `applyDomainSettings()`.  These are done here so that expensive preference requests are not done each time a domain is loaded.
+        defaultJavaScript = sharedPreferences.getBoolean(getString(R.string.javascript_key), false)
+        defaultCookies = sharedPreferences.getBoolean(getString(R.string.cookies_key), false)
+        defaultDomStorage = sharedPreferences.getBoolean(getString(R.string.dom_storage_key), false)
+        defaultFormData = sharedPreferences.getBoolean(getString(R.string.save_form_data_key), false)  // Form data can be removed once the minimum API >= 26.
+        defaultEasyList = sharedPreferences.getBoolean(getString(R.string.easylist_key), true)
+        defaultEasyPrivacy = sharedPreferences.getBoolean(getString(R.string.easyprivacy_key), true)
+        defaultFanboysAnnoyanceList = sharedPreferences.getBoolean(getString(R.string.fanboys_annoyance_list_key), true)
+        defaultFanboysSocialBlockingList = sharedPreferences.getBoolean(getString(R.string.fanboys_social_blocking_list_key), true)
+        defaultUltraList = sharedPreferences.getBoolean(getString(R.string.ultralist_key), true)
+        defaultUltraPrivacy = sharedPreferences.getBoolean(getString(R.string.ultraprivacy_key), true)
+        defaultBlockAllThirdPartyRequests = sharedPreferences.getBoolean(getString(R.string.block_all_third_party_requests_key), false)
+        defaultFontSizeString = sharedPreferences.getString(getString(R.string.font_size_key), getString(R.string.font_size_default_value))!!
+        defaultUserAgentName = sharedPreferences.getString(getString(R.string.user_agent_key), getString(R.string.user_agent_default_value))!!
+        defaultSwipeToRefresh = sharedPreferences.getBoolean(getString(R.string.swipe_to_refresh_key), true)
+        defaultWebViewTheme = sharedPreferences.getString(getString(R.string.webview_theme_key), getString(R.string.webview_theme_default_value))!!
+        defaultWideViewport = sharedPreferences.getBoolean(getString(R.string.wide_viewport_key), true)
+        defaultDisplayWebpageImages = sharedPreferences.getBoolean(getString(R.string.display_webpage_images_key), true)
+
+        // Get the WebView theme entry values string array.  This is done here so that expensive resource requests are not made each time a domain is loaded.
+        webViewThemeEntryValuesStringArray = resources.getStringArray(R.array.webview_theme_entry_values)
+
+        // Get the user agent string arrays.  These are done here so that expensive resource requests are not made each time a domain is loaded.
+        userAgentDataArray = resources.getStringArray(R.array.user_agent_data)
+        userAgentNamesArray = resources.getStringArray(R.array.user_agent_names)
+
+        // Get the user agent array adapters.  These are done here so that expensive resource requests are not made each time a domain is loaded.
+        userAgentDataArrayAdapter = ArrayAdapter.createFromResource(this, R.array.user_agent_data, R.layout.spinner_item)
+        userAgentNamesArrayAdapter = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item)
 
-        // Get new folder name string.
-        val folderNameString = folderNameEditText.text.toString()
+        // 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)
 
-        // 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
-
-            // Convert the folder icon drawable to a bitmap drawable.
-            val folderIconBitmapDrawable = folderIconDrawable as BitmapDrawable
+        // Apply the saved proxy mode if the app has been restarted.
+        if (savedProxyMode != null) {
+            // Apply the saved proxy mode.
+            proxyMode = savedProxyMode!!
 
-            // 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
+            // Reset the saved proxy mode.
+            savedProxyMode = null
         }
 
-        // Create a folder icon byte array output stream.
-        val folderIconByteArrayOutputStream = ByteArrayOutputStream()
+        // Get the search string.
+        val searchString = sharedPreferences.getString(getString(R.string.search_key), getString(R.string.search_default_value))!!
 
-        // 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)
+        // 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 byte array stream to a byte array.
-        val folderIconByteArray = folderIconByteArrayOutputStream.toByteArray()
+        // Apply the proxy.
+        applyProxy(false)
 
-        // 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()
+        // 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)
 
-            // Move the bookmark down one slot.
-            bookmarksDatabaseHelper!!.updateDisplayOrder(databaseId, i + 1)
-        }
+                // 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)
 
-        // Create the folder, which will be placed at the top of the list view.
-        bookmarksDatabaseHelper!!.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray)
+                    // 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
 
-        // Update the bookmarks cursor with the current contents of this folder.
-        bookmarksCursor = bookmarksDatabaseHelper!!.getBookmarksByDisplayOrder(currentBookmarksFolder)
+            // 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
 
-        // Update the list view.
-        bookmarksCursorAdapter.changeCursor(bookmarksCursor)
+                // Expand the app bar if it is currently collapsed.
+                appBarLayout.setExpanded(true)
+            }
 
-        // Scroll to the new folder.
-        bookmarksListView.setSelection(0)
-    }
+            // Set the app bar scrolling for each WebView.
+            for (i in 0 until webViewStateAdapter!!.itemCount) {
+                // Get the WebView tab fragment.
+                val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
 
-    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 <= ' ' }
+                // Get the fragment view.
+                val fragmentView = webViewTabFragment.view
 
-        // 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()
+    // `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!!
 
-        // Make it so.
-        loadUrl(currentWebView!!, urlString)
-    }
+        // Parse the URL into a URI.
+        val uri = Uri.parse(url)
 
-    private fun loadUrl(nestedScrollWebView: NestedScrollWebView, url: String) {
-        // Sanitize the URL.
-        val urlString = sanitizeUrl(url)
+        // Extract the domain from the URI.
+        var newHostName = uri.host
 
-        // Apply the domain settings and load the URL.
-        applyDomainSettings(nestedScrollWebView, urlString, resetTab = true, reloadWebsite = false, loadUrl = true)
-    }
+        // Strings don't like to be null.
+        if (newHostName == null)
+            newHostName = ""
 
-    // 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)
-    }
+        // 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 == "")) {  // A new domain is being loaded.
+            // Set the new host name as the current domain name.
+            nestedScrollWebView.currentDomainName = newHostName
 
-    // 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)
-    }
+            // Reset the ignoring of pinned domain information.
+            nestedScrollWebView.ignorePinnedDomainInformation = false
 
-    // 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
+            // Clear any pinned SSL certificate or IP addresses.
+            nestedScrollWebView.clearPinnedSslCertificate()
+            nestedScrollWebView.pinnedIpAddresses = ""
 
-        // Clear the highlighted phrases if the WebView is not null.
-        currentWebView?.clearMatches()
+            // Reset the favorite icon if specified.
+            if (resetTab) {
+                // Initialize the favorite icon.
+                nestedScrollWebView.initializeFavoriteIcon()
 
-        // Hide the find on page linear layout.
-        findOnPageLinearLayout.visibility = View.GONE
+                // Get the current page position.
+                val currentPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
 
-        // Show the toolbar.
-        toolbar.visibility = View.VISIBLE
+                // Get the corresponding tab.
+                val tab = tabLayout.getTabAt(currentPagePosition)
 
-        // Get a handle for the input method manager.
-        val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
+                // 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!!
 
-        // Hide the keyboard.
-        inputMethodManager.hideSoftInputFromWindow(toolbar.windowToken, 0)
-    }
+                    // Get the tab views.
+                    val tabFavoriteIconImageView = tabCustomView.findViewById<ImageView>(R.id.favorite_icon_imageview)
+                    val tabTitleTextView = tabCustomView.findViewById<TextView>(R.id.title_textview)
 
-    override fun onApplyNewFontSize(dialogFragment: DialogFragment) {
-        // Get the dialog.
-        val dialog = dialogFragment.dialog!!
+                    // Store the current values in case they need to be restored.
+                    nestedScrollWebView.previousFavoriteIconDrawable = tabFavoriteIconImageView.drawable
+                    nestedScrollWebView.previousWebpageTitle = tabTitleTextView.text.toString()
 
-        // Get a handle for the font size edit text.
-        val fontSizeEditText = dialog.findViewById<EditText>(R.id.font_size_edittext)
+                    // Set the default favorite icon as the favorite icon for this tab.
+                    tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nestedScrollWebView.getFavoriteIcon(), 64, 64, true))
 
-        // Initialize the new font size variable with the current font size.
-        var newFontSize = currentWebView!!.settings.textZoom
+                    // Set the loading title text.
+                    tabTitleTextView.setText(R.string.loading)
+                }
+            }
 
-        // 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.
-        }
-
-        // Apply the new font size.
-        currentWebView!!.settings.textZoom = newFontSize
-    }
+            // Initialize the domain name in database variable.
+            var domainNameInDatabase: String? = null
 
-    override fun onOpen(dialogFragment: DialogFragment) {
-        // Get the dialog.
-        val dialog = dialogFragment.dialog!!
+            // 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 handles for the views.
-        val fileNameEditText = dialog.findViewById<EditText>(R.id.file_name_edittext)
-        val mhtCheckBox = dialog.findViewById<CheckBox>(R.id.mht_checkbox)
+                // 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
+            }
 
-        // Get the file path string.
-        val openFilePath = fileNameEditText.text.toString()
+            // 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
 
-        // Apply the domain settings.  This resets the favorite icon and removes any domain settings.
-        applyDomainSettings(currentWebView!!, openFilePath, resetTab = true, reloadWebsite = false, loadUrl = false)
+                    // Store the applied domain names as it appears in the database.
+                    domainNameInDatabase = "*.$newHostName"
+                }
 
-        // 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))
+                // Strip out the lowest subdomain of of the host name.
+                newHostName = newHostName.substring(newHostName.indexOf(".") + 1)
+            }
 
-                // Create a temporary MHT file.
-                val temporaryMhtFile = File.createTempFile(TEMPORARY_MHT_FILE, ".mht", cacheDir)
+            // Apply either the domain settings or the default settings.
+            if (nestedScrollWebView.domainSettingsApplied) {  // The url has custom domain settings.
+                // Get a cursor for the current host.
+                val currentDomainSettingsCursor = domainsDatabaseHelper!!.getCursorForDomainName(domainNameInDatabase!!)
 
-                // Get a file output stream for the temporary MHT file.
-                val temporaryMhtFileOutputStream = FileOutputStream(temporaryMhtFile)
+                // Move to the first position.
+                currentDomainSettingsCursor.moveToFirst()
 
-                // Create a transfer byte array.
-                val transferByteArray = ByteArray(1024)
+                // Get the settings from the cursor.
+                nestedScrollWebView.domainSettingsDatabaseId = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ID))
+                val javaScriptInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_JAVASCRIPT))
+                val cookiesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(COOKIES))
+                val domStorageInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_DOM_STORAGE))
+                val formDataInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_FORM_DATA))  // Form data can be removed once the minimum API >= 26.
+                val easyListInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_EASYLIST))
+                val easyPrivacyInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_EASYPRIVACY))
+                val fanboysAnnoyanceListInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_FANBOYS_ANNOYANCE_LIST))
+                val fanboysSocialBlockingListInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST))
+                val ultraListInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.ULTRALIST))
+                val ultraPrivacyInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_ULTRAPRIVACY))
+                val blockAllThirdPartyRequestsInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.BLOCK_ALL_THIRD_PARTY_REQUESTS))
+                val userAgentName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.USER_AGENT))
+                val fontSize = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(FONT_SIZE))
+                val swipeToRefreshInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(SWIPE_TO_REFRESH))
+                val webViewThemeInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(WEBVIEW_THEME))
+                val wideViewportInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(WIDE_VIEWPORT))
+                val displayWebpageImagesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DISPLAY_IMAGES))
+                val pinnedSslCertificate = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(PINNED_SSL_CERTIFICATE)) == 1)
+                val pinnedSslIssuedToCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_TO_COMMON_NAME))
+                val pinnedSslIssuedToOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_TO_ORGANIZATION))
+                val pinnedSslIssuedToUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_TO_ORGANIZATIONAL_UNIT))
+                val pinnedSslIssuedByCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_BY_COMMON_NAME))
+                val pinnedSslIssuedByOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_BY_ORGANIZATION))
+                val pinnedSslIssuedByUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_BY_ORGANIZATIONAL_UNIT))
+                val pinnedSslStartDate = Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.SSL_START_DATE)))
+                val pinnedSslEndDate = Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.SSL_END_DATE)))
+                val pinnedIpAddresses = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(PINNED_IP_ADDRESSES)) == 1)
+                val pinnedHostIpAddresses = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(IP_ADDRESSES))
 
-                // Create an integer to track the number of bytes read.
-                var bytesRead: Int
+                // Close the current host domain settings cursor.
+                currentDomainSettingsCursor.close()
 
-                // 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)
+                // Set the JavaScript status.
+                when (javaScriptInt) {
+                    SYSTEM_DEFAULT -> nestedScrollWebView.settings.javaScriptEnabled = defaultJavaScript
+                    ENABLED -> nestedScrollWebView.settings.javaScriptEnabled = true
+                    DISABLED -> nestedScrollWebView.settings.javaScriptEnabled = false
+                }
 
-                // Flush the temporary MHT file output stream.
-                temporaryMhtFileOutputStream.flush()
+                // Store the cookies status.
+                when (cookiesInt) {
+                    SYSTEM_DEFAULT -> nestedScrollWebView.acceptCookies = defaultCookies
+                    ENABLED -> nestedScrollWebView.acceptCookies = true
+                    DISABLED -> nestedScrollWebView.acceptCookies = false
+                }
 
-                // Close the streams.
-                temporaryMhtFileOutputStream.close()
-                mhtFileInputStream.close()
+                // Apply the cookies status.
+                cookieManager.setAcceptCookie(nestedScrollWebView.acceptCookies)
 
-                // 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)
-        }
-    }
+                // Set the DOM storage status.
+                when (domStorageInt) {
+                    SYSTEM_DEFAULT -> nestedScrollWebView.settings.domStorageEnabled = defaultDomStorage
+                    ENABLED -> nestedScrollWebView.settings.domStorageEnabled = true
+                    DISABLED -> nestedScrollWebView.settings.domStorageEnabled = false
+                }
 
-    private fun downloadUrlWithExternalApp(url: String) {
-        // Create a download intent.  Not specifying the action type will display the maximum number of options.
-        val downloadIntent = Intent()
+                // Apply the form data setting if the API < 26.
+                @Suppress("DEPRECATION")
+                if (Build.VERSION.SDK_INT < 26) {
+                    // Set the form data status.
+                    when (formDataInt) {
+                        SYSTEM_DEFAULT -> nestedScrollWebView.settings.saveFormData = defaultFormData
+                        ENABLED -> nestedScrollWebView.settings.saveFormData = true
+                        DISABLED -> nestedScrollWebView.settings.saveFormData = false
+                    }
+                }
 
-        // Set the URI and the mime type.
-        downloadIntent.setDataAndType(Uri.parse(url), "text/html")
+                // Set the EasyList status.
+                when (easyListInt) {
+                    SYSTEM_DEFAULT -> nestedScrollWebView.easyListEnabled = defaultEasyList
+                    ENABLED -> nestedScrollWebView.easyListEnabled = true
+                    DISABLED -> nestedScrollWebView.easyListEnabled = false
+                }
 
-        // Flag the intent to open in a new task.
-        downloadIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
+                // Set the EasyPrivacy status.
+                when (easyPrivacyInt) {
+                    SYSTEM_DEFAULT -> nestedScrollWebView.easyPrivacyEnabled = defaultEasyPrivacy
+                    ENABLED -> nestedScrollWebView.easyPrivacyEnabled = true
+                    DISABLED -> nestedScrollWebView.easyPrivacyEnabled = false
+                }
 
-        // Show the chooser.
-        startActivity(Intent.createChooser(downloadIntent, getString(R.string.download_with_external_app)))
-    }
+                // Set the Fanboy's Annoyance List status.
+                when (fanboysAnnoyanceListInt) {
+                    SYSTEM_DEFAULT -> nestedScrollWebView.fanboysAnnoyanceListEnabled = defaultFanboysAnnoyanceList
+                    ENABLED -> nestedScrollWebView.fanboysAnnoyanceListEnabled = true
+                    DISABLED -> nestedScrollWebView.fanboysAnnoyanceListEnabled = false
+                }
 
-    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!!
+                // Set the Fanboy's Social Blocking List status.
+                when (fanboysSocialBlockingListInt) {
+                    SYSTEM_DEFAULT -> nestedScrollWebView.fanboysSocialBlockingListEnabled = defaultFanboysSocialBlockingList
+                    ENABLED -> nestedScrollWebView.fanboysSocialBlockingListEnabled = true
+                    DISABLED -> nestedScrollWebView.fanboysSocialBlockingListEnabled = false
+                }
 
-            // Get a handle for the dialog URL edit text.
-            val dialogUrlEditText = dialog.findViewById<EditText>(R.id.url_edittext)
+                // Set the UltraList status.
+                when (ultraListInt) {
+                    SYSTEM_DEFAULT -> nestedScrollWebView.ultraListEnabled = defaultUltraList
+                    ENABLED -> nestedScrollWebView.ultraListEnabled = true
+                    DISABLED -> nestedScrollWebView.ultraListEnabled = false
+                }
 
-            // Get the URL from the edit text, which may have been modified.
-            dialogUrlEditText.text.toString()
-        }
+                // Set the UltraPrivacy status.
+                when (ultraPrivacyInt) {
+                    SYSTEM_DEFAULT -> nestedScrollWebView.ultraPrivacyEnabled = defaultUltraPrivacy
+                    ENABLED -> nestedScrollWebView.ultraPrivacyEnabled = true
+                    DISABLED -> nestedScrollWebView.ultraPrivacyEnabled = false
+                }
 
-        // Open the file picker.
-        saveUrlActivityResultLauncher.launch(fileNameString)
-    }
+                // Set the block all third-party requests status.
+                when (blockAllThirdPartyRequestsInt) {
+                    SYSTEM_DEFAULT -> nestedScrollWebView.blockAllThirdPartyRequests = defaultBlockAllThirdPartyRequests
+                    ENABLED -> nestedScrollWebView.blockAllThirdPartyRequests = true
+                    DISABLED -> nestedScrollWebView.blockAllThirdPartyRequests = 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)
+                // 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 = userAgentNamesArrayAdapter.getPosition(defaultUserAgentName)) {
+                        UNRECOGNIZED_USER_AGENT ->  // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
+                            nestedScrollWebView.settings.userAgentString = defaultUserAgentName
 
-        // 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))
+                        SETTINGS_WEBVIEW_DEFAULT_USER_AGENT ->  // Set the user agent to `""`, which uses the default value.
+                            nestedScrollWebView.settings.userAgentString = ""
 
-        // 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)
+                        SETTINGS_CUSTOM_USER_AGENT ->  // Set the default custom user agent.
+                            nestedScrollWebView.settings.userAgentString = sharedPreferences.getString(getString(R.string.custom_user_agent_key), getString(R.string.custom_user_agent_default_value))
 
-                // Reapply the syntax highlighting.
-                UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
-            }
-        }
+                        else ->  // Get the user agent string from the user agent data array
+                            nestedScrollWebView.settings.userAgentString = userAgentDataArray[defaultUserAgentArrayPosition]
+                    }
+                } else {  // Set the user agent according to the stored name.
+                    // Set the user agent.
+                    when (val userAgentArrayPosition = userAgentNamesArrayAdapter.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
 
-        // 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()
+                        // Set the user agent to `""`, which uses the default value.
+                        SETTINGS_WEBVIEW_DEFAULT_USER_AGENT ->
+                            nestedScrollWebView.settings.userAgentString = ""
 
-                // Consume the event.
-                return@setOnKeyListener true
-            } else {  // Some other key was pressed.
-                // Do not consume the event.
-                return@setOnKeyListener false
-            }
-        }
+                        // Get the user agent string from the user agent data array.
+                        else ->
+                            nestedScrollWebView.settings.userAgentString = userAgentDataArray[userAgentArrayPosition]
+                    }
+                }
 
-        // 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 swipe to refresh.
+                when (swipeToRefreshInt) {
+                    SYSTEM_DEFAULT -> {
+                        // Store the swipe to refresh status in the nested scroll WebView.
+                        nestedScrollWebView.swipeToRefresh = defaultSwipeToRefresh
 
-                    // Get a list of the current fragments.
-                    val fragmentList = supportFragmentManager.fragments
+                        // 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
+                        }
+                    }
 
-                    // 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
+                    ENABLED -> {
+                        // Store the swipe to refresh status in the nested scroll WebView.
+                        nestedScrollWebView.swipeToRefresh = true
 
-                        // 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()
+                        // 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)
                         }
                     }
 
-                    // 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)
+                    DISABLED -> {
+                        // Store the swipe to refresh status in the nested scroll WebView.
+                        nestedScrollWebView.swipeToRefresh = false
 
-                        // Get the fragment view.
-                        val fragmentView = webViewTabFragment.view
+                        // Disable swipe to refresh.
+                        swipeRefreshLayout.isEnabled = false
+                    }
+                }
 
-                        // 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 WebView theme if algorithmic darkening is supported.
+                if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {
+                    // Set the WebView theme.
+                    when (webViewThemeInt) {
+                        SYSTEM_DEFAULT ->  // Set the WebView theme.
+                            when (defaultWebViewTheme) {
+                                webViewThemeEntryValuesStringArray[1] ->  // The light theme is selected.  Turn off algorithmic darkening.
+                                    WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
 
-                            // Get the waiting for proxy URL string.
-                            val waitingForProxyUrlString = nestedScrollWebView.waitingForProxyUrlString
+                                webViewThemeEntryValuesStringArray[2] ->  // The dark theme is selected.  Turn on algorithmic darkening.
+                                    WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
 
-                            // Load the pending URL if it exists.
-                            if (waitingForProxyUrlString.isNotEmpty()) {  // A URL is waiting to be loaded.
-                                // Load the URL.
-                                loadUrl(nestedScrollWebView, waitingForProxyUrlString)
+                                else -> {  // The system default theme is selected.
+                                    // Get the current system theme status.
+                                    val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
 
-                                // 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 algorithmic darkening according to the current system theme status.
+                                    WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, currentThemeStatus == Configuration.UI_MODE_NIGHT_YES)
+                                }
                             }
-                        }
-                    }
-                }
-            }
-        }
-
-        // 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) {}
+                        LIGHT_THEME ->  // Turn off algorithmic darkening.
+                            WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
 
-            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)!!
-
-                        // Select the tab.
-                        tab.select()
+                        DARK_THEME ->  // Turn on algorithmic darkening.
+                            WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
                     }
                 }
-            }
 
-            override fun onPageScrollStateChanged(state: Int) {}
-        })
+                // Set the wide viewport status.
+                when (wideViewportInt) {
+                    SYSTEM_DEFAULT -> nestedScrollWebView.settings.useWideViewPort = defaultWideViewport
+                    ENABLED -> nestedScrollWebView.settings.useWideViewPort = true
+                    DISABLED -> nestedScrollWebView.settings.useWideViewPort = 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
-            }
+                // Set the display webpage images status.
+                when (displayWebpageImagesInt) {
+                    SYSTEM_DEFAULT -> nestedScrollWebView.settings.loadsImagesAutomatically = defaultDisplayWebpageImages
+                    ENABLED -> nestedScrollWebView.settings.loadsImagesAutomatically = true
+                    DISABLED -> nestedScrollWebView.settings.loadsImagesAutomatically = false
+                }
 
-            override fun onTabUnselected(tab: TabLayout.Tab) {}
+                // If there is a pinned SSL certificate, store it in the WebView.
+                if (pinnedSslCertificate)
+                    nestedScrollWebView.setPinnedSslCertificate(pinnedSslIssuedToCName, pinnedSslIssuedToOName, pinnedSslIssuedToUName, pinnedSslIssuedByCName, pinnedSslIssuedByOName, pinnedSslIssuedByUName,
+                        pinnedSslStartDate, pinnedSslEndDate)
 
-            override fun onTabReselected(tab: TabLayout.Tab) {
-                // Instantiate the View SSL Certificate dialog.
-                val viewSslCertificateDialogFragment: DialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView!!.webViewFragmentId, currentWebView!!.getFavoriteIcon())
+                // If there is a pinned IP address, store it in the WebView.
+                if (pinnedIpAddresses)
+                    nestedScrollWebView.pinnedIpAddresses = pinnedHostIpAddresses
 
-                // Display the View SSL Certificate dialog.
-                viewSslCertificateDialogFragment.show(supportFragmentManager, getString(R.string.view_ssl_certificate))
-            }
-        })
+                // 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 = defaultJavaScript
+                nestedScrollWebView.acceptCookies = defaultCookies
+                nestedScrollWebView.settings.domStorageEnabled = defaultDomStorage
+                nestedScrollWebView.easyListEnabled = defaultEasyList
+                nestedScrollWebView.easyPrivacyEnabled = defaultEasyPrivacy
+                nestedScrollWebView.fanboysAnnoyanceListEnabled = defaultFanboysAnnoyanceList
+                nestedScrollWebView.fanboysSocialBlockingListEnabled = defaultFanboysSocialBlockingList
+                nestedScrollWebView.ultraListEnabled = defaultUltraList
+                nestedScrollWebView.ultraPrivacyEnabled = defaultUltraPrivacy
+                nestedScrollWebView.blockAllThirdPartyRequests = defaultBlockAllThirdPartyRequests
 
-        // 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 }
+                // Apply the default cookie setting.
+                cookieManager.setAcceptCookie(nestedScrollWebView.acceptCookies)
 
-        // 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()
+                // Apply the form data setting if the API < 26.
+                if (Build.VERSION.SDK_INT < 26)
+                    @Suppress("DEPRECATION")
+                    nestedScrollWebView.settings.saveFormData = defaultFormData
 
-            // Create a favorite icon byte array output stream.
-            val currentFavoriteIconByteArrayOutputStream = ByteArrayOutputStream()
+                // 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
+                }
 
-            // 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)
+                // Store the swipe to refresh status in the nested scroll WebView.
+                nestedScrollWebView.swipeToRefresh = defaultSwipeToRefresh
 
-            // Convert the favorite icon byte array stream to a byte array.
-            val currentFavoriteIconByteArray = currentFavoriteIconByteArrayOutputStream.toByteArray()
+                // 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
+                }
 
-            // Create an intent to launch the bookmarks activity.
-            val bookmarksIntent = Intent(applicationContext, BookmarksActivity::class.java)
+                // Reset the domain settings database ID.
+                nestedScrollWebView.domainSettingsDatabaseId = -1
 
-            // 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)
+                // Set the user agent.
+                when (val userAgentArrayPosition = userAgentNamesArrayAdapter.getPosition(defaultUserAgentName)) {
+                    UNRECOGNIZED_USER_AGENT ->  // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
+                        nestedScrollWebView.settings.userAgentString = defaultUserAgentName
 
-            // Make it so.
-            startActivity(bookmarksIntent)
-        }
+                    SETTINGS_WEBVIEW_DEFAULT_USER_AGENT ->  // Set the user agent to `""`, which uses the default value.
+                        nestedScrollWebView.settings.userAgentString = ""
 
-        // 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())
+                    SETTINGS_CUSTOM_USER_AGENT ->  // Set the default custom user agent.
+                        nestedScrollWebView.settings.userAgentString = sharedPreferences.getString(getString(R.string.custom_user_agent_key), getString(R.string.custom_user_agent_default_value))
 
-            // Show the create bookmark folder dialog.
-            createBookmarkFolderDialog.show(supportFragmentManager, getString(R.string.create_folder))
-        }
+                    else ->  // Get the user agent string from the user agent data array
+                        nestedScrollWebView.settings.userAgentString = userAgentDataArray[userAgentArrayPosition]
+                }
 
-        // 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())
+                // Set the WebView theme if algorithmic darkening is supported.
+                if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {
+                    // Set the WebView theme.
+                    when (defaultWebViewTheme) {
+                        webViewThemeEntryValuesStringArray[1] ->  // The light theme is selected.  Turn off algorithmic darkening.
+                            WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
 
-            // Display the create bookmark dialog.
-            createBookmarkDialog.show(supportFragmentManager, getString(R.string.create_bookmark))
-        }
+                        webViewThemeEntryValuesStringArray[2] ->  // The dark theme is selected.  Turn on algorithmic darkening.
+                            WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
 
-        // 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) {}
+                        else -> {  // The system default theme is selected.  Get the current system theme status.
+                            // Get the current theme status.
+                            val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
 
-            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
+                            // Set the algorithmic darkening according to the current system theme status.
+                            WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, currentThemeStatus == Configuration.UI_MODE_NIGHT_YES)
+                        }
+                    }
+                }
 
-            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 viewport.
+                nestedScrollWebView.settings.useWideViewPort = defaultWideViewport
 
-        // 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)
+                // Set the loading of webpage images.
+                nestedScrollWebView.settings.loadsImagesAutomatically = defaultDisplayWebpageImages
 
-                // Consume the event.
-                return@setOnKeyListener true
-            } else {  // A different key was pressed.
-                // Do not consume the event.
-                return@setOnKeyListener false
+                // Set a transparent background on the URL relative layout.
+                urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.color.transparent)
             }
-        }
 
-        // Implement swipe to refresh.
-        swipeRefreshLayout.setOnRefreshListener {
-            // Reload the website.
-            currentWebView!!.reload()
+            // Update the privacy icons.
+            updatePrivacyIcons(true)
         }
 
-        // Store the default progress view offsets.
-        defaultProgressViewStartOffset = swipeRefreshLayout.progressViewStartOffset
-        defaultProgressViewEndOffset = swipeRefreshLayout.progressViewEndOffset
-
-        // Set the refresh color scheme according to the theme.
-        swipeRefreshLayout.setColorSchemeResources(R.color.blue_text)
-
-        // Initialize a color background typed value.
-        val colorBackgroundTypedValue = TypedValue()
-
-        // Get the color background from the theme.
-        theme.resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true)
-
-        // Get the color background int from the typed value.
-        val colorBackgroundInt = colorBackgroundTypedValue.data
-
-        // Set the swipe refresh background color.
-        swipeRefreshLayout.setProgressBackgroundColorSchemeColor(colorBackgroundInt)
+        // Reload the website if returning from the Domains activity.
+        if (reloadWebsite)
+            nestedScrollWebView.reload()
 
-        // 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))
+        // Disable the wide viewport if the source is being viewed.
+        if (url.startsWith("view-source:"))
+            nestedScrollWebView.settings.useWideViewPort = false
 
-        // 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()
-        }
-
-        // 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()
+            ProxyHelper.TOR -> {
+                // Set the app bar background to indicate proxying is enabled.
+                appBarLayout.setBackgroundResource(R.color.blue_background)
 
-            // 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 Orbot is installed.
+                try {
+                    // Get the package manager.
+                    val packageManager = packageManager
 
-                // Move to the first entry in the cursor.
-                bookmarksCursor.moveToFirst()
+                    // 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.
+                    packageManager.getPackageInfo("org.torproject.android", 0)
 
-                // 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))
+                    // 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 next bookmark.
-                    bookmarksCursor.moveToNext()
-                }
+                        // 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()
 
-                // 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()
-
-                // 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)
-
-                // Close the cursor.
-                bookmarkCursor.close()
-            }
-
-            // Close the bookmarks drawer if it is not pinned.
-            if (!bookmarksDrawerPinned)
-                drawerLayout.closeDrawer(GravityCompat.END)
-
-            // Consume the event.
-            true
-        }
-
-        // The drawer listener is used to update the navigation menu.
-        drawerLayout.addDrawerListener(object : DrawerLayout.DrawerListener {
-            override fun onDrawerSlide(drawerView: View, slideOffset: Float) {}
-
-            override fun onDrawerOpened(drawerView: 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()
-            }
-
-            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)
-
-                        // Hide the keyboard (if displayed).
-                        inputMethodManager.hideSoftInputFromWindow(currentWebView!!.windowToken, 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)
 
-                    // 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()
-
-                    // 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()
+                        // 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)))
+                        }
+                    }
                 }
             }
-        })
-
-        // 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 a handle for the WebView.
-        val bareWebView = webViewLayout.findViewById<WebView>(R.id.bare_webview)
-
-        // Store the default user agent.
-        webViewDefaultUserAgent = bareWebView.settings.userAgentString
-
-        // Destroy the bare WebView.
-        bareWebView.destroy()
-
-        // Update the domains settings set.
-        updateDomainsSettingsSet()
-
-        // Instantiate the blocklist helper.
-        blocklistHelper = BlocklistHelper()
-    }
-
-    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)
-
-        // Apply the saved proxy mode if the app has been restarted.
-        if (savedProxyMode != null) {
-            // Apply the saved proxy mode.
-            proxyMode = savedProxyMode!!
-
-            // Reset the saved proxy mode.
-            savedProxyMode = null
-        }
-
-        // Get the search string.
-        val searchString = sharedPreferences.getString(getString(R.string.search_key), getString(R.string.search_default_value))!!
-
-        // 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
 
-        // Apply the proxy.
-        applyProxy(false)
-
-        // 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)
+            ProxyHelper.I2P -> {
+                // Set the app bar background to indicate proxying is enabled.
+                appBarLayout.setBackgroundResource(R.color.blue_background)
 
-                // 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)
+                // 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.
+                    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.
+                        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)
 
-                    // Make it so.
-                    objectAnimator.start()
+                            // 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)))
+                            }
+                        }
+                    }
                 }
             }
-        } 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
 
-                // Expand the app bar if it is currently collapsed.
-                appBarLayout.setExpanded(true)
-            }
+            ProxyHelper.CUSTOM ->
+                // Set the app bar background to indicate proxying is enabled.
+                appBarLayout.setBackgroundResource(R.color.blue_background)
+        }
 
-            // Set the app bar scrolling for each WebView.
-            for (i in 0 until webViewPagerAdapter!!.count) {
+        // Reload the WebViews if requested and not waiting for the proxy.
+        if (reloadWebViews && !waitingForProxy) {
+            // Reload the WebViews.
+            for (i in 0 until webViewStateAdapter!!.itemCount) {
                 // Get the WebView tab fragment.
-                val webViewTabFragment = webViewPagerAdapter!!.getPageFragment(i)
+                val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
 
                 // Get the fragment view.
                 val fragmentView = webViewTabFragment.view
 
-                // Only modify the WebViews if they exist.
+                // 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)
 
-                    // Set the app bar scrolling.
-                    nestedScrollWebView.isNestedScrollingEnabled = scrollAppBar
+                    // Reload the WebView.
+                    nestedScrollWebView.reload()
                 }
             }
         }
+    }
 
-        // 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
+    // The view parameter cannot be removed because it is called from the layout onClick.
+    fun bookmarksBack(@Suppress("UNUSED_PARAMETER")view: View?) {
+        if (currentBookmarksFolderId == HOME_FOLDER_ID) {  // 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.
+            currentBookmarksFolderId = bookmarksDatabaseHelper!!.getParentFolderId(currentBookmarksFolderId)
 
-                // Hide the app bar.
-                appBar.hide()
-            } else {
-                // Show the tab linear layout.
-                tabsLinearLayout.visibility = View.VISIBLE
+            // Load the new folder.
+            loadBookmarksFolder()
+        }
+    }
 
-                // Show the app bar.
-                appBar.show()
-            }
+    private fun calculateSettingsInt(settingCurrentlyEnabled: Boolean, settingEnabledByDefault: Boolean): Int {
+        return if (settingCurrentlyEnabled == settingEnabledByDefault)  // The current system default is used.
+            SYSTEM_DEFAULT
+        else if (settingCurrentlyEnabled)  // The setting is enabled, which is different from the system default.
+            ENABLED
+        else  // The setting is disabled, which is different from the system default.
+            DISABLED
+    }
 
-            /* 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.
-             */
+    private fun clearAndExit() {
+        // Close the bookmarks cursor if it exists.
+        bookmarksCursor?.close()
 
-            // 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
+        // Close the databases helpers if they exist.
+        bookmarksDatabaseHelper?.close()
+        domainsDatabaseHelper?.close()
 
-            // Show the tab linear layout.
-            tabsLinearLayout.visibility = View.VISIBLE
+        // Get the status of the clear everything preference.
+        val clearEverything = sharedPreferences.getBoolean(getString(R.string.clear_everything_key), true)
 
-            // Show the app bar.
-            appBar.show()
+        // Get a handle for the runtime.
+        val runtime = Runtime.getRuntime()
 
-            // 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
-        }
-    }
+        // 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
 
-    override fun navigateHistory(url: String, steps: Int) {
-        // Apply the domain settings.
-        applyDomainSettings(currentWebView!!, url, resetTab = false, reloadWebsite = false, loadUrl = false)
-
-        // Load the history entry.
-        currentWebView!!.goBackOrForward(steps)
-    }
-
-    override fun pinnedErrorGoBack() {
-        // Get the current web back forward list.
-        val webBackForwardList = currentWebView!!.copyBackForwardList()
-
-        // Get the previous entry URL.
-        val previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex - 1).url
+        // 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)
 
-        // Apply the domain settings.
-        applyDomainSettings(currentWebView!!, previousUrl, resetTab = false, reloadWebsite = false, loadUrl = false)
+            // Ask the cookie manager to flush the cookie database.
+            cookieManager.flush()
 
-        // Go back.
-        currentWebView!!.goBack()
-    }
+            // 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")
 
-    // `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!!
+                // Wait until the processes have finished.
+                deleteCookiesProcess.waitFor()
+                deleteCookiesJournalProcess.waitFor()
+            } catch (exception: Exception) {
+                // Do nothing if an error is thrown.
+            }
+        }
 
-        // Parse the URL into a URI.
-        val uri = Uri.parse(url)
+        // 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()
 
-        // Extract the domain from the URI.
-        var newHostName = uri.host
+            // 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/"))
 
-        // Strings don't like to be null.
-        if (newHostName == null)
-            newHostName = ""
+                // 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")
 
-        // 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
+                // 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.
+            }
+        }
 
-            // Reset the ignoring of pinned domain information.
-            nestedScrollWebView.ignorePinnedDomainInformation = false
+        // 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()
 
-            // Clear any pinned SSL certificate or IP addresses.
-            nestedScrollWebView.clearPinnedSslCertificate()
-            nestedScrollWebView.pinnedIpAddresses = ""
+            // 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"))
 
-            // Reset the favorite icon if specified.
-            if (resetTab) {
-                // Initialize the favorite icon.
-                nestedScrollWebView.initializeFavoriteIcon()
+                // Wait until the processes have finished.
+                deleteWebDataProcess.waitFor()
+                deleteWebDataJournalProcess.waitFor()
+            } catch (exception: Exception) {
+                // Do nothing if an error is thrown.
+            }
+        }
 
-                // Get the current page position.
-                val currentPagePosition = webViewPagerAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
+        // 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")
 
-                // Get the corresponding tab.
-                val tab = tabLayout.getTabAt(currentPagePosition)
+                // Wait for the process to finish.
+                process.waitFor()
+            } catch (exception: IOException) {
+                // Do nothing.
+            } catch (exception: InterruptedException) {
+                // Do nothing.
+            }
+        }
 
-                // 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!!
+        // 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 webViewStateAdapter!!.itemCount) {
+                // Get the WebView tab fragment.
+                val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
 
-                    // 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 WebView fragment view.
+                val webViewFragmentView = webViewTabFragment.view
 
-                    // Set the default favorite icon as the favorite icon for this tab.
-                    tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nestedScrollWebView.getFavoriteIcon(), 64, 64, true))
+                // 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)
 
-                    // Set the loading title text.
-                    tabTitleTextView.setText(R.string.loading)
+                    // Clear the cache for this WebView.
+                    nestedScrollWebView.clearCache(true)
                 }
             }
 
-            // Initialize the domain name in database variable.
-            var domainNameInDatabase: String? = null
+            // Manually delete the cache directories.
+            try {
+                // Delete the main cache directory.
+                val deleteCacheProcess = runtime.exec("rm -rf $privateDataDirectoryString/cache")
 
-            // 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
+                // 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/"))
 
-                // 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
+                // Wait until the processes have finished.
+                deleteCacheProcess.waitFor()
+                deleteServiceWorkerProcess.waitFor()
+            } catch (exception: Exception) {
+                // Do nothing if an error is thrown.
             }
+        }
 
-            // 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
+        // Wipe out each WebView.
+        for (i in 0 until webViewStateAdapter!!.itemCount) {
+            // Get the WebView tab fragment.
+            val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
 
-                    // Store the applied domain names as it appears in the database.
-                    domainNameInDatabase = "*.$newHostName"
-                }
+            // Get the WebView frame layout.
+            val webViewFrameLayout = webViewTabFragment.view as FrameLayout?
 
-                // Strip out the lowest subdomain of of the host name.
-                newHostName = newHostName.substring(newHostName.indexOf(".") + 1)
-            }
+            // 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)
 
-            // 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)
+                // Clear SSL certificate preferences for this WebView.
+                nestedScrollWebView.clearSslPreferences()
 
-            // Get the WebView theme entry values string array.
-            val webViewThemeEntryValuesStringArray = resources.getStringArray(R.array.webview_theme_entry_values)
+                // Clear the back/forward history for this WebView.
+                nestedScrollWebView.clearHistory()
 
-            // 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)
+                // Remove all the views from the frame layout.
+                webViewFrameLayout.removeAllViews()
 
-            // 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!!)
+                // Destroy the internal state of the WebView.
+                nestedScrollWebView.destroy()
+            }
+        }
 
-                // Move to the first position.
-                currentDomainSettingsCursor.moveToFirst()
+        // 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 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))
+                // Wait until the process has finished.
+                deleteAppWebviewProcess.waitFor()
+            } catch (exception: Exception) {
+                // Do nothing if an error is thrown.
+            }
+        }
 
-                // Close the current host domain settings cursor.
-                currentDomainSettingsCursor.close()
+        // Close Privacy Browser.  `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
+        finishAndRemoveTask()
 
-                // If there is a pinned SSL certificate, store it in the WebView.
-                if (pinnedSslCertificate)
-                    nestedScrollWebView.setPinnedSslCertificate(pinnedSslIssuedToCName, pinnedSslIssuedToOName, pinnedSslIssuedToUName, pinnedSslIssuedByCName, pinnedSslIssuedByOName, pinnedSslIssuedByUName,
-                        pinnedSslStartDate, pinnedSslEndDate)
+        // Remove the terminated program from RAM.  The status code is `0`.
+        exitProcess(0)
+    }
 
-                // If there is a pinned IP address, store it in the WebView.
-                if (pinnedIpAddresses)
-                    nestedScrollWebView.pinnedIpAddresses = pinnedHostIpAddresses
+    // 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
 
-                // Apply the cookie domain settings.
-                cookieManager.setAcceptCookie(nestedScrollWebView.acceptCookies)
+        // Clear the highlighted phrases if the WebView is not null.
+        currentWebView?.clearMatches()
 
-                // Apply the form data setting if the API < 26.
-                @Suppress("DEPRECATION")
-                if (Build.VERSION.SDK_INT < 26)
-                    nestedScrollWebView.settings.saveFormData = saveFormData
+        // Hide the find on page linear layout.
+        findOnPageLinearLayout.visibility = View.GONE
 
-                // 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
-                }
+        // Show the toolbar.
+        toolbar.visibility = View.VISIBLE
 
-                // 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 handle for the input method manager.
+        val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
 
-                        // Set the user agent to `""`, which uses the default value.
-                        SETTINGS_WEBVIEW_DEFAULT_USER_AGENT -> nestedScrollWebView.settings.userAgentString = ""
+        // Hide the keyboard.
+        inputMethodManager.hideSoftInputFromWindow(toolbar.windowToken, 0)
+    }
 
-                        // 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))
+    // 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 (webViewStateAdapter!!.deletePage(currentTabNumber, webViewViewPager2))
+                setCurrentWebView(currentTabNumber)
+        } else {  // There is only one tab open.
+            clearAndExit()
+        }
+    }
 
-                        // 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
+    override fun createBookmark(dialogFragment: DialogFragment, favoriteIconBitmap: Bitmap) {
+        // Get the dialog.
+        val dialog = dialogFragment.dialog!!
 
-                        // Set the user agent to `""`, which uses the default value.
-                        SETTINGS_WEBVIEW_DEFAULT_USER_AGENT ->
-                            nestedScrollWebView.settings.userAgentString = ""
+        // 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 user agent string from the user agent data array.
-                        else ->
-                            nestedScrollWebView.settings.userAgentString = userAgentDataArray[userAgentArrayPosition]
-                    }
-                }
+        // Extract the strings from the edit texts.
+        val bookmarkNameString = createBookmarkNameEditText.text.toString()
+        val bookmarkUrlString = createBookmarkUrlEditText.text.toString()
 
-                // Set swipe to refresh.
-                when (swipeToRefreshInt) {
-                    DomainsDatabaseHelper.SYSTEM_DEFAULT -> {
-                        // Store the swipe to refresh status in the nested scroll WebView.
-                        nestedScrollWebView.swipeToRefresh = defaultSwipeToRefresh
+        // Create a favorite icon byte array output stream.
+        val favoriteIconByteArrayOutputStream = ByteArrayOutputStream()
 
-                        // 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
-                        }
-                    }
+        // 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)
 
-                    DomainsDatabaseHelper.ENABLED -> {
-                        // Store the swipe to refresh status in the nested scroll WebView.
-                        nestedScrollWebView.swipeToRefresh = true
+        // Convert the favorite icon byte array stream to a byte array.
+        val favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray()
 
-                        // 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)
-                        }
-                    }
+        // Display the new bookmark below the current items in the (0 indexed) list.
+        val newBookmarkDisplayOrder = bookmarksListView.count
 
-                    DomainsDatabaseHelper.DISABLED -> {
-                        // Store the swipe to refresh status in the nested scroll WebView.
-                        nestedScrollWebView.swipeToRefresh = false
+        // Create the bookmark.
+        bookmarksDatabaseHelper!!.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolderId, newBookmarkDisplayOrder, favoriteIconByteArray)
 
-                        // Disable swipe to refresh.
-                        swipeRefreshLayout.isEnabled = false
-                    }
-                }
+        // Update the bookmarks cursor with the current contents of this folder.
+        bookmarksCursor = bookmarksDatabaseHelper!!.getBookmarksByDisplayOrder(currentBookmarksFolderId)
 
-                // 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)
+        // Update the list view.
+        bookmarksCursorAdapter.changeCursor(bookmarksCursor)
 
-                                // The dark theme is selected.  Turn on algorithmic darkening.
-                                webViewThemeEntryValuesStringArray[2] -> WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
+        // Scroll to the new bookmark.
+        bookmarksListView.setSelection(newBookmarkDisplayOrder)
+    }
 
-                                // The system default theme is selected.
-                                else -> {
-                                    // Get the current system theme status.
-                                    val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
+    override fun createBookmarkFolder(dialogFragment: DialogFragment, favoriteIconBitmap: Bitmap) {
+        // Get the dialog.
+        val dialog = dialogFragment.dialog!!
 
-                                    // Set the algorithmic darkening according to the current system theme status.
-                                    WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, currentThemeStatus == Configuration.UI_MODE_NIGHT_YES)
-                                }
-                            }
+        // 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)
 
-                        // Turn off algorithmic darkening.
-                        DomainsDatabaseHelper.LIGHT_THEME -> WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
+        // Get new folder name string.
+        val folderNameString = folderNameEditText.text.toString()
 
-                        // Turn on algorithmic darkening.
-                        DomainsDatabaseHelper.DARK_THEME -> WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
-                    }
-                }
+        // 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
 
-                // 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 folder icon drawable to a bitmap drawable.
+            val folderIconBitmapDrawable = folderIconDrawable as BitmapDrawable
 
-                // 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
-                }
+            // 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
+        }
 
-                // 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)
+        // Create a folder icon byte array output stream.
+        val folderIconByteArrayOutputStream = ByteArrayOutputStream()
 
-                // Apply the default cookie setting.
-                cookieManager.setAcceptCookie(nestedScrollWebView.acceptCookies)
+        // 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)
 
-                // 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
-                }
+        // Convert the folder icon byte array stream to a byte array.
+        val folderIconByteArray = folderIconByteArrayOutputStream.toByteArray()
 
-                // Apply the form data setting if the API < 26.
-                if (Build.VERSION.SDK_INT < 26)
-                    @Suppress("DEPRECATION")
-                    nestedScrollWebView.settings.saveFormData = saveFormData
+        // 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()
 
-                // Store the swipe to refresh status in the nested scroll WebView.
-                nestedScrollWebView.swipeToRefresh = defaultSwipeToRefresh
+            // Move the bookmark down one slot.
+            bookmarksDatabaseHelper!!.updateDisplayOrder(databaseId, displayOrder = i + 1)
+        }
 
-                // 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
-                }
+        // Create the folder, which will be placed at the top of the list view.
+        bookmarksDatabaseHelper!!.createFolder(folderNameString, currentBookmarksFolderId, displayOrder = 0, folderIconByteArray)
 
-                // Reset the domain settings database ID.
-                nestedScrollWebView.domainSettingsDatabaseId = -1
+        // Update the bookmarks cursor with the current contents of this folder.
+        bookmarksCursor = bookmarksDatabaseHelper!!.getBookmarksByDisplayOrder(currentBookmarksFolderId)
 
-                // 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
+        // Update the list view.
+        bookmarksCursorAdapter.changeCursor(bookmarksCursor)
 
-                    // Set the user agent to `""`, which uses the default value.
-                    SETTINGS_WEBVIEW_DEFAULT_USER_AGENT -> nestedScrollWebView.settings.userAgentString = ""
+        // Scroll to the new folder.
+        bookmarksListView.setSelection(0)
+    }
 
-                    // 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))
+    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 user agent string from the user agent data array
-                    else -> nestedScrollWebView.settings.userAgentString = userAgentDataArray[userAgentArrayPosition]
-                }
+        // Set the URI and the mime type.
+        downloadIntent.setDataAndType(Uri.parse(url), "text/html")
 
-                // 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)
+        // Flag the intent to open in a new task.
+        downloadIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
 
-                        // The dark theme is selected.  Turn on algorithmic darkening.
-                        webViewThemeEntryValuesStringArray[2] -> WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
+        // Show the chooser.
+        startActivity(Intent.createChooser(downloadIntent, getString(R.string.download_with_external_app)))
+    }
 
-                        // 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
+    private fun exitFullScreenVideo() {
+        // Re-enable the screen timeout.
+        fullScreenVideoFrameLayout.keepScreenOn = false
 
-                            // Set the algorithmic darkening according to the current system theme status.
-                            WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, currentThemeStatus == Configuration.UI_MODE_NIGHT_YES)
-                        }
-                    }
-                }
+        // Unset the full screen video flag.
+        displayingFullScreenVideo = false
 
-                // Set the viewport.
-                nestedScrollWebView.settings.useWideViewPort = wideViewport
+        // Remove all the views from the full screen video frame layout.
+        fullScreenVideoFrameLayout.removeAllViews()
 
-                // Set the loading of webpage images.
-                nestedScrollWebView.settings.loadsImagesAutomatically = displayWebpageImages
+        // Hide the full screen video frame layout.
+        fullScreenVideoFrameLayout.visibility = View.GONE
 
-                // Set a transparent background on the URL relative layout.
-                urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.color.transparent)
+        // Enable the sliding drawers.
+        drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED)
+
+        // Show the coordinator layout.
+        coordinatorLayout.visibility = View.VISIBLE
+
+        // 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 app bar.
+                appBar.hide()
             }
 
-            // Update the privacy icons.
-            updatePrivacyIcons(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.
+             */
+
+            // 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
         }
+    }
 
-        // Reload the website if returning from the Domains activity.
-        if (reloadWebsite)
-            nestedScrollWebView.reload()
+    // 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)
+    }
 
-        // 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)
+    // 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)
     }
 
-    private fun applyProxy(reloadWebViews: Boolean) {
-        // Set the proxy according to the mode.
-        proxyHelper.setProxy(applicationContext, appBarLayout, proxyMode)
+    override fun finishedPopulatingFilterLists(combinedFilterLists: ArrayList<ArrayList<List<Array<String>>>>) {
+        // Store the filter lists.
+        easyList = combinedFilterLists[0]
+        easyPrivacy = combinedFilterLists[1]
+        fanboysAnnoyanceList = combinedFilterLists[2]
+        fanboysSocialList = combinedFilterLists[3]
+        ultraList = combinedFilterLists[4]
+        ultraPrivacy = combinedFilterLists[5]
 
-        // Reset the waiting for proxy tracker.
-        waitingForProxy = false
+        // 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(urlString = "", adjacent = false, moveToTab = false)
+        } else {  // The activity has been restarted with a saved state.
+            // Restore each tab.
+            for (i in savedStateArrayList!!.indices) {
+                // Add a new tab.
+                tabLayout.addTab(tabLayout.newTab())
 
-        // Set the proxy.
-        when (proxyMode) {
-            ProxyHelper.NONE -> {
-                // Initialize a color background typed value.
-                val colorBackgroundTypedValue = TypedValue()
-
-                // Get the color background from the theme.
-                theme.resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true)
+                // Get the new tab.
+                val newTab = tabLayout.getTabAt(i)!!
 
-                // Get the color background int from the typed value.
-                val colorBackgroundInt = colorBackgroundTypedValue.data
+                // Set a custom view on the new tab.
+                newTab.setCustomView(R.layout.tab_custom_view)
 
-                // Set the default app bar layout background.
-                appBarLayout.setBackgroundColor(colorBackgroundInt)
+                // Add the new page.
+                webViewStateAdapter!!.restorePage(savedStateArrayList!![i], savedNestedScrollWebViewStateArrayList!![i])
             }
 
-            ProxyHelper.TOR -> {
-                // Set the app bar background to indicate proxying is enabled.
-                appBarLayout.setBackgroundResource(R.color.proxy_appbar_background)
+            // Reset the saved state variables.
+            savedStateArrayList = null
+            savedNestedScrollWebViewStateArrayList = null
 
-                // Check to see if Orbot is installed.
-                try {
-                    // Get the package manager.
-                    val packageManager = packageManager
+            // Get the intent that started the app.
+            val intent = intent
 
-                    // 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)
+            // Reset the intent.  This prevents a duplicate tab from being created on restart.
+            setIntent(Intent())
 
-                    // 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
+            // Get the information from the intent.
+            val intentAction = intent.action
+            val intentUriData = intent.data
+            val intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT)
 
-                        // 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()
+            // Determine if this is a web search.
+            val isWebSearch = (intentAction != null) && (intentAction == Intent.ACTION_WEB_SEARCH)
 
-                            // 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)))
-                            }
-                        }
+            // 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) {  // A new tab is being loaded.
+                // 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) {
+                        ""
                     }
-                } 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)
 
-                        // 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)))
-                        }
-                    }
+                    // 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!!
                 }
-            }
 
-            ProxyHelper.I2P -> {
-                // Set the app bar background to indicate proxying is enabled.
-                appBarLayout.setBackgroundResource(R.color.proxy_appbar_background)
+                // 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
 
-                // 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)
+                    // Add a new tab.
+                    addNewTab(urlString, adjacent = false, moveToTab = true)
+                } else {  // Load the URL in the current tab.
+                    // Make it so.
+                    loadUrl(currentWebView!!, urlString)
+                }
+            } else {  // A new tab is not being loaded.
+                // 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.
+                    // Select the tab when the layout has finished populating.
+                    tabLayout.post {
+                        // Get a handle for the tab.
+                        val tab = tabLayout.getTabAt(savedTabPosition)!!
 
-                            // 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)))
-                            }
-                        }
+                        // Select the tab.
+                        tab.select()
                     }
                 }
             }
-
-            ProxyHelper.CUSTOM ->
-                // Set the app bar background to indicate proxying is enabled.
-                appBarLayout.setBackgroundResource(R.color.proxy_appbar_background)
         }
+    }
 
-        // 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)
+    // 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 fragment view.
-                val fragmentView = webViewTabFragment.view
+        // 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))
 
-                // 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)
+        // 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)
 
-                    // Reload the WebView.
-                    nestedScrollWebView.reload()
-                }
+                // Reapply the syntax highlighting.
+                UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
             }
         }
-    }
-
-    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)
+        // 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()
 
-            // `invalidateOptionsMenu()` calls `onPrepareOptionsMenu()` and redraws the icons in the app bar.
-            if (runInvalidateOptionsMenu)
-                invalidateOptionsMenu()
+                // Consume the event.
+                return@setOnKeyListener true
+            } else {  // Some other key was pressed.
+                // Do not consume the event.
+                return@setOnKeyListener false
+            }
         }
-    }
 
-    private fun loadBookmarksFolder() {
-        // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
-        bookmarksCursor = bookmarksDatabaseHelper!!.getBookmarksByDisplayOrder(currentBookmarksFolder)
+        // 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")!!
 
-        // 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)
-            }
+                // 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
 
-            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)
+                    // Get a list of the current fragments.
+                    val fragmentList = supportFragmentManager.fragments
 
-                // Get the favorite icon byte array from the cursor.
-                val favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.FAVORITE_ICON))
+                    // 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
 
-                // 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)
+                        // 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()
+                        }
+                    }
 
-                // Display the bitmap in the bookmark favorite icon.
-                bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap)
+                    // Reload existing URLs and load any URLs that are waiting for the proxy.
+                    for (i in 0 until webViewStateAdapter!!.itemCount) {
+                        // Get the WebView tab fragment.
+                        val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
 
-                // Display the bookmark name from the cursor in the bookmark name text view.
-                bookmarkNameTextView.text = cursor.getString(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME))
+                        // Get the fragment view.
+                        val fragmentView = webViewTabFragment.view
 
-                // 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
-            }
-        }
+                        // 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)
 
-        // Populate the list view with the adapter.
-        bookmarksListView.adapter = bookmarksCursorAdapter
+                            // Get the waiting for proxy URL string.
+                            val waitingForProxyUrlString = nestedScrollWebView.waitingForProxyUrlString
 
-        // Set the bookmarks drawer title.
-        if (currentBookmarksFolder.isEmpty())
-            bookmarksTitleTextView.setText(R.string.bookmarks)
-        else
-            bookmarksTitleTextView.text = currentBookmarksFolder
-    }
-
-    private fun openWithApp(url: String) {
-        // Create an open with app intent with `ACTION_VIEW`.
-        val openWithAppIntent = Intent(Intent.ACTION_VIEW)
-
-        // Set the URI but not the MIME type.  This should open all available apps.
-        openWithAppIntent.data = Uri.parse(url)
-
-        // Flag the intent to open in a new task.
-        openWithAppIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
+                            // Load the pending URL if it exists.
+                            if (waitingForProxyUrlString.isNotEmpty()) {  // A URL is waiting to be loaded.
+                                // Load the URL.
+                                loadUrl(nestedScrollWebView, waitingForProxyUrlString)
 
-        // 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 waiting for proxy URL string.
+                                nestedScrollWebView.waitingForProxyUrlString = ""
+                            } else {  // No URL is waiting to be loaded.
+                                // Reload the existing URL.
+                                nestedScrollWebView.reload()
+                            }
+                        }
+                    }
+                }
+            }
         }
-    }
 
-    private fun openWithBrowser(url: String) {
+        // Register the Orbot status broadcast receiver.  `ContextCompat` must be used until the minimum API >= 34.
+        ContextCompat.registerReceiver(this, orbotStatusBroadcastReceiver, IntentFilter("org.torproject.android.intent.action.STATUS"), ContextCompat.RECEIVER_EXPORTED)
 
-        // Create an open with browser intent with `ACTION_VIEW`.
-        val openWithBrowserIntent = Intent(Intent.ACTION_VIEW)
+        // 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)
 
-        // Set the URI and the MIME type.  `"text/html"` should load browser options.
-        openWithBrowserIntent.setDataAndType(Uri.parse(url), "text/html")
+        // Handle tab selections.
+        tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
+            override fun onTabSelected(tab: TabLayout.Tab) {
+                // Close the find on page bar if it is open.
+                closeFindOnPage(null)
 
-        // Flag the intent to open in a new task.
-        openWithBrowserIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
+                // Update the view pager when it has quiesced.  Otherwise, if a page launched by a new intent on restart has not yet been created, the view pager will not be updated to match the tab layout.
+                webViewViewPager2.post {
+                    // Select the same page in the view pager.
+                    webViewViewPager2.currentItem = tab.position
 
-        // 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 current WebView.
+                    setCurrentWebView(tab.position)
+                }
+            }
 
-    private fun sanitizeUrl(urlString: String): String {
-        // Initialize a sanitized URL string.
-        var sanitizedUrlString = urlString
+            override fun onTabUnselected(tab: TabLayout.Tab) {}
 
-        // Sanitize tracking queries.
-        if (sanitizeTrackingQueries)
-            sanitizedUrlString = SanitizeUrlHelper.sanitizeTrackingQueries(sanitizedUrlString)
+            override fun onTabReselected(tab: TabLayout.Tab) {
+                // Only display the view SSL certificate dialog if the current WebView is not null.
+                // This can happen if the tab is programmatically reselected while the app is being restarted and is not yet populated.
+                if (currentWebView != null) {
+                    // Instantiate the View SSL Certificate dialog.
+                    val viewSslCertificateDialogFragment: DialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView!!.webViewFragmentId, currentWebView!!.getFavoriteIcon())
+
+                    // Display the View SSL Certificate dialog.
+                    viewSslCertificateDialogFragment.show(supportFragmentManager, getString(R.string.view_ssl_certificate))
+                }
+            }
+        })
 
-        // Sanitize AMP redirects.
-        if (sanitizeAmpRedirects)
-            sanitizedUrlString = SanitizeUrlHelper.sanitizeAmpRedirects(sanitizedUrlString)
+        // 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 }
 
-        // Return the sanitized URL string.
-        return sanitizedUrlString
-    }
+        // 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()
 
-    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]
+            // Create a favorite icon byte array output stream.
+            val currentFavoriteIconByteArrayOutputStream = ByteArrayOutputStream()
 
-        // 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())
+            // 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)
 
-                // Get the new tab.
-                val newTab = tabLayout.getTabAt(i)!!
+            // Convert the favorite icon byte array stream to a byte array.
+            val currentFavoriteIconByteArray = currentFavoriteIconByteArrayOutputStream.toByteArray()
 
-                // Set a custom view on the new tab.
-                newTab.setCustomView(R.layout.tab_custom_view)
+            // Create an intent to launch the bookmarks activity.
+            val bookmarksIntent = Intent(applicationContext, BookmarksActivity::class.java)
 
-                // Add the new page.
-                webViewPagerAdapter!!.restorePage(savedStateArrayList!![i], savedNestedScrollWebViewStateArrayList!![i])
-            }
+            // Add the extra information to the intent.
+            bookmarksIntent.putExtra(CURRENT_FOLDER_ID, currentBookmarksFolderId)
+            bookmarksIntent.putExtra(CURRENT_TITLE, currentWebView!!.title)
+            bookmarksIntent.putExtra(CURRENT_URL, currentWebView!!.url)
+            bookmarksIntent.putExtra(CURRENT_FAVORITE_ICON_BYTE_ARRAY, currentFavoriteIconByteArray)
 
-            // Reset the saved state variables.
-            savedStateArrayList = null
-            savedNestedScrollWebViewStateArrayList = null
+            // Make it so.
+            startActivity(bookmarksIntent)
+        }
 
-            // 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 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())
 
-            // Get the intent that started the app.
-            val intent = intent
+            // Show the create bookmark folder dialog.
+            createBookmarkFolderDialog.show(supportFragmentManager, getString(R.string.create_folder))
+        }
 
-            // Reset the intent.  This prevents a duplicate tab from being created on restart.
-            setIntent(Intent())
+        // 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())
 
-            // Get the information from the intent.
-            val intentAction = intent.action
-            val intentUriData = intent.data
-            val intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT)
+            // Display the create bookmark dialog.
+            createBookmarkDialog.show(supportFragmentManager, getString(R.string.create_bookmark))
+        }
 
-            // Determine if this is a web search.
-            val isWebSearch = (intentAction != null) && (intentAction == Intent.ACTION_WEB_SEARCH)
+        // 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) {}
 
-            // 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) {
-                        ""
-                    }
+            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
 
-                    // 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!!
-                }
+            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())
+            }
+        })
 
-                // 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
+        // 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)
 
-                    // Add a new tab.
-                    addNewTab(urlString, true)
-                } else {  // Load the URL in the current tab.
-                    // Make it so.
-                    loadUrl(currentWebView!!, urlString)
-                }
+                // Consume the event.
+                return@setOnKeyListener true
+            } else {  // A different key was pressed.
+                // Do not consume the event.
+                return@setOnKeyListener false
             }
         }
-    }
 
-    // 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)
-    }
+        // Implement swipe to refresh.
+        swipeRefreshLayout.setOnRefreshListener {
+            // Reload the website.
+            currentWebView!!.reload()
+        }
 
-    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()
+        // Store the default progress view offsets.
+        defaultProgressViewStartOffset = swipeRefreshLayout.progressViewStartOffset
+        defaultProgressViewEndOffset = swipeRefreshLayout.progressViewEndOffset
 
-        // 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
+        // Set the refresh color scheme according to the theme.
+        swipeRefreshLayout.setColorSchemeResources(R.color.blue_text)
 
-        // Add a new tab.
-        tabLayout.addTab(tabLayout.newTab())
+        // Initialize a color background typed value.
+        val colorBackgroundTypedValue = TypedValue()
 
-        // Get the new tab.
-        val newTab = tabLayout.getTabAt(newTabNumber)!!
+        // Get the color background from the theme.
+        theme.resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true)
 
-        // Set a custom view on the new tab.
-        newTab.setCustomView(R.layout.tab_custom_view)
+        // Get the color background int from the typed value.
+        val colorBackgroundInt = colorBackgroundTypedValue.data
 
-        // Add the new WebView page.
-        webViewPagerAdapter!!.addPage(newTabNumber, webViewPager, urlString, moveToTab)
+        // Set the swipe refresh background color.
+        swipeRefreshLayout.setProgressBackgroundColorSchemeColor(colorBackgroundInt)
 
-        // 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)
+        // 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))
 
-            // Make it so.
-            objectAnimator.start()
-        }
-    }
+        // Load the bookmarks folder.
+        loadBookmarksFolder()
 
-    // 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()
-    }
+        // 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 closeCurrentTab() {
-        // Get the current tab number.
-        val currentTabNumber = tabLayout.selectedTabPosition
+            // Get the bookmark cursor for this ID.
+            val bookmarkCursor = bookmarksDatabaseHelper!!.getBookmark(databaseId)
 
-        // Delete the current tab.
-        tabLayout.removeTabAt(currentTabNumber)
+            // Move the bookmark cursor to the first row.
+            bookmarkCursor.moveToFirst()
 
-        // 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)
-    }
+            // Act upon the bookmark according to the type.
+            if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndexOrThrow(IS_FOLDER)) == 1) {  // The selected bookmark is a folder.
+                // Store the folder ID.
+                currentBookmarksFolderId = bookmarkCursor.getLong(bookmarkCursor.getColumnIndexOrThrow(FOLDER_ID))
 
-    private fun exitFullScreenVideo() {
-        // Re-enable the screen timeout.
-        fullScreenVideoFrameLayout.keepScreenOn = false
+                // Load the new folder.
+                loadBookmarksFolder()
+            } else {  // The selected bookmark is not a folder.
+                // Load the bookmark URL.
+                loadUrl(currentWebView!!, bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BOOKMARK_URL)))
 
-        // Unset the full screen video flag.
-        displayingFullScreenVideo = false
+                // Close the bookmarks drawer if it is not pinned.
+                if (!bookmarksDrawerPinned)
+                    drawerLayout.closeDrawer(GravityCompat.END)
+            }
 
-        // Remove all the views from the full screen video frame layout.
-        fullScreenVideoFrameLayout.removeAllViews()
-
-        // Hide the full screen video frame layout.
-        fullScreenVideoFrameLayout.visibility = View.GONE
+            // Close the cursor.
+            bookmarkCursor.close()
+        }
 
-        // Enable the sliding drawers.
-        drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED)
+        // 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()
 
-        // Show the coordinator layout.
-        coordinatorLayout.visibility = View.VISIBLE
+            // Run the commands associated with the type.
+            if (bookmarksDatabaseHelper!!.isFolder(databaseId)) {  // The bookmark is a folder.
+                // Get the folder ID.
+                val folderId = bookmarksDatabaseHelper!!.getFolderId(databaseId)
 
-        // 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 a cursor of all the bookmarks in the folder.
+                val bookmarksCursor = bookmarksDatabaseHelper!!.getFolderBookmarks(folderId)
 
-                // Hide the app bar.
-                appBar.hide()
-            }
+                // Move to the first entry in the cursor.
+                bookmarksCursor.moveToFirst()
 
-            /* 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.
-             */
+                // 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(BOOKMARK_URL)), adjacent = false, moveToTab = !bookmarksDrawerPinned && (i == 0))
 
-            // 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
-        }
-    }
+                    // Move to the next bookmark.
+                    bookmarksCursor.moveToNext()
+                }
 
-    private fun clearAndExit() {
-        // Close the bookmarks cursor if it exists.
-        bookmarksCursor?.close()
+                // Close the cursor.
+                bookmarksCursor.close()
+            } else {  // The bookmark is not a folder.
+                // Get the bookmark cursor for this ID.
+                val bookmarkCursor = bookmarksDatabaseHelper!!.getBookmark(databaseId)
 
-        // Close the databases helpers if they exist.
-        bookmarksDatabaseHelper?.close()
-        domainsDatabaseHelper?.close()
+                // Move the bookmark cursor to the first row.
+                bookmarkCursor.moveToFirst()
 
-        // Get the status of the clear everything preference.
-        val clearEverything = sharedPreferences.getBoolean(getString(R.string.clear_everything_key), true)
+                // Load the bookmark in a new tab and move to the tab if the drawer is not pinned.
+                addNewTab(bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BOOKMARK_URL)), adjacent = true, moveToTab = !bookmarksDrawerPinned)
 
-        // Get a handle for the runtime.
-        val runtime = Runtime.getRuntime()
+                // Close the cursor.
+                bookmarkCursor.close()
+            }
 
-        // 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
+            // Close the bookmarks drawer if it is not pinned.
+            if (!bookmarksDrawerPinned)
+                drawerLayout.closeDrawer(GravityCompat.END)
 
-        // 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)
+            // Consume the event.
+            true
+        }
 
-            // Ask the cookie manager to flush the cookie database.
-            cookieManager.flush()
+        // The drawer listener is used to update the navigation menu.
+        drawerLayout.addDrawerListener(object : DrawerLayout.DrawerListener {
+            override fun onDrawerSlide(drawerView: View, slideOffset: Float) {}
 
-            // 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")
+            override fun onDrawerOpened(drawerView: View) {}
 
-                // Wait until the processes have finished.
-                deleteCookiesProcess.waitFor()
-                deleteCookiesJournalProcess.waitFor()
-            } catch (exception: Exception) {
-                // Do nothing if an error is thrown.
+            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()
             }
-        }
-
-        // 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()
 
-            // 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/"))
+            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) {
+                        // Set the enabled status of the menu items.
+                        navigationBackMenuItem.isEnabled = currentWebView!!.canGoBack()
+                        navigationForwardMenuItem.isEnabled = currentWebView!!.canGoForward()
+                        navigationScrollToBottomMenuItem.isEnabled = (currentWebView!!.canScrollVertically(-1) || currentWebView!!.canScrollVertically(1))
+                        navigationHistoryMenuItem.isEnabled = currentWebView!!.canGoBack() || currentWebView!!.canGoForward()
 
-                // 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")
+                        // Update the scroll menu item.
+                        if (currentWebView!!.scrollY == 0) {  // The WebView is scrolled to the top.
+                            // Set the title.
+                            navigationScrollToBottomMenuItem.title = getString(R.string.scroll_to_bottom)
 
-                // 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.
-            }
-        }
+                            // Set the icon.
+                            navigationScrollToBottomMenuItem.icon = AppCompatResources.getDrawable(applicationContext, R.drawable.move_down_enabled)
+                        } else {  // The WebView is not scrolled to the top.
+                            // Set the title.
+                            navigationScrollToBottomMenuItem.title = getString(R.string.scroll_to_top)
 
-        // 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()
+                            // Set the icon.
+                            navigationScrollToBottomMenuItem.icon = AppCompatResources.getDrawable(applicationContext, R.drawable.move_up_enabled)
+                        }
 
-            // 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"))
+                        // Display the number of blocked requests.
+                        navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + currentWebView!!.getRequestsCount(BLOCKED_REQUESTS)
 
-                // Wait until the processes have finished.
-                deleteWebDataProcess.waitFor()
-                deleteWebDataJournalProcess.waitFor()
-            } catch (exception: Exception) {
-                // Do nothing if an error is thrown.
-            }
-        }
+                        // Hide the keyboard (if displayed).
+                        inputMethodManager.hideSoftInputFromWindow(currentWebView!!.windowToken, 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")
+                    // 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()
 
-                // Wait for the process to finish.
-                process.waitFor()
-            } catch (exception: IOException) {
-                // Do nothing.
-            } catch (exception: InterruptedException) {
-                // Do nothing.
-            }
-        }
+                    // 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()
 
-        // 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)
+                    if (bottomAppBar && navigationDrawerFirstView) {
+                        // Reset the navigation drawer first view flag.
+                        navigationDrawerFirstView = false
 
-                // Get the WebView fragment view.
-                val webViewFragmentView = webViewTabFragment.view
+                        // Get a handle for the navigation recycler view.
+                        val navigationRecyclerView = navigationView.getChildAt(0) as RecyclerView
 
-                // 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)
+                        // Get the navigation linear layout manager.
+                        val navigationLinearLayoutManager = navigationRecyclerView.layoutManager as LinearLayoutManager
 
-                    // Clear the cache for this WebView.
-                    nestedScrollWebView.clearCache(true)
+                        // Scroll the navigation drawer to the bottom.
+                        navigationLinearLayoutManager.scrollToPositionWithOffset(13, 0)
+                    }
                 }
             }
+        })
 
-            // Manually delete the cache directories.
-            try {
-                // Delete the main cache directory.
-                val deleteCacheProcess = runtime.exec("rm -rf $privateDataDirectoryString/cache")
-
-                // 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/"))
+        // 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)
 
-                // Wait until the processes have finished.
-                deleteCacheProcess.waitFor()
-                deleteServiceWorkerProcess.waitFor()
-            } catch (exception: Exception) {
-                // Do nothing if an error is thrown.
-            }
-        }
+        // Get a handle for the WebView.
+        val bareWebView = webViewLayout.findViewById<WebView>(R.id.bare_webview)
 
-        // Wipe out each WebView.
-        for (i in 0 until webViewPagerAdapter!!.count) {
-            // Get the WebView tab fragment.
-            val webViewTabFragment = webViewPagerAdapter!!.getPageFragment(i)
+        // Store the default user agent.
+        webViewDefaultUserAgent = bareWebView.settings.userAgentString
 
-            // Get the WebView frame layout.
-            val webViewFrameLayout = webViewTabFragment.view as FrameLayout?
+        // Destroy the bare WebView.
+        bareWebView.destroy()
 
-            // 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)
+        // Update the domains settings set.
+        updateDomainsSettingsSet()
 
-                // Clear SSL certificate preferences for this WebView.
-                nestedScrollWebView.clearSslPreferences()
+        // Instantiate the check filter list helper.
+        checkFilterListHelper = CheckFilterListHelper()
+    }
 
-                // Clear the back/forward history for this WebView.
-                nestedScrollWebView.clearHistory()
+    @SuppressLint("ClickableViewAccessibility")
+    override fun initializeWebView(nestedScrollWebView: NestedScrollWebView, pagePosition: 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))
 
-                // Remove all the views from the frame layout.
-                webViewFrameLayout.removeAllViews()
+        // Get the WebView theme entry values string array.
+        val webViewThemeEntryValuesStringArray = resources.getStringArray(R.array.webview_theme_entry_values)
 
-                // Destroy the internal state of the WebView.
-                nestedScrollWebView.destroy()
-            }
-        }
+        // Set the WebView theme if algorithmic darkening is supported.
+        if (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)
 
-        // 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")
-
-                // Wait until the process has finished.
-                deleteAppWebviewProcess.waitFor()
-            } catch (exception: Exception) {
-                // Do nothing if an error is thrown.
-            }
-        }
-
-        // Close Privacy Browser.  `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
-        finishAndRemoveTask()
-
-        // Remove the terminated program from RAM.  The status code is `0`.
-        exitProcess(0)
-    }
-
-    // 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)
-
-            // Load the new folder.
-            loadBookmarksFolder()
-        }
-    }
-
-        // 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
-
-        // Update the bookmarks drawer pinned image view.
-        updateBookmarksDrawerPinnedImageView()
-    }
-
-    private fun updateBookmarksDrawerPinnedImageView() {
-        // Set the current icon.
-        if (bookmarksDrawerPinned)
-            bookmarksDrawerPinnedImageView.setImageResource(R.drawable.pin_selected)
-        else
-            bookmarksDrawerPinnedImageView.setImageResource(R.drawable.pin)
-    }
-
-    private fun setCurrentWebView(pageNumber: Int) {
-        // Stop the swipe to refresh indicator if it is running
-        swipeRefreshLayout.isRefreshing = false
-
-        // Get the WebView tab fragment.
-        val webViewTabFragment = webViewPagerAdapter!!.getPageFragment(pageNumber)
-
-        // 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)
-
-            // 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
-            }
-
-            // Set the cookie status.
-            cookieManager.setAcceptCookie(currentWebView!!.acceptCookies)
-
-            // Update the privacy icons.  `true` redraws the icons in the app bar.
-            updatePrivacyIcons(true)
-
-            // Get a handle for the input method manager.
-            val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
-
-            // Get the current URL.
-            val urlString = currentWebView!!.url
-
-            // 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("")
-
-                    // Request focus for the URL text box.
-                    urlEditText.requestFocus()
-
-                    // Display the keyboard.
-                    inputMethodManager.showSoftInput(urlEditText, 0)
-                } else {  // The WebView has a loaded URL.
-                    // Clear the focus from the URL text box.
-                    urlEditText.clearFocus()
-
-                    // Hide the soft keyboard.
-                    inputMethodManager.hideSoftInputFromWindow(currentWebView!!.windowToken, 0)
-
-                    // 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
-            }
-
-            // 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())
-
-            // Create a runnable to set the current WebView.
-            val setCurrentWebWebRunnable = Runnable {
-                // Set the current WebView.
-                setCurrentWebView(pageNumber)
-            }
-
-            // Try setting the current WebView again after 100 milliseconds.
-            setCurrentWebViewHandler.postDelayed(setCurrentWebWebRunnable, 100)
-        }
-    }
-
-    @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))
-
-        // Get the WebView theme entry values string array.
-        val webViewThemeEntryValuesStringArray = resources.getStringArray(R.array.webview_theme_entry_values)
-
-        // 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
+                // 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.
@@ -4830,8 +4836,7 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
 
                         // 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
+                        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) {
@@ -4882,9 +4887,9 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
                 }
             }
 
-            override fun onFling(motionEvent1: MotionEvent, motionEvent2: MotionEvent, velocityX: Float, velocityY: Float): Boolean {
+            override fun onFling(motionEvent1: MotionEvent?, motionEvent2: MotionEvent, velocityX: Float, velocityY: Float): Boolean {
                 // Scroll the bottom app bar if enabled.
-                if (bottomAppBar && scrollAppBar && !objectAnimator.isRunning) {
+                if (bottomAppBar && scrollAppBar && !objectAnimator.isRunning && (motionEvent1 != null)) {
                     // Calculate the Y change.
                     val motionY = motionEvent2.y - motionEvent1.y
 
@@ -4950,6 +4955,29 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
                     pendingDialogsArrayList.add(PendingDialogDataClass(saveDialogFragment, getString(R.string.save_dialog)))
                 }
             }
+
+            // Get the current page position.
+            val currentPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
+
+            // Get the corresponding tab.
+            val tab = tabLayout.getTabAt(currentPagePosition)!!
+
+            // Get the tab custom view.
+            val tabCustomView = tab.customView!!
+
+            // Get the tab views.
+            val tabFavoriteIconImageView = tabCustomView.findViewById<ImageView>(R.id.favorite_icon_imageview)
+            val tabTitleTextView = tabCustomView.findViewById<TextView>(R.id.title_textview)
+
+            // Restore the previous webpage favorite icon and title if the title is currently set to `Loading...`.
+            if (tabTitleTextView.text.toString() == getString(R.string.loading)) {
+                // Restore the previous webpage title text.
+                tabTitleTextView.text = nestedScrollWebView.previousWebpageTitle
+
+                // Restore the previous webpage favorite icon if it is not null.
+                if (nestedScrollWebView.previousFavoriteIconDrawable != null)
+                    tabFavoriteIconImageView.setImageDrawable(nestedScrollWebView.previousFavoriteIconDrawable)
+            }
         }
 
         // Update the find on page count.
@@ -5026,7 +5054,7 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
                     nestedScrollWebView.setFavoriteIcon(icon)
 
                     // Get the current page position.
-                    val currentPosition = webViewPagerAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
+                    val currentPosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
 
                     // Get the current tab.
                     val tab = tabLayout.getTabAt(currentPosition)
@@ -5051,7 +5079,7 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
             // 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)
+                val currentPosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
 
                 // Get the current tab.
                 val tab = tabLayout.getTabAt(currentPosition)
@@ -5243,10 +5271,10 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
                     return null
                 }
 
-                // 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.
+                // Wait until the filter lists 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.
+                        // Check to see if the filter lists have been populated after 100 ms.
                         Thread.sleep(100)
                     } catch (exception: InterruptedException) {
                         // Do nothing.
@@ -5257,7 +5285,7 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
                 val emptyWebResourceResponse = WebResourceResponse("text/plain", "utf8", ByteArrayInputStream("".toByteArray()))
 
                 // Initialize the variables.
-                var whitelistResultStringArray: Array<String>? = null
+                var allowListResultStringArray: Array<String>? = null
                 var isThirdPartyRequest = false
 
                 // Get the current URL.  `.getUrl()` throws an error because operations on the WebView cannot be made from this thread.
@@ -5288,21 +5316,21 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
                 }
 
                 // Get the current WebView page position.
-                val webViewPagePosition = webViewPagerAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
+                val webViewPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
 
                 // Determine if the WebView is currently displayed.
-                val webViewDisplayed = webViewPagePosition == tabLayout.selectedTabPosition
+                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))
+                    nestedScrollWebView.addResourceRequest(arrayOf(REQUEST_THIRD_PARTY, requestUrlString))
 
                     // Increment the blocked requests counters.
                     nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
                     nestedScrollWebView.incrementRequestsCount(THIRD_PARTY_REQUESTS)
 
-                    // Update the titles of the blocklist menu items if the WebView is currently displayed.
+                    // Update the titles of the filter lists menu items if the WebView is currently displayed.
                     if (webViewDisplayed) {
                         // Updating the UI must be run from the UI thread.
                         runOnUiThread {
@@ -5311,7 +5339,7 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
 
                             // Update the options menu if it has been populated.
                             if (optionsMenu != null) {
-                                optionsBlocklistsMenuItem.title = getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
+                                optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
                                 optionsBlockAllThirdPartyRequestsMenuItem.title =
                                     nestedScrollWebView.getRequestsCount(THIRD_PARTY_REQUESTS).toString() + " - " + getString(R.string.block_all_third_party_requests)
                             }
@@ -5325,18 +5353,18 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
                 // Check UltraList if it is enabled.
                 if (nestedScrollWebView.ultraListEnabled) {
                     // Check the URL against UltraList.
-                    val ultraListResults = blocklistHelper.checkBlocklist(currentDomain, requestUrlString, isThirdPartyRequest, ultraList)
+                    val ultraListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, ultraList)
 
                     // Process the UltraList results.
-                    if (ultraListResults[0] == BlocklistHelper.REQUEST_BLOCKED) {  // The resource request matched UltraList's blacklist.
+                    if (ultraListResults[0] == REQUEST_BLOCKED) {  // The resource request matched UltraList's block list.
                         // Add the result to the resource requests.
                         nestedScrollWebView.addResourceRequest(arrayOf(ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]))
 
                         // Increment the blocked requests counters.
                         nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
-                        nestedScrollWebView.incrementRequestsCount(ULTRALIST)
+                        nestedScrollWebView.incrementRequestsCount(com.stoutner.privacybrowser.views.ULTRALIST)
 
-                        // Update the titles of the blocklist menu items if the WebView is currently displayed.
+                        // Update the titles of the filter lists menu items if the WebView is currently displayed.
                         if (webViewDisplayed) {
                             // Updating the UI must be run from the UI thread.
                             runOnUiThread {
@@ -5345,19 +5373,19 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
 
                                 // 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)
+                                    optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
+                                    optionsUltraListMenuItem.title = nestedScrollWebView.getRequestsCount(com.stoutner.privacybrowser.views.ULTRALIST).toString() + " - " + getString(R.string.ultralist)
                                 }
                             }
                         }
 
                         // 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.
+                    } else if (ultraListResults[0] == REQUEST_ALLOWED) {  // The resource request matched UltraList's allow list.
+                        // Add an allow list entry to the resource requests array.
                         nestedScrollWebView.addResourceRequest(arrayOf(ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]))
 
-                        // The resource request has been allowed by UltraPrivacy.  `return null` loads the requested resource.
+                        // The resource request has been allowed by UltraList.  `return null` loads the requested resource.
                         return null
                     }
                 }
@@ -5365,10 +5393,10 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
                 // Check UltraPrivacy if it is enabled.
                 if (nestedScrollWebView.ultraPrivacyEnabled) {
                     // Check the URL against UltraPrivacy.
-                    val ultraPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, requestUrlString, isThirdPartyRequest, ultraPrivacy!!)
+                    val ultraPrivacyResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, ultraPrivacy!!)
 
                     // Process the UltraPrivacy results.
-                    if (ultraPrivacyResults[0] == BlocklistHelper.REQUEST_BLOCKED) {  // The resource request matched UltraPrivacy's blacklist.
+                    if (ultraPrivacyResults[0] == REQUEST_BLOCKED) {  // The resource request matched UltraPrivacy's block list.
                         // Add the result to the resource requests.
                         nestedScrollWebView.addResourceRequest(arrayOf(ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
                             ultraPrivacyResults[5]))
@@ -5377,7 +5405,7 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
                         nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
                         nestedScrollWebView.incrementRequestsCount(ULTRAPRIVACY)
 
-                        // Update the titles of the blocklist menu items if the WebView is currently displayed.
+                        // Update the titles of the filter lists menu items if the WebView is currently displayed.
                         if (webViewDisplayed) {
                             // Updating the UI must be run from the UI thread.
                             runOnUiThread {
@@ -5386,7 +5414,7 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
 
                                 // Update the options menu if it has been populated.
                                 if (optionsMenu != null) {
-                                    optionsBlocklistsMenuItem.title = getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
+                                    optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
                                     optionsUltraPrivacyMenuItem.title = nestedScrollWebView.getRequestsCount(ULTRAPRIVACY).toString() + " - " + getString(R.string.ultraprivacy)
                                 }
                             }
@@ -5394,8 +5422,8 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
 
                         // 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.
+                    } else if (ultraPrivacyResults[0] == REQUEST_ALLOWED) {  // The resource request matched UltraPrivacy's allow list.
+                        // Add an allow list entry to the resource requests array.
                         nestedScrollWebView.addResourceRequest(arrayOf(ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
                             ultraPrivacyResults[5]))
 
@@ -5407,10 +5435,10 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
                 // Check EasyList if it is enabled.
                 if (nestedScrollWebView.easyListEnabled) {
                     // Check the URL against EasyList.
-                    val easyListResults = blocklistHelper.checkBlocklist(currentDomain, requestUrlString, isThirdPartyRequest, easyList)
+                    val easyListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, easyList)
 
                     // Process the EasyList results.
-                    if (easyListResults[0] == BlocklistHelper.REQUEST_BLOCKED) {  // The resource request matched EasyList's blacklist.
+                    if (easyListResults[0] == REQUEST_BLOCKED) {  // The resource request matched EasyList's block list.
                         // Add the result to the resource requests.
                         nestedScrollWebView.addResourceRequest(arrayOf(easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]))
 
@@ -5418,7 +5446,7 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
                         nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
                         nestedScrollWebView.incrementRequestsCount(EASYLIST)
 
-                        // Update the titles of the blocklist menu items if the WebView is currently displayed.
+                        // Update the titles of the filter lists menu items if the WebView is currently displayed.
                         if (webViewDisplayed) {
                             // Updating the UI must be run from the UI thread.
                             runOnUiThread {
@@ -5427,7 +5455,7 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
 
                                 // Update the options menu if it has been populated.
                                 if (optionsMenu != null) {
-                                    optionsBlocklistsMenuItem.title = getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
+                                    optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
                                     optionsEasyListMenuItem.title = nestedScrollWebView.getRequestsCount(EASYLIST).toString() + " - " + getString(R.string.easylist)
                                 }
                             }
@@ -5435,19 +5463,19 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
 
                         // 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])
+                    } else if (easyListResults[0] == REQUEST_ALLOWED) {  // The resource request matched EasyList's allow list.
+                        // Update the allow list result string array tracker.
+                        allowListResultStringArray = arrayOf(easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5])
                     }
                 }
 
                 // Check EasyPrivacy if it is enabled.
                 if (nestedScrollWebView.easyPrivacyEnabled) {
                     // Check the URL against EasyPrivacy.
-                    val easyPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, requestUrlString, isThirdPartyRequest, easyPrivacy)
+                    val easyPrivacyResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, easyPrivacy)
 
                     // Process the EasyPrivacy results.
-                    if (easyPrivacyResults[0] == BlocklistHelper.REQUEST_BLOCKED) {  // The resource request matched EasyPrivacy's blacklist.
+                    if (easyPrivacyResults[0] == REQUEST_BLOCKED) {  // The resource request matched EasyPrivacy's block list.
                         // Add the result to the resource requests.
                         nestedScrollWebView.addResourceRequest(arrayOf(easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5]))
 
@@ -5455,7 +5483,7 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
                         nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
                         nestedScrollWebView.incrementRequestsCount(EASYPRIVACY)
 
-                        // Update the titles of the blocklist menu items if the WebView is currently displayed.
+                        // Update the titles of the filter lists menu items if the WebView is currently displayed.
                         if (webViewDisplayed) {
                             // Updating the UI must be run from the UI thread.
                             runOnUiThread {
@@ -5464,7 +5492,7 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
 
                                 // Update the options menu if it has been populated.
                                 if (optionsMenu != null) {
-                                    optionsBlocklistsMenuItem.title = getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
+                                    optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
                                     optionsEasyPrivacyMenuItem.title = nestedScrollWebView.getRequestsCount(EASYPRIVACY).toString() + " - " + getString(R.string.easyprivacy)
                                 }
                             }
@@ -5472,28 +5500,28 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
 
                         // 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])
+                    } else if (easyPrivacyResults[0] == REQUEST_ALLOWED) {  // The resource request matched EasyPrivacy's allow list.
+                        // Update the allow list result string array tracker.
+                        allowListResultStringArray = arrayOf(easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5])
                     }
                 }
 
                 // 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)
+                    val fanboysAnnoyanceListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, fanboysAnnoyanceList)
 
                     // Process the Fanboy's Annoyance List results.
-                    if (fanboysAnnoyanceListResults[0] == BlocklistHelper.REQUEST_BLOCKED) {  // The resource request matched Fanboy's Annoyance List's blacklist.
+                    if (fanboysAnnoyanceListResults[0] == REQUEST_BLOCKED) {  // The resource request matched Fanboy's Annoyance List's block list.
                         // Add the result to the resource requests.
                         nestedScrollWebView.addResourceRequest(arrayOf(fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
-                                fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]))
+                            fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]))
 
                         // Increment the blocked requests counters.
                         nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
                         nestedScrollWebView.incrementRequestsCount(FANBOYS_ANNOYANCE_LIST)
 
-                        // Update the titles of the blocklist menu items if the WebView is currently displayed.
+                        // Update the titles of the filter lists menu items if the WebView is currently displayed.
                         if (webViewDisplayed) {
                             // Updating the UI must be run from the UI thread.
                             runOnUiThread {
@@ -5502,7 +5530,7 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
 
                                 // Update the options menu if it has been populated.
                                 if (optionsMenu != null) {
-                                    optionsBlocklistsMenuItem.title = getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
+                                    optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
                                     optionsFanboysAnnoyanceListMenuItem.title = nestedScrollWebView.getRequestsCount(FANBOYS_ANNOYANCE_LIST).toString() + " - " + getString(R.string.fanboys_annoyance_list)
                                 }
                             }
@@ -5510,17 +5538,17 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
 
                         // 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],
+                    } else if (fanboysAnnoyanceListResults[0] == REQUEST_ALLOWED) {  // The resource request matched Fanboy's Annoyance List's allow list.
+                        // Update the allow list result string array tracker.
+                        allowListResultStringArray = 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)
+                    val fanboysSocialListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, fanboysSocialList)
 
                     // 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.
+                    if (fanboysSocialListResults[0] == REQUEST_BLOCKED) {  // The resource request matched Fanboy's Social Blocking List's block list.
                         // Add the result to the resource requests.
                         nestedScrollWebView.addResourceRequest(arrayOf(fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
                             fanboysSocialListResults[4], fanboysSocialListResults[5]))
@@ -5529,7 +5557,7 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
                         nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
                         nestedScrollWebView.incrementRequestsCount(FANBOYS_SOCIAL_BLOCKING_LIST)
 
-                        // Update the titles of the blocklist menu items if the WebView is currently displayed.
+                        // Update the titles of the filter lists menu items if the WebView is currently displayed.
                         if (webViewDisplayed) {
                             // Updating the UI must be run from the UI thread.
                             runOnUiThread {
@@ -5538,7 +5566,7 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
 
                                 // Update the options menu if it has been populated.
                                 if (optionsMenu != null) {
-                                    optionsBlocklistsMenuItem.title = getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
+                                    optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
                                     optionsFanboysSocialBlockingListMenuItem.title =
                                         nestedScrollWebView.getRequestsCount(FANBOYS_SOCIAL_BLOCKING_LIST).toString() + " - " + getString(R.string.fanboys_social_blocking_list)
                                 }
@@ -5547,18 +5575,18 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
 
                         // 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],
+                    } else if (fanboysSocialListResults[0] == REQUEST_ALLOWED) {  // The resource request matched Fanboy's Social Blocking List's allow list.
+                        // Update the allow list result string array tracker.
+                        allowListResultStringArray = arrayOf(fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3], fanboysSocialListResults[4],
                             fanboysSocialListResults[5])
                     }
                 }
 
                 // 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))
+                if (allowListResultStringArray != null) {  // The request was processed by an allow list.
+                    nestedScrollWebView.addResourceRequest(allowListResultStringArray)
+                } else {  // The request didn't match any filter list 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.
@@ -5605,303 +5633,678 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
                         // 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)
-                    }
-                }
+                        // 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)
+                    }
+                }
+
+                // Reset the list of resource requests.
+                nestedScrollWebView.clearResourceRequests()
+
+                // Reset the requests counters.
+                nestedScrollWebView.resetRequestsCounters()
+
+                // Get the current page position.
+                val currentPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
+
+                // 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.  The nested scroll WebView current URL preserves any initial `view-source:`, and opposed to the method URL variable.
+                    urlEditText.setText(nestedScrollWebView.currentUrl)
+
+                    // Highlight the URL syntax.
+                    UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
+
+                    // Hide the keyboard.
+                    inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.windowToken, 0)
+                }
+
+                // Reset the list of host IP addresses.
+                nestedScrollWebView.currentIpAddresses = ""
+
+                // Get a URI for the current URL.
+                val currentUri = Uri.parse(url)
+
+                // Get the current domain name.
+                val currentDomainName = currentUri.host
+
+                // Get the IP addresses for the current domain.
+                if (!currentDomainName.isNullOrEmpty())
+                    GetHostIpAddressesCoroutine.checkPinnedMismatch(currentDomainName, nestedScrollWebView, supportFragmentManager, getString(R.string.pinned_mismatch))
+
+                // 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)
+
+                    // Set the icon if it is displayed in the AppBar.
+                    if (displayAdditionalAppBarIcons)
+                        optionsRefreshMenuItem.setIcon(R.drawable.close_blue)
+                }
+            }
+
+            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()
+
+                // 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)
+
+                    // Reset the icon if it is displayed in the app bar.
+                    if (displayAdditionalAppBarIcons)
+                        optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled)
+                }
+
+                // 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
+
+                // 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 {
+                        // Delete the main cache directory.
+                        Runtime.getRuntime().exec("rm -rf $privateDataDirectoryString/cache")
+                    } catch (exception: IOException) {
+                        // Do nothing if an error is thrown.
+                    }
+
+                    // 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.
+                    }
+                }
+
+                // 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 the current page position.
+                val currentPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
+
+                // 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()
+
+                        // Display the keyboard.
+                        inputMethodManager.showSoftInput(urlEditText, 0)
+
+                        // Apply the domain settings.  This clears any settings from the previous domain.
+                        applyDomainSettings(nestedScrollWebView, "", resetTab = true, reloadWebsite = false, loadUrl = false)
+
+                        // 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!!
+
+                            // Get the title text view from the tab.
+                            val tabTitleTextView = tabView.findViewById<TextView>(R.id.title_textview)
+
+                            // 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)
+
+                            // 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)
+
+                            // Highlight the URL syntax.
+                            UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
+                        }
+
+                        // 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!!
+
+                            // 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
+                        }
+                    }
+                }
+            }
+
+            // 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
+
+                // 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 pinned SSL certificate.
+                val (pinnedSslCertificateStringArray, pinnedSslCertificateDateArray) = nestedScrollWebView.getPinnedSslCertificate()
+
+                // 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])) {
+
+                    // 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
+
+                    // Instantiate an SSL certificate error alert dialog.
+                    val sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error, nestedScrollWebView.webViewFragmentId)
+
+                    // 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)))
+                    }
+                }
+            }
+        }
+
+        // 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 (pagePosition == 0) {  // The first page is being loaded.
+            // Set this nested scroll WebView as the current WebView.
+            currentWebView = nestedScrollWebView
+
+            // Get the intent that started the app.
+            val launchingIntent = intent
+
+            // Reset the intent.  This prevents a duplicate tab from being created on restart.
+            intent = Intent()
+
+            // Get the information from the intent.
+            val launchingIntentAction = launchingIntent.action
+            val launchingIntentUriData = launchingIntent.data
+            val launchingIntentStringExtra = launchingIntent.getStringExtra(Intent.EXTRA_TEXT)
+
+            // 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) {
+                    ""
+                }
+
+                // 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))
+            }
+
+            // 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!!)
+            }
+        } else {  // This is not the first tab.
+            // Load the URL.
+            loadUrl(nestedScrollWebView, urlString)
+
+            // Set the focus and display the keyboard if the URL is blank.
+            if (urlString == "") {
+                // Request focus for the URL text box.
+                urlEditText.requestFocus()
+
+                // Display the keyboard once the tab layout has settled.
+                tabLayout.post {
+                    inputMethodManager.showSoftInput(urlEditText, 0)
+                }
+            }
+        }
+    }
+
+    private fun loadBookmarksFolder() {
+        // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
+        bookmarksCursor = bookmarksDatabaseHelper!!.getBookmarksByDisplayOrder(currentBookmarksFolderId)
+
+        // 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 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)
+
+                // Get the favorite icon byte array from the cursor.
+                val favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndexOrThrow(FAVORITE_ICON))
+
+                // 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)
+
+                // Display the bitmap in the bookmark favorite icon.
+                bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap)
+
+                // Display the bookmark name from the cursor in the bookmark name text view.
+                bookmarkNameTextView.text = cursor.getString(cursor.getColumnIndexOrThrow(BOOKMARK_NAME))
+
+                // Make the font bold for folders.
+                if (cursor.getInt(cursor.getColumnIndexOrThrow(IS_FOLDER)) == 1)
+                    bookmarkNameTextView.typeface = Typeface.DEFAULT_BOLD
+                else  // Reset the font to default for normal bookmarks.
+                    bookmarkNameTextView.typeface = Typeface.DEFAULT
+            }
+        }
+
+        // Populate the list view with the adapter.
+        bookmarksListView.adapter = bookmarksCursorAdapter
+
+        // Set the bookmarks drawer title.
+        if (currentBookmarksFolderId == HOME_FOLDER_ID)  // The current bookmarks folder is the home folder.
+            bookmarksTitleTextView.setText(R.string.bookmarks)
+        else
+            bookmarksTitleTextView.text = bookmarksDatabaseHelper!!.getFolderName(currentBookmarksFolderId)
+    }
+
+    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)
+    }
+
+    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 = ""
+
+        // Check to see if the unformatted URL string is a valid URL.  Otherwise, convert it into a search.
+        if (unformattedUrlString.startsWith("content://") || unformattedUrlString.startsWith("view-source:")) {  // This is a content or source 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.
+
+            // 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"
+
+            // Initialize the unformatted URL.
+            var unformattedUrl: URL? = null
 
-                // Reset the list of resource requests.
-                nestedScrollWebView.clearResourceRequests()
+            // Convert the unformatted URL string to a URL.
+            try {
+                unformattedUrl = URL(unformattedUrlString)
+            } catch (exception: MalformedURLException) {
+                exception.printStackTrace()
+            }
 
-                // Reset the requests counters.
-                nestedScrollWebView.resetRequestsCounters()
+            // 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
 
-                // Get the current page position.
-                val currentPagePosition = webViewPagerAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
+            // Create a URI.
+            val uri = Uri.Builder()
 
-                // 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)
+            // Build the URI from the components of the URL.
+            uri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment)
 
-                    // Highlight the URL syntax.
-                    UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
+            // 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) {
+                ""
+            }
 
-                    // Hide the keyboard.
-                    inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.windowToken, 0)
-                }
+            // Add the base search URL.
+            urlString = searchURL + encodedSearchString
+        }
 
-                // Reset the list of host IP addresses.
-                nestedScrollWebView.currentIpAddresses = ""
+        // 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()
 
-                // Get a URI for the current URL.
-                val currentUri = Uri.parse(url)
+        // Make it so.
+        loadUrl(currentWebView!!, urlString)
+    }
 
-                // Get the current domain name.
-                val currentDomainName = currentUri.host
+    override fun navigateHistory(url: String, steps: Int) {
+        // Apply the domain settings.
+        applyDomainSettings(currentWebView!!, url, resetTab = false, reloadWebsite = false, loadUrl = false)
 
-                // Get the IP addresses for the current domain.
-                if ((currentDomainName != null) && currentDomainName.isNotEmpty())
-                    GetHostIpAddressesCoroutine.checkPinnedMismatch(currentDomainName, nestedScrollWebView, supportFragmentManager, getString(R.string.pinned_mismatch))
+        // Load the history entry.
+        currentWebView!!.goBackOrForward(steps)
 
-                // 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)
+        // Update the URL edit text after a delay.
+        updateUrlEditTextAfterDelay()
+    }
 
-                    // Set the icon if it is displayed in the AppBar.
-                    if (displayAdditionalAppBarIcons)
-                        optionsRefreshMenuItem.setIcon(R.drawable.close_blue)
-                }
-            }
+    override fun openFile(dialogFragment: DialogFragment) {
+        // Get the dialog.
+        val dialog = dialogFragment.dialog!!
 
-            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 handles for the views.
+        val fileNameEditText = dialog.findViewById<EditText>(R.id.file_name_edittext)
+        val mhtCheckBox = dialog.findViewById<CheckBox>(R.id.mht_checkbox)
 
-                // 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)
+        // Get the file path string.
+        val openFilePath = fileNameEditText.text.toString()
 
-                    // Reset the icon if it is displayed in the app bar.
-                    if (displayAdditionalAppBarIcons)
-                        optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled)
-                }
+        // Apply the domain settings.  This resets the favorite icon and removes any domain settings.
+        applyDomainSettings(currentWebView!!, openFilePath, resetTab = true, reloadWebsite = false, loadUrl = false)
 
-                // 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 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))
 
-                // Clear the cache, history, and logcat if Incognito Mode is enabled.
-                if (incognitoModeEnabled) {
-                    // Clear the cache.  `true` includes disk files.
-                    nestedScrollWebView.clearCache(true)
+                // Create a temporary MHT file.
+                val temporaryMhtFile = File.createTempFile(TEMPORARY_MHT_FILE, ".mht", cacheDir)
 
-                    // Clear the back/forward history.
-                    nestedScrollWebView.clearHistory()
+                // Get a file output stream for the temporary MHT file.
+                val temporaryMhtFileOutputStream = FileOutputStream(temporaryMhtFile)
 
-                    // 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.
-                    }
+                // Create a transfer byte array.
+                val transferByteArray = ByteArray(1024)
 
-                    // 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.
-                    }
-                }
+                // Create an integer to track the number of bytes read.
+                var bytesRead: Int
 
-                // 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.
-                }
+                // 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)
 
-                // Get the current page position.
-                val currentPagePosition = webViewPagerAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
+                // Flush the temporary MHT file output stream.
+                temporaryMhtFileOutputStream.flush()
 
-                // 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
+                // Close the streams.
+                temporaryMhtFileOutputStream.close()
+                mhtFileInputStream.close()
 
-                // Get the current tab.
-                val tab = tabLayout.getTabAt(currentPagePosition)
+                // 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)
+        }
+    }
 
-                // 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("")
+    private fun openWithApp(url: String) {
+        // Create an open with app intent with `ACTION_VIEW`.
+        val openWithAppIntent = Intent(Intent.ACTION_VIEW)
 
-                        // Request focus for the URL text box.
-                        urlEditText.requestFocus()
+        // Set the URI but not the MIME type.  This should open all available apps.
+        openWithAppIntent.data = Uri.parse(url)
 
-                        // Display the keyboard.
-                        inputMethodManager.showSoftInput(urlEditText, 0)
+        // Flag the intent to open in a new task.
+        openWithAppIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
 
-                        // Apply the domain settings.  This clears any settings from the previous domain.
-                        applyDomainSettings(nestedScrollWebView, "", resetTab = true, reloadWebsite = false, loadUrl = false)
+        // 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()
+        }
+    }
 
-                        // 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!!
+    private fun openWithBrowser(url: String) {
 
-                            // Get the title text view from the tab.
-                            val tabTitleTextView = tabView.findViewById<TextView>(R.id.title_textview)
+        // Create an open with browser intent with `ACTION_VIEW`.
+        val openWithBrowserIntent = Intent(Intent.ACTION_VIEW)
 
-                            // 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)
+        // Set the URI and the MIME type.  `"text/html"` should load browser options.
+        openWithBrowserIntent.setDataAndType(Uri.parse(url), "text/html")
 
-                            // 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)
+        // Flag the intent to open in a new task.
+        openWithBrowserIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
 
-                            // Highlight the URL syntax.
-                            UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
-                        }
+        // 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()
+        }
+    }
 
-                        // 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!!
+    override fun pinnedErrorGoBack() {
+        // Get the current web back forward list.
+        val webBackForwardList = currentWebView!!.copyBackForwardList()
 
-                            // Get the title text view from the tab.
-                            val tabTitleTextView = tabView.findViewById<TextView>(R.id.title_textview)
+        // Get the previous entry URL.
+        val previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex - 1).url
 
-                            // Set the title as the tab text.  Sometimes `onReceivedTitle()` is not called, especially when navigating history.
-                            tabTitleTextView.text = nestedScrollWebView.title
-                        }
-                    }
-                }
-            }
+        // Apply the domain settings.
+        applyDomainSettings(currentWebView!!, previousUrl, resetTab = false, reloadWebsite = false, loadUrl = false)
+
+        // Go back.
+        currentWebView!!.goBack()
 
-            // 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
+        // Update the URL edit text after a delay.
+        updateUrlEditTextAfterDelay()
+    }
 
-                // 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
+    private fun sanitizeUrl(urlString: String): String {
+        // Initialize a sanitized URL string.
+        var sanitizedUrlString = urlString
 
-                // Get the pinned SSL certificate.
-                val (pinnedSslCertificateStringArray, pinnedSslCertificateDateArray) = nestedScrollWebView.getPinnedSslCertificate()
+        // Sanitize tracking queries.
+        if (sanitizeTrackingQueries)
+            sanitizedUrlString = SanitizeUrlHelper.sanitizeTrackingQueries(sanitizedUrlString)
 
-                // 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])) {
+        // Sanitize AMP redirects.
+        if (sanitizeAmpRedirects)
+            sanitizedUrlString = SanitizeUrlHelper.sanitizeAmpRedirects(sanitizedUrlString)
 
-                    // 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
+        // Return the sanitized URL string.
+        return sanitizedUrlString
+    }
 
-                    // Instantiate an SSL certificate error alert dialog.
-                    val sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error, nestedScrollWebView.webViewFragmentId)
+    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!!
 
-                    // 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)))
-                    }
-                }
-            }
+            // 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()
         }
 
-        // 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
+        // Open the file picker.
+        saveUrlActivityResultLauncher.launch(fileNameString)
+    }
 
-            // Get the intent that started the app.
-            val launchingIntent = intent
+    private fun setCurrentWebView(pageNumber: Int) {
+        // Stop the swipe to refresh indicator if it is running
+        swipeRefreshLayout.isRefreshing = false
 
-            // Reset the intent.  This prevents a duplicate tab from being created on restart.
-            intent = Intent()
+        // Try to set the current WebView.  This will fail if the WebView has not yet been populated.
+        try {
+            // Get the WebView tab fragment.
+            val webViewTabFragment = webViewStateAdapter!!.getPageFragment(pageNumber)
 
-            // Get the information from the intent.
-            val launchingIntentAction = launchingIntent.action
-            val launchingIntentUriData = launchingIntent.data
-            val launchingIntentStringExtra = launchingIntent.getStringExtra(Intent.EXTRA_TEXT)
+            // Get the fragment view.
+            val webViewFragmentView = webViewTabFragment.view
 
-            // 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 current WebView.
+            currentWebView = webViewFragmentView!!.findViewById(R.id.nestedscroll_webview)
 
-                // 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))
+            // 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
             }
 
-            // 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!!)
-            }
+            // Set the cookie status.
+            cookieManager.setAcceptCookie(currentWebView!!.acceptCookies)
 
-            // 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 privacy icons.  `true` redraws the icons in the app bar.
+            updatePrivacyIcons(true)
 
-            // Set the focus and display the keyboard if the URL is blank.
-            if (urlString == "") {
-                // Request focus for the URL text box.
-                urlEditText.requestFocus()
+            // Get a handle for the input method manager.
+            val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
+
+            // Get the current URL.
+            val urlString = currentWebView!!.url
 
-                // Create a display keyboard handler.
-                val displayKeyboardHandler = Handler(Looper.getMainLooper())
+            // 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("")
+
+                    // Request focus for the URL text box.
+                    urlEditText.requestFocus()
 
-                // Create a display keyboard runnable.
-                val displayKeyboardRunnable = Runnable {
                     // Display the keyboard.
                     inputMethodManager.showSoftInput(urlEditText, 0)
+                } else {  // The WebView has a loaded URL.
+                    // Clear the focus from the URL text box.
+                    urlEditText.clearFocus()
+
+                    // Hide the soft keyboard.
+                    inputMethodManager.hideSoftInputFromWindow(currentWebView!!.windowToken, 0)
+
+                    // 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
+            }
+
+            // 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)
+            }
+        }  catch (exception: Exception) {
+            //  Try again in 50 milliseconds if the WebView has not yet been populated.
+            // Create a handler to set the current WebView.
+            val setCurrentWebViewHandler = Handler(Looper.getMainLooper())
 
-                // Display the keyboard after 100 milliseconds, which leaves enough time for the tab to transition.
-                displayKeyboardHandler.postDelayed(displayKeyboardRunnable, 100)
+            // Create a runnable to set the current WebView.
+            val setCurrentWebWebRunnable = Runnable {
+                // Set the current WebView.
+                setCurrentWebView(pageNumber)
             }
+
+            // Try setting the current WebView again after 50 milliseconds.
+            setCurrentWebViewHandler.postDelayed(setCurrentWebWebRunnable, 50)
         }
     }
 
+    // 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
+
+        // Update the bookmarks drawer pinned image view.
+        updateBookmarksDrawerPinnedImageView()
+    }
+
+    private fun updateBookmarksDrawerPinnedImageView() {
+        // Set the current icon.
+        if (bookmarksDrawerPinned)
+            bookmarksDrawerPinnedImageView.setImageResource(R.drawable.pin_selected)
+        else
+            bookmarksDrawerPinnedImageView.setImageResource(R.drawable.pin)
+    }
+
     private fun updateDomainsSettingsSet() {
         // Reset the domains settings set.
         domainsSettingsSet = HashSet()
@@ -5913,7 +6316,7 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
         val domainsCount = domainsCursor.count
 
         // Get the domain name column index.
-        val domainNameColumnIndex = domainsCursor.getColumnIndexOrThrow(DomainsDatabaseHelper.DOMAIN_NAME)
+        val domainNameColumnIndex = domainsCursor.getColumnIndexOrThrow(DOMAIN_NAME)
 
         // Populate the domain settings set.
         for (i in 0 until domainsCount) {
@@ -5927,4 +6330,72 @@ class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBook
         // Close the domains cursor.
         domainsCursor.close()
     }
+
+    override fun updateFontSize(dialogFragment: DialogFragment) {
+        // Get the dialog.
+        val dialog = dialogFragment.dialog!!
+
+        // Get a handle for the font size edit text.
+        val fontSizeEditText = dialog.findViewById<EditText>(R.id.font_size_edittext)
+
+        // Initialize the new font size variable with the current font size.
+        var newFontSize = currentWebView!!.settings.textZoom
+
+        // 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.
+        }
+
+        // Apply the new font size.
+        currentWebView!!.settings.textZoom = newFontSize
+    }
+
+    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()
+        }
+    }
+
+    fun updateUrlEditTextAfterDelay() {
+        // Create a handler to update the URL edit box.
+        val urlEditTextUpdateHandler = Handler(Looper.getMainLooper())
+
+        // Create a runnable to update the URL edit box.
+        val urlEditTextUpdateRunnable = Runnable {
+            // Update the URL edit text.
+            urlEditText.setText(currentWebView!!.url)
+
+            // Disable the wide viewport if the source is being viewed.
+            if (currentWebView!!.url!!.startsWith("view-source:"))
+                currentWebView!!.settings.useWideViewPort = false
+        }
+
+        // Update the URL edit text after 50 milliseconds, so that the WebView has enough time to navigate to the new URL.
+        urlEditTextUpdateHandler.postDelayed(urlEditTextUpdateRunnable, 50)
+    }
 }