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