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