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