]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/activities/MainWebViewActivity.kt
First wrong button text in View Headers in night theme. https://redmine.stoutner...
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / activities / 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(), 128, 128, 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) {
3889         // Get the dialog.
3890         val dialog = dialogFragment.dialog!!
3891
3892         // Get the views from the dialog fragment.
3893         val webpageFavoriteIconRadioButton = dialog.findViewById<RadioButton>(R.id.webpage_favorite_icon_radiobutton)
3894         val webpageFavoriteIconImageView = dialog.findViewById<ImageView>(R.id.webpage_favorite_icon_imageview)
3895         val customIconImageView = dialog.findViewById<ImageView>(R.id.custom_icon_imageview)
3896         val bookmarkNameEditText = dialog.findViewById<EditText>(R.id.bookmark_name_edittext)
3897         val bookmarkUrlEditText = dialog.findViewById<EditText>(R.id.bookmark_url_edittext)
3898
3899         // Extract the strings from the edit texts.
3900         val bookmarkNameString = bookmarkNameEditText.text.toString()
3901         val bookmarkUrlString = bookmarkUrlEditText.text.toString()
3902
3903         // Get the selected favorite icon drawable.
3904         val favoriteIconDrawable = if (webpageFavoriteIconRadioButton.isChecked)  // Use the webpage favorite icon.
3905             webpageFavoriteIconImageView.drawable
3906         else  // Use the custom icon.
3907             customIconImageView.drawable
3908
3909         // Cast the favorite icon bitmap to a bitmap drawable
3910         val favoriteIconBitmapDrawable = favoriteIconDrawable as BitmapDrawable
3911
3912         // Convert the favorite icon bitmap drawable to a bitmap.
3913         val favoriteIconBitmap = favoriteIconBitmapDrawable.bitmap
3914
3915         // Create a favorite icon byte array output stream.
3916         val favoriteIconByteArrayOutputStream = ByteArrayOutputStream()
3917
3918         // Convert the favorite icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
3919         favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream)
3920
3921         // Convert the favorite icon byte array stream to a byte array.
3922         val favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray()
3923
3924         // Display the new bookmark below the current items in the (0 indexed) list.
3925         val newBookmarkDisplayOrder = bookmarksListView.count
3926
3927         // Create the bookmark.
3928         bookmarksDatabaseHelper!!.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolderId, newBookmarkDisplayOrder, favoriteIconByteArray)
3929
3930         // Update the bookmarks cursor with the current contents of this folder.
3931         bookmarksCursor = bookmarksDatabaseHelper!!.getBookmarksByDisplayOrder(currentBookmarksFolderId)
3932
3933         // Update the list view.
3934         bookmarksCursorAdapter.changeCursor(bookmarksCursor)
3935
3936         // Scroll to the new bookmark.
3937         bookmarksListView.setSelection(newBookmarkDisplayOrder)
3938     }
3939
3940     override fun createBookmarkFolder(dialogFragment: DialogFragment) {
3941         // Get the dialog.
3942         val dialog = dialogFragment.dialog!!
3943
3944         // Get handles for the views in the dialog fragment.
3945         val defaultFolderIconRadioButton = dialog.findViewById<RadioButton>(R.id.default_folder_icon_radiobutton)
3946         val defaultFolderIconImageView = dialog.findViewById<ImageView>(R.id.default_folder_icon_imageview)
3947         val webpageFavoriteIconRadioButton = dialog.findViewById<RadioButton>(R.id.webpage_favorite_icon_radiobutton)
3948         val webpageFavoriteIconImageView = dialog.findViewById<ImageView>(R.id.webpage_favorite_icon_imageview)
3949         val customIconImageView = dialog.findViewById<ImageView>(R.id.custom_icon_imageview)
3950         val folderNameEditText = dialog.findViewById<EditText>(R.id.folder_name_edittext)
3951
3952         // Get new folder name string.
3953         val folderNameString = folderNameEditText.text.toString()
3954
3955         // Set the folder icon bitmap according to the dialog.
3956         val folderIconDrawable = if (defaultFolderIconRadioButton.isChecked)  // Use the default folder icon.
3957             defaultFolderIconImageView.drawable
3958         else if (webpageFavoriteIconRadioButton.isChecked)  // Use the webpage favorite icon.
3959             webpageFavoriteIconImageView.drawable
3960         else  // Use the custom icon.
3961             customIconImageView.drawable
3962
3963         // Cast the folder icon bitmap to a bitmap drawable.
3964         val folderIconBitmapDrawable = folderIconDrawable as BitmapDrawable
3965
3966         // Convert the folder icon bitmap drawable to a bitmap.
3967         val folderIconBitmap = folderIconBitmapDrawable.bitmap
3968
3969         // Create a folder icon byte array output stream.
3970         val folderIconByteArrayOutputStream = ByteArrayOutputStream()
3971
3972         // Convert the folder icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
3973         folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream)
3974
3975         // Convert the folder icon byte array stream to a byte array.
3976         val folderIconByteArray = folderIconByteArrayOutputStream.toByteArray()
3977
3978         // Move all the bookmarks down one in the display order.
3979         for (i in 0 until bookmarksListView.count) {
3980             // Get the bookmark database id.
3981             val databaseId = bookmarksListView.getItemIdAtPosition(i).toInt()
3982
3983             // Move the bookmark down one slot.
3984             bookmarksDatabaseHelper!!.updateDisplayOrder(databaseId, displayOrder = i + 1)
3985         }
3986
3987         // Create the folder, which will be placed at the top of the list view.
3988         bookmarksDatabaseHelper!!.createFolder(folderNameString, currentBookmarksFolderId, displayOrder = 0, folderIconByteArray)
3989
3990         // Update the bookmarks cursor with the current contents of this folder.
3991         bookmarksCursor = bookmarksDatabaseHelper!!.getBookmarksByDisplayOrder(currentBookmarksFolderId)
3992
3993         // Update the list view.
3994         bookmarksCursorAdapter.changeCursor(bookmarksCursor)
3995
3996         // Scroll to the new folder.
3997         bookmarksListView.setSelection(0)
3998     }
3999
4000     private fun exitFullScreenVideo() {
4001         // Re-enable the screen timeout.
4002         fullScreenVideoFrameLayout.keepScreenOn = false
4003
4004         // Unset the full screen video flag.
4005         displayingFullScreenVideo = false
4006
4007         // Remove all the views from the full screen video frame layout.
4008         fullScreenVideoFrameLayout.removeAllViews()
4009
4010         // Hide the full screen video frame layout.
4011         fullScreenVideoFrameLayout.visibility = View.GONE
4012
4013         // Enable the sliding drawers.
4014         drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED)
4015
4016         // Show the coordinator layout.
4017         coordinatorLayout.visibility = View.VISIBLE
4018
4019         // Apply the appropriate full screen mode flags.
4020         if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {  // Privacy Browser is currently in full screen browsing mode.
4021             // Hide the app bar if specified.
4022             if (hideAppBar) {
4023                 // Hide the tab linear layout.
4024                 tabsLinearLayout.visibility = View.GONE
4025
4026                 // Hide the app bar.
4027                 appBar.hide()
4028             }
4029
4030             /* Hide the system bars.
4031              * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4032              * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4033              * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4034              * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4035              */
4036
4037             // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4038             @Suppress("DEPRECATION")
4039             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
4040         } else {  // Switch to normal viewing mode.
4041             // Remove the `SYSTEM_UI` flags from the root frame layout.  The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4042             @Suppress("DEPRECATION")
4043             rootFrameLayout.systemUiVisibility = 0
4044         }
4045     }
4046
4047     // The view parameter cannot be removed because it is called from the layout onClick.
4048     fun findNextOnPage(@Suppress("UNUSED_PARAMETER")view: View?) {
4049         // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
4050         currentWebView!!.findNext(true)
4051     }
4052
4053     // The view parameter cannot be removed because it is called from the layout onClick.
4054     fun findPreviousOnPage(@Suppress("UNUSED_PARAMETER")view: View?) {
4055         // Go to the previous highlighted phrase on the page.  `false` goes backwards instead of forwards.
4056         currentWebView!!.findNext(false)
4057     }
4058
4059     override fun finishedPopulatingFilterLists(combinedFilterLists: ArrayList<ArrayList<List<Array<String>>>>) {
4060         // Store the filter lists.
4061         easyList = combinedFilterLists[0]
4062         easyPrivacy = combinedFilterLists[1]
4063         fanboysAnnoyanceList = combinedFilterLists[2]
4064         fanboysSocialList = combinedFilterLists[3]
4065         ultraList = combinedFilterLists[4]
4066         ultraPrivacy = combinedFilterLists[5]
4067
4068         // Check to see if the activity has been restarted with a saved state.
4069         if ((savedStateArrayList == null) || (savedStateArrayList!!.size == 0)) {  // The activity has not been restarted or it was restarted on start to change the theme.
4070             // Add the first tab.
4071             addNewPage(urlString = "", adjacent = false, moveToTab = false)
4072         } else {  // The activity has been restarted with a saved state.
4073             // Restore each tab.
4074             for (i in savedStateArrayList!!.indices) {
4075                 // Add a new tab.
4076                 tabLayout.addTab(tabLayout.newTab())
4077
4078                 // Get the new tab.
4079                 val newTab = tabLayout.getTabAt(i)!!
4080
4081                 // Set a custom view on the new tab.
4082                 newTab.setCustomView(R.layout.tab_custom_view)
4083
4084                 // Add the new page.
4085                 webViewStateAdapter!!.restorePage(savedStateArrayList!![i], savedNestedScrollWebViewStateArrayList!![i])
4086             }
4087
4088             // Reset the saved state variables.
4089             savedStateArrayList = null
4090             savedNestedScrollWebViewStateArrayList = null
4091
4092             // Get the intent that started the app.
4093             val intent = intent
4094
4095             // Reset the intent.  This prevents a duplicate tab from being created on restart.
4096             setIntent(Intent())
4097
4098             // Get the information from the intent.
4099             val intentAction = intent.action
4100             val intentUriData = intent.data
4101             val intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT)
4102
4103             // Determine if this is a web search.
4104             val isWebSearch = (intentAction != null) && (intentAction == Intent.ACTION_WEB_SEARCH)
4105
4106             // 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.
4107             if ((intentUriData != null) || (intentStringExtra != null) || isWebSearch) {  // A new tab is being loaded.
4108                 // Get the URL string.
4109                 val urlString = if (isWebSearch) {  // The intent is a web search.
4110                     // Sanitize the search input.
4111                     val encodedSearchString: String = try {
4112                         URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8")
4113                     } catch (exception: UnsupportedEncodingException) {
4114                         ""
4115                     }
4116
4117                     // Add the base search URL.
4118                     searchURL + encodedSearchString
4119                 } else { // The intent contains a URL formatted as a URI or a URL in the string extra.
4120                     // Get the URL string.
4121                     intentUriData?.toString() ?: intentStringExtra!!
4122                 }
4123
4124                 // Add a new tab if specified in the preferences.
4125                 if (sharedPreferences.getBoolean(getString(R.string.open_intents_in_new_tab_key), true)) {  // Load the URL in a new tab.
4126                     // Set the loading new intent flag.
4127                     loadingNewIntent = true
4128
4129                     // Add a new tab.
4130                     addNewPage(urlString, adjacent = false, moveToTab = true)
4131                 } else {  // Load the URL in the current tab.
4132                     // Make it so.
4133                     loadUrl(currentWebView!!, urlString)
4134                 }
4135             } else {  // A new tab is not being loaded.
4136                 // Restore the selected tab position.
4137                 if (savedTabPosition == 0) {  // The first tab is selected.
4138                     // Set the first page as the current WebView.
4139                     setCurrentWebView(0)
4140                 } else {  // The first tab is not selected.
4141                     // Select the tab when the layout has finished populating.
4142                     tabLayout.post {
4143                         // Get a handle for the tab.
4144                         val tab = tabLayout.getTabAt(savedTabPosition)!!
4145
4146                         // Select the tab.
4147                         tab.select()
4148                     }
4149                 }
4150             }
4151         }
4152     }
4153
4154     // Remove the warning that `OnTouchListener()` needs to override `performClick()`, as the only purpose of setting the `OnTouchListener()` is to make it do nothing.
4155     @SuppressLint("ClickableViewAccessibility")
4156     private fun initializeApp() {
4157         // Get a handle for the input method.
4158         val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
4159
4160         // Initialize the color spans for highlighting the URLs.
4161         initialGrayColorSpan = ForegroundColorSpan(getColor(R.color.gray_500))
4162         finalGrayColorSpan = ForegroundColorSpan(getColor(R.color.gray_500))
4163         redColorSpan = ForegroundColorSpan(getColor(R.color.red_text))
4164
4165         // Remove the formatting from the URL edit text when the user is editing the text.
4166         urlEditText.onFocusChangeListener = View.OnFocusChangeListener { _: View?, hasFocus: Boolean ->
4167             if (hasFocus) {  // The user is editing the URL text box.
4168                 // Remove the syntax highlighting.
4169                 urlEditText.text.removeSpan(redColorSpan)
4170                 urlEditText.text.removeSpan(initialGrayColorSpan)
4171                 urlEditText.text.removeSpan(finalGrayColorSpan)
4172             } else {  // The user has stopped editing the URL text box.
4173                 // Move to the beginning of the string.
4174                 urlEditText.setSelection(0)
4175
4176                 // Reapply the syntax highlighting.
4177                 UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
4178             }
4179         }
4180
4181         // Set the go button on the keyboard to load the URL in url text box.
4182         urlEditText.setOnKeyListener { _: View?, keyCode: Int, keyEvent: KeyEvent ->
4183             // If the event is a key-down event on the `enter` button, load the URL.
4184             if ((keyEvent.action == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {  // The enter key was pressed.
4185                 // Load the URL.
4186                 loadUrlFromTextBox()
4187
4188                 // Consume the event.
4189                 return@setOnKeyListener true
4190             } else {  // Some other key was pressed.
4191                 // Do not consume the event.
4192                 return@setOnKeyListener false
4193             }
4194         }
4195
4196         // Create an Orbot status broadcast receiver.
4197         orbotStatusBroadcastReceiver = object : BroadcastReceiver() {
4198             override fun onReceive(context: Context, intent: Intent) {
4199                 // Get the content of the status message.
4200                 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS")!!
4201
4202                 // If Privacy Browser is waiting on the proxy, load the website now that Orbot is connected.
4203                 if ((orbotStatus == ProxyHelper.ORBOT_STATUS_ON) && waitingForProxy) {
4204                     // Reset the waiting for proxy status.
4205                     waitingForProxy = false
4206
4207                     // Get a list of the current fragments.
4208                     val fragmentList = supportFragmentManager.fragments
4209
4210                     // Check each fragment to see if it is a waiting for proxy dialog.  Sometimes more than one is displayed.
4211                     for (i in fragmentList.indices) {
4212                         // Get the fragment tag.
4213                         val fragmentTag = fragmentList[i].tag
4214
4215                         // Check to see if it is the waiting for proxy dialog.
4216                         if (fragmentTag != null && fragmentTag == getString(R.string.waiting_for_proxy_dialog)) {
4217                             // Dismiss the waiting for proxy dialog.
4218                             (fragmentList[i] as DialogFragment).dismiss()
4219                         }
4220                     }
4221
4222                     // Reload existing URLs and load any URLs that are waiting for the proxy.
4223                     for (i in 0 until webViewStateAdapter!!.itemCount) {
4224                         // Get the WebView tab fragment.
4225                         val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
4226
4227                         // Get the fragment view.
4228                         val fragmentView = webViewTabFragment.view
4229
4230                         // Only process the WebViews if they exist.
4231                         if (fragmentView != null) {
4232                             // Get the nested scroll WebView from the tab fragment.
4233                             val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
4234
4235                             // Get the waiting for proxy URL string.
4236                             val waitingForProxyUrlString = nestedScrollWebView.waitingForProxyUrlString
4237
4238                             // Load the pending URL if it exists.
4239                             if (waitingForProxyUrlString.isNotEmpty()) {  // A URL is waiting to be loaded.
4240                                 // Load the URL.
4241                                 loadUrl(nestedScrollWebView, waitingForProxyUrlString)
4242
4243                                 // Reset the waiting for proxy URL string.
4244                                 nestedScrollWebView.waitingForProxyUrlString = ""
4245                             } else {  // No URL is waiting to be loaded.
4246                                 // Reload the existing URL.
4247                                 nestedScrollWebView.reload()
4248                             }
4249                         }
4250                     }
4251                 }
4252             }
4253         }
4254
4255         // Register the Orbot status broadcast receiver.  `ContextCompat` must be used until the minimum API >= 34.
4256         ContextCompat.registerReceiver(this, orbotStatusBroadcastReceiver, IntentFilter("org.torproject.android.intent.action.STATUS"), ContextCompat.RECEIVER_EXPORTED)
4257
4258         // Get handles for views that need to be modified.
4259         val bookmarksHeaderLinearLayout = findViewById<LinearLayout>(R.id.bookmarks_header_linearlayout)
4260         val launchBookmarksActivityFab = findViewById<FloatingActionButton>(R.id.launch_bookmarks_activity_fab)
4261         val createBookmarkFolderFab = findViewById<FloatingActionButton>(R.id.create_bookmark_folder_fab)
4262         val createBookmarkFab = findViewById<FloatingActionButton>(R.id.create_bookmark_fab)
4263
4264         // Handle tab selections.
4265         tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
4266             override fun onTabSelected(tab: TabLayout.Tab) {
4267                 // Close the find on page bar if it is open.
4268                 closeFindOnPage(null)
4269
4270                 // 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.
4271                 webViewViewPager2.post {
4272                     // Select the same page in the view pager.
4273                     webViewViewPager2.currentItem = tab.position
4274
4275                     // 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>
4276                     tabLayout.post {
4277                         setCurrentWebView(tab.position)
4278                     }
4279                 }
4280             }
4281
4282             override fun onTabUnselected(tab: TabLayout.Tab) {}
4283
4284             override fun onTabReselected(tab: TabLayout.Tab) {
4285                 // Only display the view SSL certificate dialog if the current WebView is not null.
4286                 // This can happen if the tab is programmatically reselected while the app is being restarted and is not yet populated.
4287                 if (currentWebView != null) {
4288                     // Instantiate the View SSL Certificate dialog.
4289                     val viewSslCertificateDialogFragment: DialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView!!.webViewFragmentId, currentWebView!!.getFavoriteIcon())
4290
4291                     // Display the View SSL Certificate dialog.
4292                     viewSslCertificateDialogFragment.show(supportFragmentManager, getString(R.string.view_ssl_certificate))
4293                 }
4294             }
4295         })
4296
4297         // Set a touch listener on the bookmarks header linear layout so that touches don't pass through to the button underneath.
4298         bookmarksHeaderLinearLayout.setOnTouchListener { _: View?, _: MotionEvent? -> true }
4299
4300         // Set the launch bookmarks activity floating action button to launch the bookmarks activity.
4301         launchBookmarksActivityFab.setOnClickListener {
4302             // Get a copy of the favorite icon bitmap.
4303             val currentFavoriteIconBitmap = currentWebView!!.getFavoriteIcon()
4304
4305             // Create a favorite icon byte array output stream.
4306             val currentFavoriteIconByteArrayOutputStream = ByteArrayOutputStream()
4307
4308             // Convert the favorite icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
4309             currentFavoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, currentFavoriteIconByteArrayOutputStream)
4310
4311             // Convert the favorite icon byte array stream to a byte array.
4312             val currentFavoriteIconByteArray = currentFavoriteIconByteArrayOutputStream.toByteArray()
4313
4314             // Create an intent to launch the bookmarks activity.
4315             val bookmarksIntent = Intent(applicationContext, BookmarksActivity::class.java)
4316
4317             // Add the extra information to the intent.
4318             bookmarksIntent.putExtra(CURRENT_FOLDER_ID, currentBookmarksFolderId)
4319             bookmarksIntent.putExtra(CURRENT_TITLE, currentWebView!!.title)
4320             bookmarksIntent.putExtra(CURRENT_URL, currentWebView!!.url)
4321             bookmarksIntent.putExtra(CURRENT_FAVORITE_ICON_BYTE_ARRAY, currentFavoriteIconByteArray)
4322
4323             // Make it so.
4324             startActivity(bookmarksIntent)
4325         }
4326
4327         // Set the create new bookmark folder floating action button to display an alert dialog.
4328         createBookmarkFolderFab.setOnClickListener {
4329             // Create a create bookmark folder dialog.
4330             val createBookmarkFolderDialog: DialogFragment = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView!!.getFavoriteIcon())
4331
4332             // Show the create bookmark folder dialog.
4333             createBookmarkFolderDialog.show(supportFragmentManager, getString(R.string.create_folder))
4334         }
4335
4336         // Set the create new bookmark floating action button to display an alert dialog.
4337         createBookmarkFab.setOnClickListener {
4338             // Instantiate the create bookmark dialog.
4339             val createBookmarkDialog: DialogFragment = CreateBookmarkDialog.createBookmark(currentWebView!!.url!!, currentWebView!!.title!!, currentWebView!!.getFavoriteIcon())
4340
4341             // Display the create bookmark dialog.
4342             createBookmarkDialog.show(supportFragmentManager, getString(R.string.create_bookmark))
4343         }
4344
4345         // Search for the string on the page whenever a character changes in the find on page edit text.
4346         findOnPageEditText.addTextChangedListener(object : TextWatcher {
4347             override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
4348
4349             override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
4350
4351             override fun afterTextChanged(s: Editable) {
4352                 // 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.
4353                 currentWebView?.findAllAsync(findOnPageEditText.text.toString())
4354             }
4355         })
4356
4357         // Set the `check mark` button for the find on page edit text keyboard to close the soft keyboard.
4358         findOnPageEditText.setOnKeyListener { _: View?, keyCode: Int, keyEvent: KeyEvent ->
4359             if ((keyEvent.action == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {  // The `enter` key was pressed.
4360                 // Hide the soft keyboard.
4361                 inputMethodManager.hideSoftInputFromWindow(currentWebView!!.windowToken, 0)
4362
4363                 // Consume the event.
4364                 return@setOnKeyListener true
4365             } else {  // A different key was pressed.
4366                 // Do not consume the event.
4367                 return@setOnKeyListener false
4368             }
4369         }
4370
4371         // Implement swipe to refresh.
4372         swipeRefreshLayout.setOnRefreshListener {
4373             // Reload the website.
4374             currentWebView!!.reload()
4375         }
4376
4377         // Store the default progress view offsets.
4378         defaultProgressViewStartOffset = swipeRefreshLayout.progressViewStartOffset
4379         defaultProgressViewEndOffset = swipeRefreshLayout.progressViewEndOffset
4380
4381         // Set the refresh color scheme according to the theme.
4382         swipeRefreshLayout.setColorSchemeResources(R.color.blue_text)
4383
4384         // Initialize a color background typed value.
4385         val colorBackgroundTypedValue = TypedValue()
4386
4387         // Get the color background from the theme.
4388         theme.resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true)
4389
4390         // Get the color background int from the typed value.
4391         val colorBackgroundInt = colorBackgroundTypedValue.data
4392
4393         // Set the swipe refresh background color.
4394         swipeRefreshLayout.setProgressBackgroundColorSchemeColor(colorBackgroundInt)
4395
4396         // Set the drawer titles, which identify the drawer layouts in accessibility mode.
4397         drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer))
4398         drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks))
4399
4400         // Load the bookmarks folder.
4401         loadBookmarksFolder()
4402
4403         // Handle clicks on bookmarks.
4404         bookmarksListView.onItemClickListener = AdapterView.OnItemClickListener { _: AdapterView<*>?, _: View?, _: Int, id: Long ->
4405             // Convert the id from long to int to match the format of the bookmarks database.
4406             val databaseId = id.toInt()
4407
4408             // Get the bookmark cursor for this ID.
4409             val bookmarkCursor = bookmarksDatabaseHelper!!.getBookmark(databaseId)
4410
4411             // Move the bookmark cursor to the first row.
4412             bookmarkCursor.moveToFirst()
4413
4414             // Act upon the bookmark according to the type.
4415             if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndexOrThrow(IS_FOLDER)) == 1) {  // The selected bookmark is a folder.
4416                 // Store the folder ID.
4417                 currentBookmarksFolderId = bookmarkCursor.getLong(bookmarkCursor.getColumnIndexOrThrow(FOLDER_ID))
4418
4419                 // Load the new folder.
4420                 loadBookmarksFolder()
4421             } else {  // The selected bookmark is not a folder.
4422                 // Load the bookmark URL.
4423                 loadUrl(currentWebView!!, bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BOOKMARK_URL)))
4424
4425                 // Close the bookmarks drawer if it is not pinned.
4426                 if (!bookmarksDrawerPinned)
4427                     drawerLayout.closeDrawer(GravityCompat.END)
4428             }
4429
4430             // Close the cursor.
4431             bookmarkCursor.close()
4432         }
4433
4434         // Handle long-presses on bookmarks.
4435         bookmarksListView.onItemLongClickListener = AdapterView.OnItemLongClickListener { _: AdapterView<*>?, _: View?, _: Int, id: Long ->
4436             // Convert the database ID from `long` to `int`.
4437             val databaseId = id.toInt()
4438
4439             // Run the commands associated with the type.
4440             if (bookmarksDatabaseHelper!!.isFolder(databaseId)) {  // The bookmark is a folder.
4441                 // Get the folder ID.
4442                 val folderId = bookmarksDatabaseHelper!!.getFolderId(databaseId)
4443
4444                 // Get a cursor of all the bookmarks in the folder.
4445                 val bookmarksCursor = bookmarksDatabaseHelper!!.getFolderBookmarks(folderId)
4446
4447                 // Move to the first entry in the cursor.
4448                 bookmarksCursor.moveToFirst()
4449
4450                 // Open each bookmark
4451                 for (i in 0 until bookmarksCursor.count) {
4452                     // Load the bookmark in a new tab, moving to the tab for the first bookmark if the drawer is not pinned.
4453                     addNewPage(bookmarksCursor.getString(bookmarksCursor.getColumnIndexOrThrow(BOOKMARK_URL)), adjacent = false, moveToTab = !bookmarksDrawerPinned && (i == 0))
4454
4455                     // Move to the next bookmark.
4456                     bookmarksCursor.moveToNext()
4457                 }
4458
4459                 // Close the cursor.
4460                 bookmarksCursor.close()
4461             } else {  // The bookmark is not a folder.
4462                 // Get the bookmark cursor for this ID.
4463                 val bookmarkCursor = bookmarksDatabaseHelper!!.getBookmark(databaseId)
4464
4465                 // Move the bookmark cursor to the first row.
4466                 bookmarkCursor.moveToFirst()
4467
4468                 // Load the bookmark in a new tab and move to the tab if the drawer is not pinned.
4469                 addNewPage(bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BOOKMARK_URL)), adjacent = true, moveToTab = !bookmarksDrawerPinned)
4470
4471                 // Close the cursor.
4472                 bookmarkCursor.close()
4473             }
4474
4475             // Close the bookmarks drawer if it is not pinned.
4476             if (!bookmarksDrawerPinned)
4477                 drawerLayout.closeDrawer(GravityCompat.END)
4478
4479             // Consume the event.
4480             true
4481         }
4482
4483         // The drawer listener is used to update the navigation menu.
4484         drawerLayout.addDrawerListener(object : DrawerLayout.DrawerListener {
4485             override fun onDrawerSlide(drawerView: View, slideOffset: Float) {}
4486
4487             override fun onDrawerOpened(drawerView: View) {}
4488
4489             override fun onDrawerClosed(drawerView: View) {}
4490
4491             override fun onDrawerStateChanged(newState: Int) {
4492                 if (newState == DrawerLayout.STATE_SETTLING || newState == DrawerLayout.STATE_DRAGGING) {  // A drawer is opening or closing.
4493                     // Update the navigation menu items if the WebView is not null.
4494                     if (currentWebView != null) {
4495                         // Set the enabled status of the menu items.
4496                         navigationBackMenuItem.isEnabled = currentWebView!!.canGoBack()
4497                         navigationForwardMenuItem.isEnabled = currentWebView!!.canGoForward()
4498                         navigationScrollToBottomMenuItem.isEnabled = (currentWebView!!.canScrollVertically(-1) || currentWebView!!.canScrollVertically(1))
4499                         navigationHistoryMenuItem.isEnabled = currentWebView!!.canGoBack() || currentWebView!!.canGoForward()
4500
4501                         // Update the scroll menu item.
4502                         if (currentWebView!!.scrollY == 0) {  // The WebView is scrolled to the top.
4503                             // Set the title.
4504                             navigationScrollToBottomMenuItem.title = getString(R.string.scroll_to_bottom)
4505
4506                             // Set the icon.
4507                             navigationScrollToBottomMenuItem.icon = AppCompatResources.getDrawable(applicationContext, R.drawable.move_down_enabled)
4508                         } else {  // The WebView is not scrolled to the top.
4509                             // Set the title.
4510                             navigationScrollToBottomMenuItem.title = getString(R.string.scroll_to_top)
4511
4512                             // Set the icon.
4513                             navigationScrollToBottomMenuItem.icon = AppCompatResources.getDrawable(applicationContext, R.drawable.move_up_enabled)
4514                         }
4515
4516                         // Display the number of blocked requests.
4517                         navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + currentWebView!!.getRequestsCount(BLOCKED_REQUESTS)
4518
4519                         // Hide the keyboard (if displayed).
4520                         inputMethodManager.hideSoftInputFromWindow(currentWebView!!.windowToken, 0)
4521                     }
4522
4523                     // 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.
4524                     urlEditText.clearFocus()
4525
4526                     // 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.
4527                     // Clearing the focus from the WebView removes any text selection markers and context menus, which otherwise draw above the open drawers.
4528                     currentWebView?.clearFocus()
4529
4530                     if (bottomAppBar && navigationDrawerFirstView) {
4531                         // Reset the navigation drawer first view flag.
4532                         navigationDrawerFirstView = false
4533
4534                         // Get a handle for the navigation recycler view.
4535                         val navigationRecyclerView = navigationView.getChildAt(0) as RecyclerView
4536
4537                         // Get the navigation linear layout manager.
4538                         val navigationLinearLayoutManager = navigationRecyclerView.layoutManager as LinearLayoutManager
4539
4540                         // Scroll the navigation drawer to the bottom.
4541                         navigationLinearLayoutManager.scrollToPositionWithOffset(13, 0)
4542                     }
4543                 }
4544             }
4545         })
4546
4547         // Inflate a bare WebView to get the default user agent.  It is not used to render content on the screen.
4548         @SuppressLint("InflateParams") val webViewLayout = layoutInflater.inflate(R.layout.bare_webview, null, false)
4549
4550         // Get a handle for the WebView.
4551         val bareWebView = webViewLayout.findViewById<WebView>(R.id.bare_webview)
4552
4553         // Store the default user agent.
4554         webViewDefaultUserAgent = bareWebView.settings.userAgentString
4555
4556         // Destroy the bare WebView.
4557         bareWebView.destroy()
4558
4559         // Update the domains settings set.
4560         updateDomainsSettingsSet()
4561
4562         // Instantiate the check filter list helper.
4563         checkFilterListHelper = CheckFilterListHelper()
4564     }
4565
4566     @SuppressLint("ClickableViewAccessibility")
4567     override fun initializeWebView(nestedScrollWebView: NestedScrollWebView, pagePosition: Int, progressBar: ProgressBar, urlString: String, restoringState: Boolean) {
4568         // Get the WebView theme.
4569         val webViewTheme = sharedPreferences.getString(getString(R.string.webview_theme_key), getString(R.string.webview_theme_default_value))
4570
4571         // Get the WebView theme entry values string array.
4572         val webViewThemeEntryValuesStringArray = resources.getStringArray(R.array.webview_theme_entry_values)
4573
4574         // Set the WebView theme if algorithmic darkening is supported.
4575         if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {
4576             // Set the WebView them.  A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
4577             if (webViewTheme == webViewThemeEntryValuesStringArray[1]) {  // The light theme is selected.
4578                 // Turn off algorithmic darkening.
4579                 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
4580
4581                 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
4582                 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
4583                 nestedScrollWebView.visibility = View.VISIBLE
4584             } else if (webViewTheme == webViewThemeEntryValuesStringArray[2]) {  // The dark theme is selected.
4585                 // Turn on algorithmic darkening.
4586                 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
4587             } else {  // The system default theme is selected.
4588                 // Get the current theme status.
4589                 val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
4590
4591                 // Set the algorithmic darkening according to the current system theme status.
4592                 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {  // The system is in day mode.
4593                     // Turn off algorithmic darkening.
4594                     WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
4595
4596                     // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
4597                     // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
4598                     nestedScrollWebView.visibility = View.VISIBLE
4599                 } else {  // The system is in night mode.
4600                     // Turn on algorithmic darkening.
4601                     WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
4602                 }
4603             }
4604         }
4605
4606         // Get a handle for the input method manager.
4607         val inputMethodManager = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
4608
4609         // Set the app bar scrolling.
4610         nestedScrollWebView.isNestedScrollingEnabled = scrollAppBar
4611
4612         // Allow pinch to zoom.
4613         nestedScrollWebView.settings.builtInZoomControls = true
4614
4615         // Hide zoom controls.
4616         nestedScrollWebView.settings.displayZoomControls = false
4617
4618         // Don't allow mixed content (HTTP and HTTPS) on the same website.
4619         nestedScrollWebView.settings.mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW
4620
4621         // Set the WebView to load in overview mode (zoomed out to the maximum width).
4622         nestedScrollWebView.settings.loadWithOverviewMode = true
4623
4624         // Explicitly disable geolocation.
4625         nestedScrollWebView.settings.setGeolocationEnabled(false)
4626
4627         // Allow loading of file:// URLs.  This is necessary for opening MHT web archives, which are copied into a temporary cache location.
4628         nestedScrollWebView.settings.allowFileAccess = true
4629
4630         // Create a double-tap gesture detector to toggle full-screen mode.
4631         val doubleTapGestureDetector = GestureDetector(this, object : GestureDetector.SimpleOnGestureListener() {
4632             // Override `onDoubleTap()`.  All other events are handled using the default settings.
4633             override fun onDoubleTap(motionEvent: MotionEvent): Boolean {
4634                 return if (fullScreenBrowsingModeEnabled) {  // Only process the double-tap if full screen browsing mode is enabled.
4635                     // Toggle the full screen browsing mode tracker.
4636                     inFullScreenBrowsingMode = !inFullScreenBrowsingMode
4637
4638                     // Toggle the full screen browsing mode.
4639                     if (inFullScreenBrowsingMode) {  // Switch to full screen mode.
4640                         // Hide the app bar if specified.
4641                         if (hideAppBar) {  // App bar hiding is enabled.
4642                             // Close the find on page bar if it is visible.
4643                             closeFindOnPage(null)
4644
4645                             // Hide the tab linear layout.
4646                             tabsLinearLayout.visibility = View.GONE
4647
4648                             // Hide the app bar.
4649                             appBar.hide()
4650
4651                             // Set layout and scrolling parameters according to the position of the app bar.
4652                             if (bottomAppBar) {  // The app bar is at the bottom.
4653                                 // Reset the WebView padding to fill the available space.
4654                                 swipeRefreshLayout.setPadding(0, 0, 0, 0)
4655                             } else {  // The app bar is at the top.
4656                                 // Check to see if the app bar is normally scrolled.
4657                                 if (scrollAppBar) {  // The app bar is scrolled when it is displayed.
4658                                     // Get the swipe refresh layout parameters.
4659                                     val swipeRefreshLayoutParams = swipeRefreshLayout.layoutParams as CoordinatorLayout.LayoutParams
4660
4661                                     // Remove the off-screen scrolling layout.
4662                                     swipeRefreshLayoutParams.behavior = null
4663                                 } else {  // The app bar is not scrolled when it is displayed.
4664                                     // Remove the padding from the top of the swipe refresh layout.
4665                                     swipeRefreshLayout.setPadding(0, 0, 0, 0)
4666
4667                                     // The swipe refresh circle must be moved above the now removed status bar location.
4668                                     swipeRefreshLayout.setProgressViewOffset(false, -200, defaultProgressViewEndOffset)
4669                                 }
4670                             }
4671                         } else {  // App bar hiding is not enabled.
4672                             // Adjust the UI for the bottom app bar.
4673                             if (bottomAppBar) {
4674                                 // Adjust the UI according to the scrolling of the app bar.
4675                                 if (scrollAppBar) {
4676                                     // Reset the WebView padding to fill the available space.
4677                                     swipeRefreshLayout.setPadding(0, 0, 0, 0)
4678                                 } else {
4679                                     // Move the WebView above the app bar layout.
4680                                     swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
4681                                 }
4682                             }
4683                         }
4684
4685                         /* Hide the system bars.
4686                          * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4687                          * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4688                          * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4689                          * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4690                          */
4691
4692                         // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4693                         @Suppress("DEPRECATION")
4694                         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
4695                     } else {  // Switch to normal viewing mode.
4696                         // Show the app bar if it was hidden.
4697                         if (hideAppBar) {
4698                             // Show the tab linear layout.
4699                             tabsLinearLayout.visibility = View.VISIBLE
4700
4701                             // Show the app bar.
4702                             appBar.show()
4703                         }
4704
4705                         // Set layout and scrolling parameters according to the position of the app bar.
4706                         if (bottomAppBar) {  // The app bar is at the bottom.
4707                             // Adjust the UI.
4708                             if (scrollAppBar) {
4709                                 // Reset the WebView padding to fill the available space.
4710                                 swipeRefreshLayout.setPadding(0, 0, 0, 0)
4711                             } else {
4712                                 // Move the WebView above the app bar layout.
4713                                 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
4714                             }
4715                         } else {  // The app bar is at the top.
4716                             // Check to see if the app bar is normally scrolled.
4717                             if (scrollAppBar) {  // The app bar is scrolled when it is displayed.
4718                                 // Get the swipe refresh layout parameters.
4719                                 val swipeRefreshLayoutParams = swipeRefreshLayout.layoutParams as CoordinatorLayout.LayoutParams
4720
4721                                 // Add the off-screen scrolling layout.
4722                                 swipeRefreshLayoutParams.behavior = AppBarLayout.ScrollingViewBehavior()
4723                             } else {  // The app bar is not scrolled when it is displayed.
4724                                 // The swipe refresh layout must be manually moved below the app bar layout.
4725                                 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0)
4726
4727                                 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
4728                                 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight)
4729                             }
4730                         }
4731
4732                         // Remove the `SYSTEM_UI` flags from the root frame layout.  The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4733                         @Suppress("DEPRECATION")
4734                         rootFrameLayout.systemUiVisibility = 0
4735                     }
4736
4737                     // Consume the double-tap.
4738                     true
4739                 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
4740                     // Return false.
4741                     false
4742                 }
4743             }
4744
4745             override fun onFling(motionEvent1: MotionEvent?, motionEvent2: MotionEvent, velocityX: Float, velocityY: Float): Boolean {
4746                 // Scroll the bottom app bar if enabled.
4747                 if (bottomAppBar && scrollAppBar && !objectAnimator.isRunning && (motionEvent1 != null)) {
4748                     // Calculate the Y change.
4749                     val motionY = motionEvent2.y - motionEvent1.y
4750
4751                     // Scroll the app bar if the change is greater than 50 pixels.
4752                     if (motionY > 50) {
4753                         // Animate the bottom app bar onto the screen.
4754                         objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0f)
4755                     } else if (motionY < -50) {
4756                         // Animate the bottom app bar off the screen.
4757                         objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", appBarLayout.height.toFloat())
4758                     }
4759
4760                     // Make it so.
4761                     objectAnimator.start()
4762                 }
4763
4764                 // Do not consume the event.
4765                 return false
4766             }
4767         })
4768
4769         // Pass all touch events on the WebView through the double-tap gesture detector.
4770         nestedScrollWebView.setOnTouchListener { view: View, motionEvent: MotionEvent? ->
4771             // Call `performClick()` on the view, which is required for accessibility.
4772             view.performClick()
4773
4774             // Check for double-taps.
4775             doubleTapGestureDetector.onTouchEvent(motionEvent!!)
4776         }
4777
4778         // Register the WebView for a context menu.  This is used to see link targets and download images.
4779         registerForContextMenu(nestedScrollWebView)
4780
4781         // Allow the downloading of files.
4782         nestedScrollWebView.setDownloadListener { downloadUrlString: String, userAgent: String, contentDisposition: String, mimetype: String, contentLength: Long ->
4783             // Use the specified download provider.
4784             if (downloadWithExternalApp) {  // Download with an external app.
4785                 // Download with an external app.
4786                 saveWithExternalApp(downloadUrlString)
4787             } else {  // Download with Privacy Browser or Android's download manager.
4788                 // Process the content length if it contains data.
4789                 val formattedFileSizeString = if (contentLength > 0) {  // The content length is greater than 0.
4790                     // Format the content length as a string.
4791                     NumberFormat.getInstance().format(contentLength) + " " + getString(R.string.bytes)
4792                 } else {  // The content length is not greater than 0.
4793                     // Set the formatted file size string to be `unknown size`.
4794                     getString(R.string.unknown_size)
4795                 }
4796
4797                 // Get the file name from the content disposition.
4798                 val fileNameString = UrlHelper.getFileName(this, contentDisposition, mimetype, downloadUrlString)
4799
4800                 // Instantiate the save dialog according.
4801                 val saveDialogFragment = SaveDialog.saveUrl(downloadUrlString, fileNameString, formattedFileSizeString, userAgent, nestedScrollWebView.acceptCookies)
4802
4803                 // 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.
4804                 try {
4805                     // Show the save dialog.
4806                     saveDialogFragment.show(supportFragmentManager, getString(R.string.save_dialog))
4807                 } catch (exception: Exception) {  // The dialog could not be shown.
4808                     // Add the dialog to the pending dialog array list.  It will be displayed in `onStart()`.
4809                     pendingDialogsArrayList.add(PendingDialogDataClass(saveDialogFragment, getString(R.string.save_dialog)))
4810                 }
4811             }
4812
4813             // Get the current page position.
4814             val currentPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
4815
4816             // Get the corresponding tab.
4817             val tab = tabLayout.getTabAt(currentPagePosition)!!
4818
4819             // Get the tab custom view.
4820             val tabCustomView = tab.customView!!
4821
4822             // Get the tab views.
4823             val tabFavoriteIconImageView = tabCustomView.findViewById<ImageView>(R.id.favorite_icon_imageview)
4824             val tabTitleTextView = tabCustomView.findViewById<TextView>(R.id.title_textview)
4825
4826             // Restore the previous webpage favorite icon and title if the title is currently set to `Loading...`.
4827             if (tabTitleTextView.text.toString() == getString(R.string.loading)) {
4828                 // Restore the previous webpage title text.
4829                 tabTitleTextView.text = nestedScrollWebView.previousWebpageTitle
4830
4831                 // Restore the previous webpage favorite icon if it is not null.
4832                 if (nestedScrollWebView.previousFavoriteIconDrawable != null)
4833                     tabFavoriteIconImageView.setImageDrawable(nestedScrollWebView.previousFavoriteIconDrawable)
4834             }
4835         }
4836
4837         // Update the find on page count.
4838         nestedScrollWebView.setFindListener { activeMatchOrdinal, numberOfMatches, isDoneCounting ->
4839             if (isDoneCounting && (numberOfMatches == 0)) {  // There are no matches.
4840                 // Set the find on page count text view to be `0/0`.
4841                 findOnPageCountTextView.setText(R.string.zero_of_zero)
4842             } else if (isDoneCounting) {  // There are matches.
4843                 // The active match ordinal is zero-based.
4844                 val activeMatch = activeMatchOrdinal + 1
4845
4846                 // Build the match string.
4847                 val matchString = "$activeMatch/$numberOfMatches"
4848
4849                 // Update the find on page count text view.
4850                 findOnPageCountTextView.text = matchString
4851             }
4852         }
4853
4854         // Process scroll changes.
4855         nestedScrollWebView.setOnScrollChangeListener { _: View?, _: Int, _: Int, _: Int, _: Int ->
4856             // Set the swipe to refresh status.
4857             if (nestedScrollWebView.swipeToRefresh)  // Only enable swipe to refresh if the WebView is scrolled to the top.
4858                 swipeRefreshLayout.isEnabled = nestedScrollWebView.scrollY == 0
4859             else  // Disable swipe to refresh.
4860                 swipeRefreshLayout.isEnabled = false
4861
4862             // Reinforce the system UI visibility flags if in full screen browsing mode.
4863             // This hides the status and navigation bars, which are displayed if other elements are shown, like dialog boxes, the options menu, or the keyboard.
4864             if (inFullScreenBrowsingMode) {
4865                 /* Hide the system bars.
4866                  * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4867                  * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4868                  * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4869                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4870                  */
4871
4872                 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4873                 @Suppress("DEPRECATION")
4874                 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
4875             }
4876         }
4877
4878         // Set the web chrome client.
4879         nestedScrollWebView.webChromeClient = object : WebChromeClient() {
4880             // Update the progress bar when a page is loading.
4881             override fun onProgressChanged(view: WebView, progress: Int) {
4882                 // Update the progress bar.
4883                 progressBar.progress = progress
4884
4885                 // Set the visibility of the progress bar.
4886                 if (progress < 100) {
4887                     // Show the progress bar.
4888                     progressBar.visibility = View.VISIBLE
4889                 } else {
4890                     // Hide the progress bar.
4891                     progressBar.visibility = View.GONE
4892
4893                     //Stop the swipe to refresh indicator if it is running
4894                     swipeRefreshLayout.isRefreshing = false
4895
4896                     // 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.
4897                     nestedScrollWebView.visibility = View.VISIBLE
4898                 }
4899             }
4900
4901             // Set the favorite icon when it changes.
4902             override fun onReceivedIcon(view: WebView, icon: Bitmap) {
4903                 // 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.
4904                 // This prevents low resolution icons from replacing high resolution one.
4905                 // The check for the visibility of the progress bar can possibly be removed once https://redmine.stoutner.com/issues/747 is fixed.
4906                 if ((progressBar.visibility == View.GONE) && (icon.height > nestedScrollWebView.getFavoriteIconHeight())) {
4907                     // Store the new favorite icon.
4908                     nestedScrollWebView.setFavoriteIcon(icon)
4909
4910                     // Get the current page position.
4911                     val currentPosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
4912
4913                     // Get the current tab.
4914                     val tab = tabLayout.getTabAt(currentPosition)
4915
4916                     // Check to see if the tab has been populated.
4917                     if (tab != null) {
4918                         // Get the custom view from the tab.
4919                         val tabView = tab.customView
4920
4921                         // Check to see if the custom tab view has been populated.
4922                         if (tabView != null) {
4923                             // Get the favorite icon image view from the tab.
4924                             val tabFavoriteIconImageView = tabView.findViewById<ImageView>(R.id.favorite_icon_imageview)
4925
4926                             // Display the favorite icon in the tab.
4927                             tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 128, 128, true))
4928                         }
4929                     }
4930                 }
4931             }
4932
4933             // Save a copy of the title when it changes.
4934             override fun onReceivedTitle(view: WebView, title: String) {
4935                 // Get the current page position.
4936                 val currentPosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
4937
4938                 // Get the current tab.
4939                 val tab = tabLayout.getTabAt(currentPosition)
4940
4941                 // Only populate the title text view if the tab has been fully created.
4942                 if (tab != null) {
4943                     // Get the custom view from the tab.
4944                     val tabView = tab.customView
4945
4946                     // Only populate the title text view if the tab view has been fully populated.
4947                     if (tabView != null) {
4948                         // Get the title text view from the tab.
4949                         val tabTitleTextView = tabView.findViewById<TextView>(R.id.title_textview)
4950
4951                         // Set the title according to the URL.
4952                         if (title == "about:blank") {
4953                             // Set the title to indicate a new tab.
4954                             tabTitleTextView.setText(R.string.new_tab)
4955                         } else {
4956                             // Set the title as the tab text.
4957                             tabTitleTextView.text = title
4958                         }
4959                     }
4960                 }
4961             }
4962
4963             // Enter full screen video.
4964             override fun onShowCustomView(video: View, callback: CustomViewCallback) {
4965                 // Set the full screen video flag.
4966                 displayingFullScreenVideo = true
4967
4968                 // Hide the keyboard.
4969                 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.windowToken, 0)
4970
4971                 // Hide the coordinator layout.
4972                 coordinatorLayout.visibility = View.GONE
4973
4974                 /* Hide the system bars.
4975                  * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4976                  * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4977                  * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4978                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4979                  */
4980
4981                 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4982                 @Suppress("DEPRECATION")
4983                 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
4984
4985                 // Disable the sliding drawers.
4986                 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
4987
4988                 // Add the video view to the full screen video frame layout.
4989                 fullScreenVideoFrameLayout.addView(video)
4990
4991                 // Show the full screen video frame layout.
4992                 fullScreenVideoFrameLayout.visibility = View.VISIBLE
4993
4994                 // Disable the screen timeout while the video is playing.  YouTube does this automatically, but not all other videos do.
4995                 fullScreenVideoFrameLayout.keepScreenOn = true
4996             }
4997
4998             // Exit full screen video.
4999             override fun onHideCustomView() {
5000                 // Exit the full screen video.
5001                 exitFullScreenVideo()
5002             }
5003
5004             // Upload files.
5005             override fun onShowFileChooser(webView: WebView, filePathCallback: ValueCallback<Array<Uri>>, fileChooserParams: FileChooserParams): Boolean {
5006                 // Store the file path callback.
5007                 fileChooserCallback = filePathCallback
5008
5009                 // Create an intent to open a chooser based on the file chooser parameters.
5010                 val fileChooserIntent = fileChooserParams.createIntent()
5011
5012                 // Check to see if the file chooser intent resolves to an installed package.
5013                 if (fileChooserIntent.resolveActivity(packageManager) != null) {  // The file chooser intent is fine.
5014                     // Launch the file chooser intent.
5015                     browseFileUploadActivityResultLauncher.launch(fileChooserIntent)
5016                 } else {  // The file chooser intent will cause a crash.
5017                     // Create a generic intent to open a chooser.
5018                     val genericFileChooserIntent = Intent(Intent.ACTION_GET_CONTENT)
5019
5020                     // Request an openable file.
5021                     genericFileChooserIntent.addCategory(Intent.CATEGORY_OPENABLE)
5022
5023                     // Set the file type to everything.
5024                     genericFileChooserIntent.type = "*/*"
5025
5026                     // Launch the generic file chooser intent.
5027                     browseFileUploadActivityResultLauncher.launch(genericFileChooserIntent)
5028                 }
5029
5030                 // Handle the event.
5031                 return true
5032             }
5033         }
5034         nestedScrollWebView.webViewClient = object : WebViewClient() {
5035             // `shouldOverrideUrlLoading` makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
5036             override fun shouldOverrideUrlLoading(view: WebView, webResourceRequest: WebResourceRequest): Boolean {
5037                 // Get the URL from the web resource request.
5038                 var requestUrlString = webResourceRequest.url.toString()
5039
5040                 // Sanitize the url.
5041                 requestUrlString = sanitizeUrl(requestUrlString)
5042
5043                 // Handle the URL according to the type.
5044                 return if (requestUrlString.startsWith("http")) {  // Load the URL in Privacy Browser.
5045                     // Load the URL.  By using `loadUrl()`, instead of `loadUrlFromBase()`, the Referer header will never be sent.
5046                     loadUrl(nestedScrollWebView, requestUrlString)
5047
5048                     // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
5049                     // Custom headers cannot be added if false is returned and the WebView handles the loading of the URL.
5050                     true
5051                 } else if (requestUrlString.startsWith("mailto:")) {  // Load the email address in an external email program.
5052                     // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
5053                     val emailIntent = Intent(Intent.ACTION_SENDTO)
5054
5055                     // Parse the url and set it as the data for the intent.
5056                     emailIntent.data = Uri.parse(requestUrlString)
5057
5058                     // Open the email program in a new task instead of as part of Privacy Browser.
5059                     emailIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
5060
5061                     try {
5062                         // Make it so.
5063                         startActivity(emailIntent)
5064                     } catch (exception: ActivityNotFoundException) {
5065                         // Display a snackbar.
5066                         Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
5067                     }
5068
5069                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5070                     true
5071                 } else if (requestUrlString.startsWith("tel:")) {  // Load the phone number in the dialer.
5072                     // Create a dial intent.
5073                     val dialIntent = Intent(Intent.ACTION_DIAL)
5074
5075                     // Add the phone number to the intent.
5076                     dialIntent.data = Uri.parse(requestUrlString)
5077
5078                     // Open the dialer in a new task instead of as part of Privacy Browser.
5079                     dialIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
5080
5081                     try {
5082                         // Make it so.
5083                         startActivity(dialIntent)
5084                     } catch (exception: ActivityNotFoundException) {
5085                         // Display a snackbar.
5086                         Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
5087                     }
5088
5089                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5090                     true
5091                 } else {  // Load a system chooser to select an app that can handle the URL.
5092                     // Create a generic intent to open an app.
5093                     val genericIntent = Intent(Intent.ACTION_VIEW)
5094
5095                     // Add the URL to the intent.
5096                     genericIntent.data = Uri.parse(requestUrlString)
5097
5098                     // List all apps that can handle the URL instead of just opening the first one.
5099                     genericIntent.addCategory(Intent.CATEGORY_BROWSABLE)
5100
5101                     // Open the app in a new task instead of as part of Privacy Browser.
5102                     genericIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
5103
5104                     try {
5105                         // Make it so.
5106                         startActivity(genericIntent)
5107                     } catch (exception: ActivityNotFoundException) {
5108                         // Display a snackbar.
5109                         Snackbar.make(nestedScrollWebView, getString(R.string.unrecognized_url, requestUrlString), Snackbar.LENGTH_SHORT).show()
5110                     }
5111
5112                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5113                     true
5114                 }
5115             }
5116
5117             // Check requests against the block lists.
5118             override fun shouldInterceptRequest(view: WebView, webResourceRequest: WebResourceRequest): WebResourceResponse? {
5119                 // Get the URL.
5120                 val requestUrlString = webResourceRequest.url.toString()
5121
5122                 // Check to see if the resource request is for the main URL.
5123                 if (requestUrlString == nestedScrollWebView.currentUrl) {
5124                     // `return null` loads the resource request, which should never be blocked if it is the main URL.
5125                     return null
5126                 }
5127
5128                 // 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.
5129                 while (ultraPrivacy == null) {
5130                     try {
5131                         // Check to see if the filter lists have been populated after 100 ms.
5132                         Thread.sleep(100)
5133                     } catch (exception: InterruptedException) {
5134                         // Do nothing.
5135                     }
5136                 }
5137
5138                 // Create an empty web resource response to be used if the resource request is blocked.
5139                 val emptyWebResourceResponse = WebResourceResponse("text/plain", "utf8", ByteArrayInputStream("".toByteArray()))
5140
5141                 // Initialize the variables.
5142                 var allowListResultStringArray: Array<String>? = null
5143                 var isThirdPartyRequest = false
5144
5145                 // Get the current URL.  `.getUrl()` throws an error because operations on the WebView cannot be made from this thread.
5146                 var currentBaseDomain = nestedScrollWebView.currentDomainName
5147
5148                 // Store a copy of the current domain for use in later requests.
5149                 val currentDomain = currentBaseDomain
5150
5151                 // Get the request host name.
5152                 var requestBaseDomain = webResourceRequest.url.host
5153
5154                 // Only check for third-party requests if the current base domain is not empty and the request domain is not null.
5155                 if (currentBaseDomain.isNotEmpty() && (requestBaseDomain != null)) {
5156                     // Determine the current base domain.
5157                     while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) {  // There is at least one subdomain.
5158                         // Remove the first subdomain.
5159                         currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1)
5160                     }
5161
5162                     // Determine the request base domain.
5163                     while (requestBaseDomain!!.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) {  // There is at least one subdomain.
5164                         // Remove the first subdomain.
5165                         requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1)
5166                     }
5167
5168                     // Update the third party request tracker.
5169                     isThirdPartyRequest = currentBaseDomain != requestBaseDomain
5170                 }
5171
5172                 // Get the current WebView page position.
5173                 val webViewPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
5174
5175                 // Determine if the WebView is currently displayed.
5176                 val webViewDisplayed = (webViewPagePosition == tabLayout.selectedTabPosition)
5177
5178                 // Block third-party requests if enabled.
5179                 if (isThirdPartyRequest && nestedScrollWebView.blockAllThirdPartyRequests) {
5180                     // Add the result to the resource requests.
5181                     nestedScrollWebView.addResourceRequest(arrayOf(REQUEST_THIRD_PARTY, requestUrlString))
5182
5183                     // Increment the blocked requests counters.
5184                     nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5185                     nestedScrollWebView.incrementRequestsCount(THIRD_PARTY_REQUESTS)
5186
5187                     // Update the titles of the filter lists menu items if the WebView is currently displayed.
5188                     if (webViewDisplayed) {
5189                         // Updating the UI must be run from the UI thread.
5190                         runOnUiThread {
5191                             // Update the menu item titles.
5192                             navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5193
5194                             // Update the options menu if it has been populated.
5195                             if (optionsMenu != null) {
5196                                 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5197                                 optionsBlockAllThirdPartyRequestsMenuItem.title =
5198                                     nestedScrollWebView.getRequestsCount(THIRD_PARTY_REQUESTS).toString() + " - " + getString(R.string.block_all_third_party_requests)
5199                             }
5200                         }
5201                     }
5202
5203                     // The resource request was blocked.  Return an empty web resource response.
5204                     return emptyWebResourceResponse
5205                 }
5206
5207                 // Check UltraList if it is enabled.
5208                 if (nestedScrollWebView.ultraListEnabled) {
5209                     // Check the URL against UltraList.
5210                     val ultraListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, ultraList)
5211
5212                     // Process the UltraList results.
5213                     if (ultraListResults[0] == REQUEST_BLOCKED) {  // The resource request matched UltraList's block list.
5214                         // Add the result to the resource requests.
5215                         nestedScrollWebView.addResourceRequest(arrayOf(ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]))
5216
5217                         // Increment the blocked requests counters.
5218                         nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5219                         nestedScrollWebView.incrementRequestsCount(com.stoutner.privacybrowser.views.ULTRALIST)
5220
5221                         // Update the titles of the filter lists menu items if the WebView is currently displayed.
5222                         if (webViewDisplayed) {
5223                             // Updating the UI must be run from the UI thread.
5224                             runOnUiThread {
5225                                 // Update the menu item titles.
5226                                 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5227
5228                                 // Update the options menu if it has been populated.
5229                                 if (optionsMenu != null) {
5230                                     optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5231                                     optionsUltraListMenuItem.title = nestedScrollWebView.getRequestsCount(com.stoutner.privacybrowser.views.ULTRALIST).toString() + " - " + getString(R.string.ultralist)
5232                                 }
5233                             }
5234                         }
5235
5236                         // The resource request was blocked.  Return an empty web resource response.
5237                         return emptyWebResourceResponse
5238                     } else if (ultraListResults[0] == REQUEST_ALLOWED) {  // The resource request matched UltraList's allow list.
5239                         // Add an allow list entry to the resource requests array.
5240                         nestedScrollWebView.addResourceRequest(arrayOf(ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]))
5241
5242                         // The resource request has been allowed by UltraList.  `return null` loads the requested resource.
5243                         return null
5244                     }
5245                 }
5246
5247                 // Check UltraPrivacy if it is enabled.
5248                 if (nestedScrollWebView.ultraPrivacyEnabled) {
5249                     // Check the URL against UltraPrivacy.
5250                     val ultraPrivacyResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, ultraPrivacy!!)
5251
5252                     // Process the UltraPrivacy results.
5253                     if (ultraPrivacyResults[0] == REQUEST_BLOCKED) {  // The resource request matched UltraPrivacy's block list.
5254                         // Add the result to the resource requests.
5255                         nestedScrollWebView.addResourceRequest(arrayOf(ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5256                             ultraPrivacyResults[5]))
5257
5258                         // Increment the blocked requests counters.
5259                         nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5260                         nestedScrollWebView.incrementRequestsCount(ULTRAPRIVACY)
5261
5262                         // Update the titles of the filter lists menu items if the WebView is currently displayed.
5263                         if (webViewDisplayed) {
5264                             // Updating the UI must be run from the UI thread.
5265                             runOnUiThread {
5266                                 // Update the menu item titles.
5267                                 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5268
5269                                 // Update the options menu if it has been populated.
5270                                 if (optionsMenu != null) {
5271                                     optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5272                                     optionsUltraPrivacyMenuItem.title = nestedScrollWebView.getRequestsCount(ULTRAPRIVACY).toString() + " - " + getString(R.string.ultraprivacy)
5273                                 }
5274                             }
5275                         }
5276
5277                         // The resource request was blocked.  Return an empty web resource response.
5278                         return emptyWebResourceResponse
5279                     } else if (ultraPrivacyResults[0] == REQUEST_ALLOWED) {  // The resource request matched UltraPrivacy's allow list.
5280                         // Add an allow list entry to the resource requests array.
5281                         nestedScrollWebView.addResourceRequest(arrayOf(ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5282                             ultraPrivacyResults[5]))
5283
5284                         // The resource request has been allowed by UltraPrivacy.  `return null` loads the requested resource.
5285                         return null
5286                     }
5287                 }
5288
5289                 // Check EasyList if it is enabled.
5290                 if (nestedScrollWebView.easyListEnabled) {
5291                     // Check the URL against EasyList.
5292                     val easyListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, easyList)
5293
5294                     // Process the EasyList results.
5295                     if (easyListResults[0] == REQUEST_BLOCKED) {  // The resource request matched EasyList's block list.
5296                         // Add the result to the resource requests.
5297                         nestedScrollWebView.addResourceRequest(arrayOf(easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]))
5298
5299                         // Increment the blocked requests counters.
5300                         nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5301                         nestedScrollWebView.incrementRequestsCount(EASYLIST)
5302
5303                         // Update the titles of the filter lists menu items if the WebView is currently displayed.
5304                         if (webViewDisplayed) {
5305                             // Updating the UI must be run from the UI thread.
5306                             runOnUiThread {
5307                                 // Update the menu item titles.
5308                                 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5309
5310                                 // Update the options menu if it has been populated.
5311                                 if (optionsMenu != null) {
5312                                     optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5313                                     optionsEasyListMenuItem.title = nestedScrollWebView.getRequestsCount(EASYLIST).toString() + " - " + getString(R.string.easylist)
5314                                 }
5315                             }
5316                         }
5317
5318                         // The resource request was blocked.  Return an empty web resource response.
5319                         return emptyWebResourceResponse
5320                     } else if (easyListResults[0] == REQUEST_ALLOWED) {  // The resource request matched EasyList's allow list.
5321                         // Update the allow list result string array tracker.
5322                         allowListResultStringArray = arrayOf(easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5])
5323                     }
5324                 }
5325
5326                 // Check EasyPrivacy if it is enabled.
5327                 if (nestedScrollWebView.easyPrivacyEnabled) {
5328                     // Check the URL against EasyPrivacy.
5329                     val easyPrivacyResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, easyPrivacy)
5330
5331                     // Process the EasyPrivacy results.
5332                     if (easyPrivacyResults[0] == REQUEST_BLOCKED) {  // The resource request matched EasyPrivacy's block list.
5333                         // Add the result to the resource requests.
5334                         nestedScrollWebView.addResourceRequest(arrayOf(easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5]))
5335
5336                         // Increment the blocked requests counters.
5337                         nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5338                         nestedScrollWebView.incrementRequestsCount(EASYPRIVACY)
5339
5340                         // Update the titles of the filter lists menu items if the WebView is currently displayed.
5341                         if (webViewDisplayed) {
5342                             // Updating the UI must be run from the UI thread.
5343                             runOnUiThread {
5344                                 // Update the menu item titles.
5345                                 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5346
5347                                 // Update the options menu if it has been populated.
5348                                 if (optionsMenu != null) {
5349                                     optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5350                                     optionsEasyPrivacyMenuItem.title = nestedScrollWebView.getRequestsCount(EASYPRIVACY).toString() + " - " + getString(R.string.easyprivacy)
5351                                 }
5352                             }
5353                         }
5354
5355                         // The resource request was blocked.  Return an empty web resource response.
5356                         return emptyWebResourceResponse
5357                     } else if (easyPrivacyResults[0] == REQUEST_ALLOWED) {  // The resource request matched EasyPrivacy's allow list.
5358                         // Update the allow list result string array tracker.
5359                         allowListResultStringArray = arrayOf(easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5])
5360                     }
5361                 }
5362
5363                 // Check Fanboy’s Annoyance List if it is enabled.
5364                 if (nestedScrollWebView.fanboysAnnoyanceListEnabled) {
5365                     // Check the URL against Fanboy's Annoyance List.
5366                     val fanboysAnnoyanceListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, fanboysAnnoyanceList)
5367
5368                     // Process the Fanboy's Annoyance List results.
5369                     if (fanboysAnnoyanceListResults[0] == REQUEST_BLOCKED) {  // The resource request matched Fanboy's Annoyance List's block list.
5370                         // Add the result to the resource requests.
5371                         nestedScrollWebView.addResourceRequest(arrayOf(fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5372                             fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]))
5373
5374                         // Increment the blocked requests counters.
5375                         nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5376                         nestedScrollWebView.incrementRequestsCount(FANBOYS_ANNOYANCE_LIST)
5377
5378                         // Update the titles of the filter lists menu items if the WebView is currently displayed.
5379                         if (webViewDisplayed) {
5380                             // Updating the UI must be run from the UI thread.
5381                             runOnUiThread {
5382                                 // Update the menu item titles.
5383                                 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5384
5385                                 // Update the options menu if it has been populated.
5386                                 if (optionsMenu != null) {
5387                                     optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5388                                     optionsFanboysAnnoyanceListMenuItem.title = nestedScrollWebView.getRequestsCount(FANBOYS_ANNOYANCE_LIST).toString() + " - " + getString(R.string.fanboys_annoyance_list)
5389                                 }
5390                             }
5391                         }
5392
5393                         // The resource request was blocked.  Return an empty web resource response.
5394                         return emptyWebResourceResponse
5395                     } else if (fanboysAnnoyanceListResults[0] == REQUEST_ALLOWED) {  // The resource request matched Fanboy's Annoyance List's allow list.
5396                         // Update the allow list result string array tracker.
5397                         allowListResultStringArray = arrayOf(fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5398                             fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5])
5399                     }
5400                 } else if (nestedScrollWebView.fanboysSocialBlockingListEnabled) {  // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
5401                     // Check the URL against Fanboy's Annoyance List.
5402                     val fanboysSocialListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, fanboysSocialList)
5403
5404                     // Process the Fanboy's Social Blocking List results.
5405                     if (fanboysSocialListResults[0] == REQUEST_BLOCKED) {  // The resource request matched Fanboy's Social Blocking List's block list.
5406                         // Add the result to the resource requests.
5407                         nestedScrollWebView.addResourceRequest(arrayOf(fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5408                             fanboysSocialListResults[4], fanboysSocialListResults[5]))
5409
5410                         // Increment the blocked requests counters.
5411                         nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5412                         nestedScrollWebView.incrementRequestsCount(FANBOYS_SOCIAL_BLOCKING_LIST)
5413
5414                         // Update the titles of the filter lists menu items if the WebView is currently displayed.
5415                         if (webViewDisplayed) {
5416                             // Updating the UI must be run from the UI thread.
5417                             runOnUiThread {
5418                                 // Update the menu item titles.
5419                                 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5420
5421                                 // Update the options menu if it has been populated.
5422                                 if (optionsMenu != null) {
5423                                     optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5424                                     optionsFanboysSocialBlockingListMenuItem.title =
5425                                         nestedScrollWebView.getRequestsCount(FANBOYS_SOCIAL_BLOCKING_LIST).toString() + " - " + getString(R.string.fanboys_social_blocking_list)
5426                                 }
5427                             }
5428                         }
5429
5430                         // The resource request was blocked.  Return an empty web resource response.
5431                         return emptyWebResourceResponse
5432                     } else if (fanboysSocialListResults[0] == REQUEST_ALLOWED) {  // The resource request matched Fanboy's Social Blocking List's allow list.
5433                         // Update the allow list result string array tracker.
5434                         allowListResultStringArray = arrayOf(fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3], fanboysSocialListResults[4],
5435                             fanboysSocialListResults[5])
5436                     }
5437                 }
5438
5439                 // Add the request to the log because it hasn't been processed by any of the previous checks.
5440                 if (allowListResultStringArray != null) {  // The request was processed by an allow list.
5441                     nestedScrollWebView.addResourceRequest(allowListResultStringArray)
5442                 } else {  // The request didn't match any filter list entry.  Log it as a default request.
5443                     nestedScrollWebView.addResourceRequest(arrayOf(REQUEST_DEFAULT, requestUrlString))
5444                 }
5445
5446                 // The resource request has not been blocked.  `return null` loads the requested resource.
5447                 return null
5448             }
5449
5450             // Handle HTTP authentication requests.
5451             override fun onReceivedHttpAuthRequest(view: WebView, handler: HttpAuthHandler, host: String, realm: String) {
5452                 // Store the handler.
5453                 nestedScrollWebView.httpAuthHandler = handler
5454
5455                 // Instantiate an HTTP authentication dialog.
5456                 val httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm, nestedScrollWebView.webViewFragmentId)
5457
5458                 // Try to show the dialog.  WebView can receive an HTTP authentication request even after the app has been paused.  Attempting to display a dialog in that state leads to a crash.
5459                 try {
5460                     // Show the HTTP authentication dialog.
5461                     httpAuthenticationDialogFragment.show(supportFragmentManager, getString(R.string.http_authentication))
5462                 } catch (exception: Exception) {  // The dialog could not be shown.
5463                     // Add the dialog to the pending dialog array list.  It will be displayed in `onStart()`.
5464                     pendingDialogsArrayList.add(PendingDialogDataClass(httpAuthenticationDialogFragment, getString(R.string.http_authentication)))
5465                 }
5466             }
5467
5468             override fun onPageStarted(webView: WebView, url: String, favicon: Bitmap?) {
5469                 // Get the app bar layout height.  This can't be done in `applyAppSettings()` because the app bar is not yet populated there.
5470                 // 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.
5471                 if (appBarLayout.height > 0)
5472                     appBarHeight = appBarLayout.height
5473
5474                 // Set the padding and layout settings according to the position of the app bar.
5475                 if (bottomAppBar) {  // The app bar is on the bottom.
5476                     // Adjust the UI.
5477                     if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) {  // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
5478                         // Reset the WebView padding to fill the available space.
5479                         swipeRefreshLayout.setPadding(0, 0, 0, 0)
5480                     } else {  // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
5481                         // Move the WebView above the app bar layout.
5482                         swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
5483                     }
5484                 } else {  // The app bar is on the top.
5485                     // 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.
5486                     if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) {  // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
5487                         // No padding is needed because it will automatically be placed below the app bar layout due to the scrolling layout behavior.
5488                         swipeRefreshLayout.setPadding(0, 0, 0, 0)
5489
5490                         // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5491                         swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10, defaultProgressViewEndOffset)
5492                     } else {  // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
5493                         // The swipe refresh layout must be manually moved below the app bar layout.
5494                         swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0)
5495
5496                         // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5497                         swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight)
5498                     }
5499                 }
5500
5501                 // Reset the list of resource requests.
5502                 nestedScrollWebView.clearResourceRequests()
5503
5504                 // Reset the requests counters.
5505                 nestedScrollWebView.resetRequestsCounters()
5506
5507                 // Get the current page position.
5508                 val currentPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
5509
5510                 // Update the URL text bar if the page is currently selected and the URL edit text is not currently being edited.
5511                 if ((tabLayout.selectedTabPosition == currentPagePosition) && !urlEditText.hasFocus()) {
5512                     // Display the formatted URL text.  The nested scroll WebView current URL preserves any initial `view-source:`, and opposed to the method URL variable.
5513                     urlEditText.setText(nestedScrollWebView.currentUrl)
5514
5515                     // Highlight the URL syntax.
5516                     UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
5517
5518                     // Hide the keyboard.
5519                     inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.windowToken, 0)
5520                 }
5521
5522                 // Reset the list of host IP addresses.
5523                 nestedScrollWebView.currentIpAddresses = ""
5524
5525                 // Get a URI for the current URL.
5526                 val currentUri = Uri.parse(url)
5527
5528                 // Get the current domain name.
5529                 val currentDomainName = currentUri.host
5530
5531                 // Get the IP addresses for the current domain.
5532                 if (!currentDomainName.isNullOrEmpty())
5533                     GetHostIpAddressesCoroutine.checkPinnedMismatch(currentDomainName, nestedScrollWebView, supportFragmentManager, getString(R.string.pinned_mismatch))
5534
5535                 // 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.)
5536                 if ((optionsMenu != null) && (webView == currentWebView)) {
5537                     // Set the title.
5538                     optionsRefreshMenuItem.setTitle(R.string.stop)
5539
5540                     // Set the icon if it is displayed in the AppBar.
5541                     if (displayAdditionalAppBarIcons)
5542                         optionsRefreshMenuItem.setIcon(R.drawable.close_blue)
5543                 }
5544             }
5545
5546             override fun onPageFinished(webView: WebView, url: String) {
5547                 // Flush any cookies to persistent storage.  The cookie manager has become very lazy about flushing cookies in recent versions.
5548                 if (nestedScrollWebView.acceptCookies)
5549                     cookieManager.flush()
5550
5551                 // Update the Refresh menu item if the options menu has been created and the WebView is currently displayed.
5552                 if (optionsMenu != null && (webView == currentWebView)) {
5553                     // Reset the Refresh title.
5554                     optionsRefreshMenuItem.setTitle(R.string.refresh)
5555
5556                     // Reset the icon if it is displayed in the app bar.
5557                     if (displayAdditionalAppBarIcons)
5558                         optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled)
5559                 }
5560
5561                 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
5562                 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
5563                 val privateDataDirectoryString = applicationInfo.dataDir
5564
5565                 // Clear the cache, history, and logcat if Incognito Mode is enabled.
5566                 if (incognitoModeEnabled) {
5567                     // Clear the cache.  `true` includes disk files.
5568                     nestedScrollWebView.clearCache(true)
5569
5570                     // Clear the back/forward history.
5571                     nestedScrollWebView.clearHistory()
5572
5573                     // Manually delete cache folders.
5574                     try {
5575                         // Delete the main cache directory.
5576                         Runtime.getRuntime().exec("rm -rf $privateDataDirectoryString/cache")
5577                     } catch (exception: IOException) {
5578                         // Do nothing if an error is thrown.
5579                     }
5580
5581                     // Clear the logcat.
5582                     try {
5583                         // Clear the logcat.  `-c` clears the logcat.  `-b all` clears all the buffers (instead of just crash, main, and system).
5584                         Runtime.getRuntime().exec("logcat -b all -c")
5585                     } catch (exception: IOException) {
5586                         // Do nothing.
5587                     }
5588                 }
5589
5590                 // Clear the `Service Worker` directory.
5591                 try {
5592                     // A string array must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
5593                     Runtime.getRuntime().exec(arrayOf("rm", "-rf", "$privateDataDirectoryString/app_webview/Default/Service Worker/"))
5594                 } catch (exception: IOException) {
5595                     // Do nothing.
5596                 }
5597
5598                 // Get the current page position.
5599                 val currentPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
5600
5601                 // 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.
5602                 val currentUrl = nestedScrollWebView.url
5603
5604                 // Get the current tab.
5605                 val tab = tabLayout.getTabAt(currentPagePosition)
5606
5607                 // Update the URL text bar if the page is currently selected and the user is not currently typing in the URL edit text.
5608                 // Crash records show that, in some crazy way, it is possible for the current URL to be blank at this point.
5609                 // Probably some sort of race condition when Privacy Browser is being resumed.
5610                 if ((tabLayout.selectedTabPosition == currentPagePosition) && !urlEditText.hasFocus() && (currentUrl != null)) {
5611                     // Check to see if the URL is `about:blank`.
5612                     if (currentUrl == "about:blank") {  // The WebView is blank.
5613                         // Display the hint in the URL edit text.
5614                         urlEditText.setText("")
5615
5616                         // Request focus for the URL text box.
5617                         urlEditText.requestFocus()
5618
5619                         // Display the keyboard.
5620                         inputMethodManager.showSoftInput(urlEditText, 0)
5621
5622                         // Apply the domain settings.  This clears any settings from the previous domain.
5623                         applyDomainSettings(nestedScrollWebView, "", resetTab = true, reloadWebsite = false, loadUrl = false)
5624
5625                         // Only populate the title text view if the tab has been fully created.
5626                         if (tab != null) {
5627                             // Get the custom view from the tab.
5628                             val tabView = tab.customView!!
5629
5630                             // Get the title text view from the tab.
5631                             val tabTitleTextView = tabView.findViewById<TextView>(R.id.title_textview)
5632
5633                             // Set the title as the tab text.
5634                             tabTitleTextView.setText(R.string.new_tab)
5635                         }
5636                     } else {  // The WebView has loaded a webpage.
5637                         // Update the URL edit text if it is not currently being edited.
5638                         if (!urlEditText.hasFocus()) {
5639                             // 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.
5640                             val sanitizedUrl = sanitizeUrl(currentUrl)
5641
5642                             // Display the final URL.  Getting the URL from the WebView instead of using the one provided by `onPageFinished()` makes websites like YouTube function correctly.
5643                             urlEditText.setText(sanitizedUrl)
5644
5645                             // Highlight the URL syntax.
5646                             UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
5647                         }
5648
5649                         // Only populate the title text view if the tab has been fully created.
5650                         if (tab != null) {
5651                             // Get the custom view from the tab.
5652                             val tabView = tab.customView!!
5653
5654                             // Get the title text view from the tab.
5655                             val tabTitleTextView = tabView.findViewById<TextView>(R.id.title_textview)
5656
5657                             // Set the title as the tab text.  Sometimes `onReceivedTitle()` is not called, especially when navigating history.
5658                             tabTitleTextView.text = nestedScrollWebView.title
5659                         }
5660                     }
5661                 }
5662             }
5663
5664             // Handle SSL Certificate errors.  Suppress the lint warning that ignoring the error might be dangerous.
5665             @SuppressLint("WebViewClientOnReceivedSslError")
5666             override fun onReceivedSslError(view: WebView, handler: SslErrorHandler, error: SslError) {
5667                 // Get the current website SSL certificate.
5668                 val currentWebsiteSslCertificate = error.certificate
5669
5670                 // Extract the individual pieces of information from the current website SSL certificate.
5671                 val currentWebsiteIssuedToCName = currentWebsiteSslCertificate.issuedTo.cName
5672                 val currentWebsiteIssuedToOName = currentWebsiteSslCertificate.issuedTo.oName
5673                 val currentWebsiteIssuedToUName = currentWebsiteSslCertificate.issuedTo.uName
5674                 val currentWebsiteIssuedByCName = currentWebsiteSslCertificate.issuedBy.cName
5675                 val currentWebsiteIssuedByOName = currentWebsiteSslCertificate.issuedBy.oName
5676                 val currentWebsiteIssuedByUName = currentWebsiteSslCertificate.issuedBy.uName
5677                 val currentWebsiteSslStartDate = currentWebsiteSslCertificate.validNotBeforeDate
5678                 val currentWebsiteSslEndDate = currentWebsiteSslCertificate.validNotAfterDate
5679
5680                 // Get the pinned SSL certificate.
5681                 val (pinnedSslCertificateStringArray, pinnedSslCertificateDateArray) = nestedScrollWebView.getPinnedSslCertificate()
5682
5683                 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
5684                 if (nestedScrollWebView.hasPinnedSslCertificate() &&
5685                     (currentWebsiteIssuedToCName == pinnedSslCertificateStringArray[0]) &&
5686                     (currentWebsiteIssuedToOName == pinnedSslCertificateStringArray[1]) &&
5687                     (currentWebsiteIssuedToUName == pinnedSslCertificateStringArray[2]) &&
5688                     (currentWebsiteIssuedByCName == pinnedSslCertificateStringArray[3]) &&
5689                     (currentWebsiteIssuedByOName == pinnedSslCertificateStringArray[4]) &&
5690                     (currentWebsiteIssuedByUName == pinnedSslCertificateStringArray[5]) &&
5691                     (currentWebsiteSslStartDate == pinnedSslCertificateDateArray[0]) &&
5692                     (currentWebsiteSslEndDate == pinnedSslCertificateDateArray[1])) {
5693
5694                     // An SSL certificate is pinned and matches the current domain certificate.  Proceed to the website without displaying an error.
5695                     handler.proceed()
5696                 } else {  // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
5697                     // Store the SSL error handler.
5698                     nestedScrollWebView.sslErrorHandler = handler
5699
5700                     // Instantiate an SSL certificate error alert dialog.
5701                     val sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error, nestedScrollWebView.webViewFragmentId)
5702
5703                     // Try to show the dialog.  The SSL error handler continues to function even when the app has been stopped.  Attempting to display a dialog in that state leads to a crash.
5704                     try {
5705                         // Show the SSL certificate error dialog.
5706                         sslCertificateErrorDialogFragment.show(supportFragmentManager, getString(R.string.ssl_certificate_error))
5707                     } catch (exception: Exception) {
5708                         // Add the dialog to the pending dialog array list.  It will be displayed in `onStart()`.
5709                         pendingDialogsArrayList.add(PendingDialogDataClass(sslCertificateErrorDialogFragment, getString(R.string.ssl_certificate_error)))
5710                     }
5711                 }
5712             }
5713         }
5714
5715         // Check to see if the state is being restored.
5716         if (restoringState) {  // The state is being restored.
5717             // Resume the nested scroll WebView JavaScript timers.
5718             nestedScrollWebView.resumeTimers()
5719         } else if (pagePosition == 0) {  // The first page is being loaded.
5720             // Set this nested scroll WebView as the current WebView.
5721             currentWebView = nestedScrollWebView
5722
5723             // Get the intent that started the app.
5724             val launchingIntent = intent
5725
5726             // Reset the intent.  This prevents a duplicate tab from being created on restart.
5727             intent = Intent()
5728
5729             // Get the information from the intent.
5730             val launchingIntentAction = launchingIntent.action
5731             val launchingIntentUriData = launchingIntent.data
5732             val launchingIntentStringExtra = launchingIntent.getStringExtra(Intent.EXTRA_TEXT)
5733
5734             // Parse the launching intent URL.  Suppress the suggestions of using elvis expressions as they make the logic very difficult to follow.
5735             @Suppress("IfThenToElvis") val urlToLoadString = if ((launchingIntentAction != null) && (launchingIntentAction == Intent.ACTION_WEB_SEARCH)) {  // The intent contains a search string.
5736                 // Sanitize the search input and convert it to a search.
5737                 val encodedSearchString = try {
5738                     URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8")
5739                 } catch (exception: UnsupportedEncodingException) {
5740                     ""
5741                 }
5742
5743                 // Add the search URL to the encodedSearchString
5744                 searchURL + encodedSearchString
5745             } else if (launchingIntentUriData != null) {  // The launching intent contains a URL formatted as a URI.
5746                 // Get the URL from the URI.
5747                 launchingIntentUriData.toString()
5748             } else if (launchingIntentStringExtra != null) {  // The launching intent contains text that might be a URL.
5749                 // Get the URL from the string extra.
5750                 launchingIntentStringExtra
5751             } else if (urlString != "") {  // The activity has been restarted.
5752                 // Load the saved URL.
5753                 urlString
5754             } else {  // The is no saved URL and there is no URL in the intent.
5755                 // Load the homepage.
5756                 sharedPreferences.getString("homepage", getString(R.string.homepage_default_value))
5757             }
5758
5759             // Load the website if not waiting for the proxy.
5760             if (waitingForProxy) {  // Store the URL to be loaded in the Nested Scroll WebView.
5761                 nestedScrollWebView.waitingForProxyUrlString = urlToLoadString!!
5762             } else {  // Load the URL.
5763                 loadUrl(nestedScrollWebView, urlToLoadString!!)
5764             }
5765         } else {  // This is not the first tab.
5766             // Load the URL.
5767             loadUrl(nestedScrollWebView, urlString)
5768
5769             // Set the focus and display the keyboard if the URL is blank.
5770             if (urlString == "") {
5771                 // Request focus for the URL text box.
5772                 urlEditText.requestFocus()
5773
5774                 // Display the keyboard once the tab layout has settled.
5775                 tabLayout.post {
5776                     inputMethodManager.showSoftInput(urlEditText, 0)
5777                 }
5778             }
5779         }
5780     }
5781
5782     private fun loadBookmarksFolder() {
5783         // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
5784         bookmarksCursor = bookmarksDatabaseHelper!!.getBookmarksByDisplayOrder(currentBookmarksFolderId)
5785
5786         // Populate the bookmarks cursor adapter.
5787         bookmarksCursorAdapter = object : CursorAdapter(this, bookmarksCursor, false) {
5788             override fun newView(context: Context, cursor: Cursor, parent: ViewGroup): View {
5789                 // Inflate the individual item layout.
5790                 return layoutInflater.inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false)
5791             }
5792
5793             override fun bindView(view: View, context: Context, cursor: Cursor) {
5794                 // Get handles for the views.
5795                 val bookmarkFavoriteIcon = view.findViewById<ImageView>(R.id.bookmark_favorite_icon)
5796                 val bookmarkNameTextView = view.findViewById<TextView>(R.id.bookmark_name)
5797
5798                 // Get the favorite icon byte array from the cursor.
5799                 val favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndexOrThrow(FAVORITE_ICON))
5800
5801                 // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
5802                 val favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.size)
5803
5804                 // Display the bitmap in the bookmark favorite icon.
5805                 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap)
5806
5807                 // Display the bookmark name from the cursor in the bookmark name text view.
5808                 bookmarkNameTextView.text = cursor.getString(cursor.getColumnIndexOrThrow(BOOKMARK_NAME))
5809
5810                 // Make the font bold for folders.
5811                 if (cursor.getInt(cursor.getColumnIndexOrThrow(IS_FOLDER)) == 1)
5812                     bookmarkNameTextView.typeface = Typeface.DEFAULT_BOLD
5813                 else  // Reset the font to default for normal bookmarks.
5814                     bookmarkNameTextView.typeface = Typeface.DEFAULT
5815             }
5816         }
5817
5818         // Populate the list view with the adapter.
5819         bookmarksListView.adapter = bookmarksCursorAdapter
5820
5821         // Set the bookmarks drawer title.
5822         if (currentBookmarksFolderId == HOME_FOLDER_ID)  // The current bookmarks folder is the home folder.
5823             bookmarksTitleTextView.setText(R.string.bookmarks)
5824         else
5825             bookmarksTitleTextView.text = bookmarksDatabaseHelper!!.getFolderName(currentBookmarksFolderId)
5826     }
5827
5828     private fun loadUrl(nestedScrollWebView: NestedScrollWebView, url: String) {
5829         // Sanitize the URL.
5830         val urlString = sanitizeUrl(url)
5831
5832         // Apply the domain settings and load the URL.
5833         applyDomainSettings(nestedScrollWebView, urlString, resetTab = true, reloadWebsite = false, loadUrl = true)
5834     }
5835
5836     private fun loadUrlFromTextBox() {
5837         // 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.
5838         var unformattedUrlString = urlEditText.text.toString().trim { it <= ' ' }
5839
5840         // Create the formatted URL string.
5841         var urlString = ""
5842
5843         // Check to see if the unformatted URL string is a valid URL.  Otherwise, convert it into a search.
5844         if (unformattedUrlString.startsWith("content://") || unformattedUrlString.startsWith("view-source:")) {  // This is a content or source URL.
5845             // Load the entire content URL.
5846             urlString = unformattedUrlString
5847         } else if (Patterns.WEB_URL.matcher(unformattedUrlString).matches() || unformattedUrlString.startsWith("http://") || unformattedUrlString.startsWith("https://") ||
5848             unformattedUrlString.startsWith("file://")) {  // This is a standard URL.
5849
5850             // Add `https://` at the beginning if there is no protocol.  Otherwise the app will segfault.
5851             if (!unformattedUrlString.startsWith("http") && !unformattedUrlString.startsWith("file://"))
5852                 unformattedUrlString = "https://$unformattedUrlString"
5853
5854             // Initialize the unformatted URL.
5855             var unformattedUrl: URL? = null
5856
5857             // Convert the unformatted URL string to a URL.
5858             try {
5859                 unformattedUrl = URL(unformattedUrlString)
5860             } catch (exception: MalformedURLException) {
5861                 exception.printStackTrace()
5862             }
5863
5864             // Get the components of the URL.
5865             val scheme = unformattedUrl?.protocol
5866             val authority = unformattedUrl?.authority
5867             val path = unformattedUrl?.path
5868             val query = unformattedUrl?.query
5869             val fragment = unformattedUrl?.ref
5870
5871             // Create a URI.
5872             val uri = Uri.Builder()
5873
5874             // Build the URI from the components of the URL.
5875             uri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment)
5876
5877             // Decode the URI as a UTF-8 string in.
5878             try {
5879                 urlString = URLDecoder.decode(uri.build().toString(), "UTF-8")
5880             } catch (exception: UnsupportedEncodingException) {
5881                 // Do nothing.  The formatted URL string will remain blank.
5882             }
5883         } else if (unformattedUrlString.isNotEmpty()) {  // This is not a URL, but rather a search string.
5884             // Sanitize the search input.
5885             val encodedSearchString = try {
5886                 URLEncoder.encode(unformattedUrlString, "UTF-8")
5887             } catch (exception: UnsupportedEncodingException) {
5888                 ""
5889             }
5890
5891             // Add the base search URL.
5892             urlString = searchURL + encodedSearchString
5893         }
5894
5895         // 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.
5896         urlEditText.clearFocus()
5897
5898         // Make it so.
5899         loadUrl(currentWebView!!, urlString)
5900     }
5901
5902     override fun navigateHistory(steps: Int) {
5903         // Get the current web back forward list.
5904         val webBackForwardList = currentWebView!!.copyBackForwardList()
5905
5906         // Calculate the target index.
5907         val targetIndex = webBackForwardList.currentIndex + steps
5908
5909         // Get the previous entry data.
5910         val previousUrl = webBackForwardList.getItemAtIndex(targetIndex).url
5911         val previousFavoriteIcon = webBackForwardList.getItemAtIndex(targetIndex).favicon
5912
5913         // Apply the domain settings.
5914         applyDomainSettings(currentWebView!!, previousUrl, resetTab = false, reloadWebsite = false, loadUrl = false)
5915
5916         // Get the current tab.
5917         val tab = tabLayout.getTabAt(tabLayout.selectedTabPosition)!!
5918
5919         // Get the custom view from the tab.
5920         val tabView = tab.customView!!
5921
5922         // Get the favorite icon image view from the tab.
5923         val tabFavoriteIconImageView = tabView.findViewById<ImageView>(R.id.favorite_icon_imageview)
5924
5925         // Store the previous favorite icon.
5926         if (previousFavoriteIcon == null)
5927             currentWebView!!.setFavoriteIcon(defaultFavoriteIconBitmap)
5928         else
5929             currentWebView!!.setFavoriteIcon(previousFavoriteIcon)
5930
5931         // Display the previous favorite icon in the tab.
5932         tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(currentWebView!!.getFavoriteIcon(), 128, 128, true))
5933
5934         // Load the history entry.
5935         currentWebView!!.goBackOrForward(steps)
5936
5937         // Create a handler to update the URL edit box.
5938         val urlEditTextUpdateHandler = Handler(Looper.getMainLooper())
5939
5940         // Create a runnable to update the URL edit box.
5941         val urlEditTextUpdateRunnable = Runnable {
5942             // Update the URL edit text.
5943             urlEditText.setText(currentWebView!!.url)
5944
5945             // Disable the wide viewport if the source is being viewed.
5946             if (currentWebView!!.url!!.startsWith("view-source:"))
5947                 currentWebView!!.settings.useWideViewPort = false
5948         }
5949
5950         // Update the URL edit text after 50 milliseconds, so that the WebView has enough time to navigate to the new URL.
5951         urlEditTextUpdateHandler.postDelayed(urlEditTextUpdateRunnable, 50)
5952     }
5953
5954     override fun openFile(dialogFragment: DialogFragment) {
5955         // Get the dialog.
5956         val dialog = dialogFragment.dialog!!
5957
5958         // Get handles for the views.
5959         val fileNameEditText = dialog.findViewById<EditText>(R.id.file_name_edittext)
5960         val mhtCheckBox = dialog.findViewById<CheckBox>(R.id.mht_checkbox)
5961
5962         // Get the file path string.
5963         val openFilePath = fileNameEditText.text.toString()
5964
5965         // Apply the domain settings.  This resets the favorite icon and removes any domain settings.
5966         applyDomainSettings(currentWebView!!, openFilePath, resetTab = true, reloadWebsite = false, loadUrl = false)
5967
5968         // Open the file according to the type.
5969         if (mhtCheckBox.isChecked) {  // Force opening of an MHT file.
5970             try {
5971                 // Get the MHT file input stream.
5972                 val mhtFileInputStream = contentResolver.openInputStream(Uri.parse(openFilePath))
5973
5974                 // Create a temporary MHT file.
5975                 val temporaryMhtFile = File.createTempFile(TEMPORARY_MHT_FILE, ".mht", cacheDir)
5976
5977                 // Get a file output stream for the temporary MHT file.
5978                 val temporaryMhtFileOutputStream = FileOutputStream(temporaryMhtFile)
5979
5980                 // Create a transfer byte array.
5981                 val transferByteArray = ByteArray(1024)
5982
5983                 // Create an integer to track the number of bytes read.
5984                 var bytesRead: Int
5985
5986                 // Copy the temporary MHT file input stream to the MHT output stream.
5987                 while (mhtFileInputStream!!.read(transferByteArray).also { bytesRead = it } > 0)
5988                     temporaryMhtFileOutputStream.write(transferByteArray, 0, bytesRead)
5989
5990                 // Flush the temporary MHT file output stream.
5991                 temporaryMhtFileOutputStream.flush()
5992
5993                 // Close the streams.
5994                 temporaryMhtFileOutputStream.close()
5995                 mhtFileInputStream.close()
5996
5997                 // Load the temporary MHT file.
5998                 currentWebView!!.loadUrl(temporaryMhtFile.toString())
5999             } catch (exception: Exception) {
6000                 // Display a snackbar.
6001                 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
6002             }
6003         } else {  // Let the WebView handle opening of the file.
6004             // Open the file.
6005             currentWebView!!.loadUrl(openFilePath)
6006         }
6007     }
6008     // The view parameter cannot be removed because it is called from the layout onClick.
6009     fun openNavigationDrawer(@Suppress("UNUSED_PARAMETER")view: View) {
6010         // Open the navigation drawer.
6011         drawerLayout.openDrawer(GravityCompat.START)
6012     }
6013
6014     private fun openWithApp(url: String) {
6015         // Create an open with app intent with `ACTION_VIEW`.
6016         val openWithAppIntent = Intent(Intent.ACTION_VIEW)
6017
6018         // Set the URI but not the MIME type.  This should open all available apps.
6019         openWithAppIntent.data = Uri.parse(url)
6020
6021         // Flag the intent to open in a new task.
6022         openWithAppIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
6023
6024         // Try the intent.
6025         try {
6026             // Show the chooser.
6027             startActivity(openWithAppIntent)
6028         } catch (exception: ActivityNotFoundException) {  // There are no apps available to open the URL.
6029             // Show a snackbar with the error.
6030             Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
6031         }
6032     }
6033
6034     private fun openWithBrowser(url: String) {
6035
6036         // Create an open with browser intent with `ACTION_VIEW`.
6037         val openWithBrowserIntent = Intent(Intent.ACTION_VIEW)
6038
6039         // Set the URI and the MIME type.  `"text/html"` should load browser options.
6040         openWithBrowserIntent.setDataAndType(Uri.parse(url), "text/html")
6041
6042         // Flag the intent to open in a new task.
6043         openWithBrowserIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
6044
6045         // Try the intent.
6046         try {
6047             // Show the chooser.
6048             startActivity(openWithBrowserIntent)
6049         } catch (exception: ActivityNotFoundException) {  // There are no browsers available to open the URL.
6050             // Show a snackbar with the error.
6051             Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
6052         }
6053     }
6054
6055     override fun pinnedErrorGoBack() {
6056         // Navigate back one page.
6057         navigateHistory(-1)
6058     }
6059
6060     private fun sanitizeUrl(urlString: String): String {
6061         // Initialize a sanitized URL string.
6062         var sanitizedUrlString = urlString
6063
6064         // Sanitize tracking queries.
6065         if (sanitizeTrackingQueries)
6066             sanitizedUrlString = SanitizeUrlHelper.sanitizeTrackingQueries(sanitizedUrlString)
6067
6068         // Sanitize AMP redirects.
6069         if (sanitizeAmpRedirects)
6070             sanitizedUrlString = SanitizeUrlHelper.sanitizeAmpRedirects(sanitizedUrlString)
6071
6072         // Return the sanitized URL string.
6073         return sanitizedUrlString
6074     }
6075
6076     override fun saveWithAndroidDownloadManager(dialogFragment: DialogFragment) {
6077         // Get the dialog.
6078         val dialog = dialogFragment.dialog!!
6079
6080         // Get handles for the dialog views.
6081         val dialogUrlEditText = dialog.findViewById<EditText>(R.id.url_edittext)
6082         val downloadDirectoryRadioGroup = dialog.findViewById<RadioGroup>(R.id.download_directory_radiogroup)
6083         val dialogFileNameEditText = dialog.findViewById<EditText>(R.id.file_name_edittext)
6084
6085         // Get the string from the edit texts, which may have been modified by the user.
6086         val saveUrlString = dialogUrlEditText.text.toString()
6087         val fileNameString = dialogFileNameEditText.text.toString()
6088
6089         // Get a handle for the system download service.
6090         val downloadManager = getSystemService(DOWNLOAD_SERVICE) as DownloadManager
6091
6092         // Parse the URL.
6093         val downloadRequest = DownloadManager.Request(Uri.parse(saveUrlString))
6094
6095         // Pass cookies to download manager if cookies are enabled.  This is required to download files from websites that require a login.
6096         // Code contributed 2017 Hendrik Knackstedt.  Copyright assigned to Soren Stoutner <soren@stoutner.com>.
6097         if (cookieManager.acceptCookie()) {
6098             // Get the cookies for the URL.
6099             val cookiesString = cookieManager.getCookie(saveUrlString)
6100
6101             // Add the cookies to the download request.  In the HTTP request header, cookies are named `Cookie`.
6102             downloadRequest.addRequestHeader("Cookie", cookiesString)
6103         }
6104
6105         // Get the download directory.
6106         val downloadDirectory = when (downloadDirectoryRadioGroup.checkedRadioButtonId) {
6107             R.id.downloads_radiobutton -> Environment.DIRECTORY_DOWNLOADS
6108             R.id.documents_radiobutton -> Environment.DIRECTORY_DOCUMENTS
6109             R.id.pictures_radiobutton -> Environment.DIRECTORY_PICTURES
6110             else -> Environment.DIRECTORY_MUSIC
6111         }
6112
6113         // Set the download destination.
6114         downloadRequest.setDestinationInExternalPublicDir(downloadDirectory, fileNameString)
6115
6116         // Allow media scanner to index the download if it is a media file.  This is automatic for API >= 29.
6117         @Suppress("DEPRECATION")
6118         if (Build.VERSION.SDK_INT <= 28)
6119             downloadRequest.allowScanningByMediaScanner()
6120
6121         // Add the URL as the description for the download.
6122         downloadRequest.setDescription(saveUrlString)
6123
6124         // Show the download notification after the download is completed.
6125         downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
6126
6127         // Initiate the download.
6128         downloadManager.enqueue(downloadRequest)
6129     }
6130
6131     private fun saveWithExternalApp(url: String) {
6132         // Create a download intent.  Not specifying the action type will display the maximum number of options.
6133         val downloadIntent = Intent()
6134
6135         // Set the URI and the mime type.
6136         downloadIntent.setDataAndType(Uri.parse(url), "text/html")
6137
6138         // Flag the intent to open in a new task.
6139         downloadIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
6140
6141         // Show the chooser.
6142         startActivity(Intent.createChooser(downloadIntent, getString(R.string.download_with_external_app)))
6143     }
6144
6145     override fun saveWithPrivacyBrowser(originalUrlString: String, fileNameString: String, dialogFragment: DialogFragment) {
6146         // Store the URL.  This will be used in the save URL activity result launcher.
6147         saveUrlString = if (originalUrlString.startsWith("data:")) {
6148             // Save the original URL.
6149             originalUrlString
6150         } else {
6151             // Get the dialog.
6152             val dialog = dialogFragment.dialog!!
6153
6154             // Get a handle for the dialog URL edit text.
6155             val dialogUrlEditText = dialog.findViewById<EditText>(R.id.url_edittext)
6156
6157             // Get the URL from the edit text, which may have been modified by the user.
6158             dialogUrlEditText.text.toString()
6159         }
6160
6161         // Open the file picker.
6162         saveUrlActivityResultLauncher.launch(fileNameString)
6163     }
6164
6165     private fun setCurrentWebView(pageNumber: Int) {
6166         // Stop the swipe to refresh indicator if it is running
6167         swipeRefreshLayout.isRefreshing = false
6168
6169         // Try to set the current WebView.  This will fail if the WebView has not yet been populated.
6170         try {
6171             // Get the WebView tab fragment.
6172             val webViewTabFragment = webViewStateAdapter!!.getPageFragment(pageNumber)
6173
6174             // Get the fragment view.
6175             val webViewFragmentView = webViewTabFragment.view
6176
6177             // Store the current WebView.
6178             currentWebView = webViewFragmentView!!.findViewById(R.id.nestedscroll_webview)
6179
6180             // Update the status of swipe to refresh.
6181             if (currentWebView!!.swipeToRefresh) {  // Swipe to refresh is enabled.
6182                 // Enable the swipe refresh layout if the WebView is scrolled all the way to the top.  It is updated every time the scroll changes.
6183                 swipeRefreshLayout.isEnabled = (currentWebView!!.scrollY == 0)
6184             } else {  // Swipe to refresh is disabled.
6185                 // Disable the swipe refresh layout.
6186                 swipeRefreshLayout.isEnabled = false
6187             }
6188
6189             // Set the cookie status.
6190             cookieManager.setAcceptCookie(currentWebView!!.acceptCookies)
6191
6192             // Update the privacy icons.  `true` redraws the icons in the app bar.
6193             updatePrivacyIcons(true)
6194
6195             // Get a handle for the input method manager.
6196             val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
6197
6198             // Get the current URL.
6199             val urlString = currentWebView!!.url
6200
6201             // Update the URL edit text if not loading a new intent.  Otherwise, this will be handled by `onPageStarted()` (if called) and `onPageFinished()`.
6202             if (!loadingNewIntent) {  // A new intent is not being loaded.
6203                 if ((urlString == null) || (urlString == "about:blank")) {  // The WebView is blank.
6204                     // Display the hint in the URL edit text.
6205                     urlEditText.setText("")
6206
6207                     // Request focus for the URL text box.
6208                     urlEditText.requestFocus()
6209
6210                     // Display the keyboard.
6211                     inputMethodManager.showSoftInput(urlEditText, 0)
6212                 } else {  // The WebView has a loaded URL.
6213                     // Clear the focus from the URL text box.
6214                     urlEditText.clearFocus()
6215
6216                     // Hide the soft keyboard.
6217                     inputMethodManager.hideSoftInputFromWindow(currentWebView!!.windowToken, 0)
6218
6219                     // Display the current URL in the URL text box.
6220                     urlEditText.setText(urlString)
6221
6222                     // Highlight the URL syntax.
6223                     UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
6224                 }
6225             } else {  // A new intent is being loaded.
6226                 // Reset the loading new intent flag.
6227                 loadingNewIntent = false
6228             }
6229
6230             // Set the background to indicate the domain settings status.
6231             if (currentWebView!!.domainSettingsApplied) {
6232                 // Set a background on the URL relative layout to indicate that custom domain settings are being used.
6233                 urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.drawable.domain_settings_url_background)
6234             } else {
6235                 // Remove any background on the URL relative layout.
6236                 urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.color.transparent)
6237             }
6238         }  catch (exception: Exception) {  //  Try again in 10 milliseconds if the WebView has not yet been populated.
6239             // Create a handler to set the current WebView.
6240             val setCurrentWebViewHandler = Handler(Looper.getMainLooper())
6241
6242             // Create a runnable to set the current WebView.
6243             val setCurrentWebWebRunnable = Runnable {
6244                 // Set the current WebView.
6245                 setCurrentWebView(pageNumber)
6246             }
6247
6248             // Try setting the current WebView again after 10 milliseconds.
6249             setCurrentWebViewHandler.postDelayed(setCurrentWebWebRunnable, 10)
6250         }
6251     }
6252
6253     // The view parameter cannot be removed because it is called from the layout onClick.
6254     fun toggleBookmarksDrawerPinned(@Suppress("UNUSED_PARAMETER")view: View?) {
6255         // Toggle the bookmarks drawer pinned tracker.
6256         bookmarksDrawerPinned = !bookmarksDrawerPinned
6257
6258         // Update the bookmarks drawer pinned image view.
6259         updateBookmarksDrawerPinnedImageView()
6260     }
6261
6262     private fun updateBookmarksDrawerPinnedImageView() {
6263         // Set the current icon.
6264         if (bookmarksDrawerPinned)
6265             bookmarksDrawerPinnedImageView.setImageResource(R.drawable.pin_selected)
6266         else
6267             bookmarksDrawerPinnedImageView.setImageResource(R.drawable.pin)
6268     }
6269
6270     private fun updateDomainsSettingsSet() {
6271         // Reset the domains settings set.
6272         domainsSettingsSet = HashSet()
6273
6274         // Get a domains cursor.
6275         val domainsCursor = domainsDatabaseHelper!!.domainNameCursorOrderedByDomain
6276
6277         // Get the current count of domains.
6278         val domainsCount = domainsCursor.count
6279
6280         // Get the domain name column index.
6281         val domainNameColumnIndex = domainsCursor.getColumnIndexOrThrow(DOMAIN_NAME)
6282
6283         // Populate the domain settings set.
6284         for (i in 0 until domainsCount) {
6285             // Move the domains cursor to the current row.
6286             domainsCursor.moveToPosition(i)
6287
6288             // Store the domain name in the domain settings set.
6289             domainsSettingsSet.add(domainsCursor.getString(domainNameColumnIndex))
6290         }
6291
6292         // Close the domains cursor.
6293         domainsCursor.close()
6294     }
6295
6296     override fun updateFontSize(dialogFragment: DialogFragment) {
6297         // Get the dialog.
6298         val dialog = dialogFragment.dialog!!
6299
6300         // Get a handle for the font size edit text.
6301         val fontSizeEditText = dialog.findViewById<EditText>(R.id.font_size_edittext)
6302
6303         // Initialize the new font size variable with the current font size.
6304         var newFontSize = currentWebView!!.settings.textZoom
6305
6306         // Get the font size from the edit text.
6307         try {
6308             newFontSize = fontSizeEditText.text.toString().toInt()
6309         } catch (exception: Exception) {
6310             // If the edit text does not contain a valid font size do nothing.
6311         }
6312
6313         // Apply the new font size.
6314         currentWebView!!.settings.textZoom = newFontSize
6315     }
6316
6317     private fun updatePrivacyIcons(runInvalidateOptionsMenu: Boolean) {
6318         // Only update the privacy icons if the options menu and the current WebView have already been populated.
6319         if ((optionsMenu != null) && (currentWebView != null)) {
6320             // Update the privacy icon.
6321             if (currentWebView!!.settings.javaScriptEnabled)  // JavaScript is enabled.
6322                 optionsPrivacyMenuItem.setIcon(R.drawable.javascript_enabled)
6323             else if (currentWebView!!.acceptCookies)  // JavaScript is disabled but cookies are enabled.
6324                 optionsPrivacyMenuItem.setIcon(R.drawable.warning)
6325             else  // All the dangerous features are disabled.
6326                 optionsPrivacyMenuItem.setIcon(R.drawable.privacy_mode)
6327
6328             // Update the cookies icon.
6329             if (currentWebView!!.acceptCookies)
6330                 optionsCookiesMenuItem.setIcon(R.drawable.cookies_enabled)
6331             else
6332                 optionsCookiesMenuItem.setIcon(R.drawable.cookies_disabled)
6333
6334             // Update the refresh icon.
6335             if (optionsRefreshMenuItem.title == getString(R.string.refresh))  // The refresh icon is displayed.
6336                 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled)
6337             else  // The stop icon is displayed.
6338                 optionsRefreshMenuItem.setIcon(R.drawable.close_blue)
6339
6340             // `invalidateOptionsMenu()` calls `onPrepareOptionsMenu()` and redraws the icons in the app bar.
6341             if (runInvalidateOptionsMenu)
6342                 invalidateOptionsMenu()
6343         }
6344     }
6345 }