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