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