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