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