]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/activities/MainWebViewActivity.kt
0d9755f1f21d2621716c6f678ad5d3da6f025332
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / activities / MainWebViewActivity.kt
1 /*
2  * Copyright 2015-2024 Soren Stoutner <soren@stoutner.com>.
3  *
4  * Download cookie code contributed 2017 Hendrik Knackstedt.  Copyright assigned to Soren Stoutner <soren@stoutner.com>.
5  *
6  * This file is part of Privacy Browser Android <https://www.stoutner.com/privacy-browser-android>.
7  *
8  * Privacy Browser Android is free software: you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation, either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * Privacy Browser Android is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with Privacy Browser Android.  If not, see <http://www.gnu.org/licenses/>.
20  */
21
22 package com.stoutner.privacybrowser.activities
23
24 import android.animation.ObjectAnimator
25 import android.annotation.SuppressLint
26 import android.app.DownloadManager
27 import android.app.SearchManager
28 import android.content.ActivityNotFoundException
29 import android.content.BroadcastReceiver
30 import android.content.ClipData
31 import android.content.ClipboardManager
32 import android.content.Context
33 import android.content.Intent
34 import android.content.IntentFilter
35 import android.content.SharedPreferences
36 import android.content.pm.PackageManager
37 import android.content.res.Configuration
38 import android.database.Cursor
39 import android.graphics.Bitmap
40 import android.graphics.BitmapFactory
41 import android.graphics.Typeface
42 import android.graphics.drawable.BitmapDrawable
43 import android.net.Uri
44 import android.net.http.SslError
45 import android.os.Build
46 import android.os.Bundle
47 import android.os.Environment
48 import android.os.Handler
49 import android.os.Looper
50 import android.print.PrintManager
51 import android.provider.DocumentsContract
52 import android.provider.OpenableColumns
53 import android.text.Editable
54 import android.text.TextWatcher
55 import android.text.style.ForegroundColorSpan
56 import android.util.Patterns
57 import android.util.TypedValue
58 import android.view.ContextMenu
59 import android.view.GestureDetector
60 import android.view.KeyEvent
61 import android.view.Menu
62 import android.view.MenuItem
63 import android.view.MotionEvent
64 import android.view.View
65 import android.view.ViewGroup
66 import android.view.WindowManager
67 import android.view.inputmethod.InputMethodManager
68 import android.webkit.CookieManager
69 import android.webkit.HttpAuthHandler
70 import android.webkit.ValueCallback
71 import android.webkit.SslErrorHandler
72 import android.webkit.WebChromeClient
73 import android.webkit.WebResourceRequest
74 import android.webkit.WebResourceResponse
75 import android.webkit.WebSettings
76 import android.webkit.WebStorage
77 import android.webkit.WebView
78 import android.webkit.WebViewClient
79 import android.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 WebView pager adapter.
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_IP_ADDRESSES, currentWebView!!.currentIpAddresses)
2118
2119                     // Get the current certificate.
2120                     val sslCertificate = currentWebView!!.certificate
2121
2122                     // Check to see if the SSL certificate is populated.
2123                     if (sslCertificate != null) {
2124                         // Extract the certificate to strings.
2125                         val issuedToCName = sslCertificate.issuedTo.cName
2126                         val issuedToOName = sslCertificate.issuedTo.oName
2127                         val issuedToUName = sslCertificate.issuedTo.uName
2128                         val issuedByCName = sslCertificate.issuedBy.cName
2129                         val issuedByOName = sslCertificate.issuedBy.oName
2130                         val issuedByUName = sslCertificate.issuedBy.uName
2131                         val startDateLong = sslCertificate.validNotBeforeDate.time
2132                         val endDateLong = sslCertificate.validNotAfterDate.time
2133
2134                         // Add the certificate to the intent.
2135                         domainsIntent.putExtra(SSL_ISSUED_TO_CNAME, issuedToCName)
2136                         domainsIntent.putExtra(SSL_ISSUED_TO_ONAME, issuedToOName)
2137                         domainsIntent.putExtra(SSL_ISSUED_TO_UNAME, issuedToUName)
2138                         domainsIntent.putExtra(SSL_ISSUED_BY_CNAME, issuedByCName)
2139                         domainsIntent.putExtra(SSL_ISSUED_BY_ONAME, issuedByOName)
2140                         domainsIntent.putExtra(SSL_ISSUED_BY_UNAME, issuedByUName)
2141                         domainsIntent.putExtra(SSL_START_DATE, startDateLong)
2142                         domainsIntent.putExtra(SSL_END_DATE, endDateLong)
2143                     }
2144
2145                     // Make it so.
2146                     startActivity(domainsIntent)
2147                 } else {  // Add a new domain.
2148                     // Get the current URI.
2149                     val currentUri = Uri.parse(currentWebView!!.url)
2150
2151                     // Get the current domain from the URI.  Use an empty string if it is null.
2152                     val currentDomain = currentUri.host?: ""
2153
2154                     // Get the current settings status.
2155                     val javaScriptInt = calculateSettingsInt(currentWebView!!.settings.javaScriptEnabled, sharedPreferences.getBoolean(getString(R.string.javascript_key), false))
2156                     val cookiesInt = calculateSettingsInt(currentWebView!!.acceptCookies, sharedPreferences.getBoolean(getString(R.string.cookies_key), false))
2157                     val domStorageInt = calculateSettingsInt(currentWebView!!.settings.domStorageEnabled, sharedPreferences.getBoolean(getString(R.string.dom_storage_key), false))
2158                     val easyListInt = calculateSettingsInt(currentWebView!!.easyListEnabled, sharedPreferences.getBoolean(getString(R.string.easylist_key), true))
2159                     val easyPrivacyInt = calculateSettingsInt(currentWebView!!.easyPrivacyEnabled, sharedPreferences.getBoolean(getString(R.string.easyprivacy_key), true))
2160                     val fanboysAnnoyanceListInt = calculateSettingsInt(currentWebView!!.fanboysAnnoyanceListEnabled, sharedPreferences.getBoolean(getString(R.string.fanboys_annoyance_list_key), true))
2161                     val fanboysSocialBlockingListInt = calculateSettingsInt(currentWebView!!.fanboysSocialBlockingListEnabled, sharedPreferences.getBoolean(getString(R.string.fanboys_social_blocking_list_key), true))
2162                     val ultraListInt = calculateSettingsInt(currentWebView!!.ultraListEnabled, sharedPreferences.getBoolean(getString(R.string.ultralist_key), true))
2163                     val ultraPrivacyInt = calculateSettingsInt(currentWebView!!.ultraPrivacyEnabled, sharedPreferences.getBoolean(getString(R.string.ultraprivacy_key), true))
2164                     val blockAllThirdPartyRequestsInt = calculateSettingsInt(currentWebView!!.blockAllThirdPartyRequests, sharedPreferences.getBoolean(getString(R.string.block_all_third_party_requests_key), true))
2165                     val swipeToRefreshInt = calculateSettingsInt(currentWebView!!.swipeToRefresh, sharedPreferences.getBoolean(getString(R.string.swipe_to_refresh_key), true))
2166                     val wideViewportInt = calculateSettingsInt(currentWebView!!.settings.useWideViewPort, sharedPreferences.getBoolean(getString(R.string.wide_viewport_key), true))
2167                     val displayImagesInt = calculateSettingsInt(currentWebView!!.settings.loadsImagesAutomatically, sharedPreferences.getBoolean(getString(R.string.display_webpage_images_key), true))
2168
2169                     // Initialize the form data int.
2170                     var formDataInt = SYSTEM_DEFAULT
2171
2172                     // Set the form data int, which can be removed once the minimum API >= 26.
2173                     @Suppress("DEPRECATION")
2174                     if (Build.VERSION.SDK_INT < 26) {
2175                         // Get the form data status.
2176                         val formDataEnabled = currentWebView!!.settings.saveFormData
2177
2178                         // Calculate the form data Int.
2179                         formDataInt = calculateSettingsInt(formDataEnabled, sharedPreferences.getBoolean(getString(R.string.save_form_data_key), false))
2180                     }
2181
2182                     // Get the current user agent string.
2183                     val currentUserAgentString = currentWebView!!.settings.userAgentString
2184
2185                     // Get the user agent string array position.
2186                     val userAgentStringArrayPosition = userAgentDataArrayAdapter.getPosition(currentUserAgentString)
2187
2188                     // Set the user agent name.
2189                     val userAgentName = if ((userAgentStringArrayPosition >= 0) && (defaultUserAgentName == userAgentNamesArray[userAgentStringArrayPosition])) {  // The system default user agent is in use.
2190                         getString(R.string.system_default_user_agent)
2191                     } else {  // An on-the-fly user agent is being used (or the WebView default user agent is applied).
2192                         when (userAgentStringArrayPosition) {
2193                             UNRECOGNIZED_USER_AGENT -> { // The user agent is unrecognized.
2194                                 if (currentUserAgentString == webViewDefaultUserAgent) {  // The WebView default user agent is being used.
2195                                     if (defaultUserAgentName == getString(R.string.webview_default)) {  // The WebView default user agent is the system default.
2196                                         // Set the user agent name to be the system default.
2197                                         getString(R.string.system_default_user_agent)
2198                                     } else {  // The WebView default user agent is set as an on-the-fly setting.
2199                                         // Set the default user agent name.
2200                                         getString(R.string.webview_default)
2201                                     }
2202                                 } else {  // A custom user agent is being used.
2203                                     if (defaultUserAgentName == getString(R.string.custom_user_agent_non_translatable)) {  // The system custom user agent is in use.
2204                                         // Set the user agent name to be the system default.
2205                                         getString(R.string.system_default_user_agent)
2206                                     } else {  // An on-the-fly custom user agent is in use.
2207                                         // Store the user agent as currently applied.
2208                                         currentUserAgentString
2209                                     }
2210                                 }
2211                             }
2212
2213                             else ->  // Store the standard user agent name.
2214                                 userAgentNamesArray[userAgentStringArrayPosition]
2215                         }
2216                     }
2217
2218                     // Get the current text zoom integer.
2219                     val textZoomInt = currentWebView!!.settings.textZoom
2220
2221                     // Set the font size integer.
2222                     val fontSizeInt = if (textZoomInt == defaultFontSizeString.toInt())  // The current system default is used, which is encoded as a zoom of `0`.
2223                         SYSTEM_DEFAULT
2224                     else  // A custom font size is used.
2225                         textZoomInt
2226
2227                     // Get the current WebView dark theme status.
2228                     val webViewDarkThemeCurrentlyEnabled = if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING))  // Algorithmic darkening is supported.
2229                         WebSettingsCompat.isAlgorithmicDarkeningAllowed(currentWebView!!.settings)
2230                     else  // Algorithmic darkening is not supported.
2231                         false
2232
2233                     // Get the default WebView dark theme setting.
2234                     val defaultWebViewDarkThemeEnabled = if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {  // Algorithmic darkening is supported.
2235                         when (defaultWebViewTheme) {
2236                             webViewThemeEntryValuesStringArray[1] ->  // The dark theme is disabled by default.
2237                                 false
2238
2239                             webViewThemeEntryValuesStringArray[2] ->  // The dark theme is enabled by default.
2240                                 true
2241
2242                             else -> {  // The system default theme is selected.
2243                                 // Get the current app theme status.
2244                                 val currentAppThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
2245
2246                                 // Check if the current app theme is dark.
2247                                 currentAppThemeStatus == Configuration.UI_MODE_NIGHT_YES
2248                             }
2249                         }
2250                     } else {  // Algorithmic darkening is not supported.
2251                         false
2252                     }
2253
2254                     // Set the WebView theme int.
2255                     val webViewThemeInt = if (webViewDarkThemeCurrentlyEnabled == defaultWebViewDarkThemeEnabled)  // The current WebView theme matches the default.
2256                         SYSTEM_DEFAULT
2257                     else if (webViewDarkThemeCurrentlyEnabled)  // The current WebView theme is dark and that is not the default.
2258                         DARK_THEME
2259                     else  // The current WebView theme is light and that is not the default.
2260                         LIGHT_THEME
2261
2262                     // Create the domain and store the database ID.
2263                     val newDomainDatabaseId = domainsDatabaseHelper!!.addDomain(currentDomain, javaScriptInt, cookiesInt, domStorageInt, formDataInt, userAgentName, easyListInt, easyPrivacyInt,
2264                                                                                 fanboysAnnoyanceListInt, fanboysSocialBlockingListInt, ultraListInt, ultraPrivacyInt, blockAllThirdPartyRequestsInt, fontSizeInt,
2265                                                                                 swipeToRefreshInt, webViewThemeInt, wideViewportInt, displayImagesInt)
2266
2267                     // Create an intent to launch the domains activity.
2268                     val domainsIntent = Intent(this, DomainsActivity::class.java)
2269
2270                     // Add the extra information to the intent.
2271                     domainsIntent.putExtra(LOAD_DOMAIN, newDomainDatabaseId)
2272                     domainsIntent.putExtra(CLOSE_ON_BACK, true)
2273                     domainsIntent.putExtra(CURRENT_IP_ADDRESSES, currentWebView!!.currentIpAddresses)
2274
2275                     // Get the current certificate.
2276                     val sslCertificate = currentWebView!!.certificate
2277
2278                     // Check to see if the SSL certificate is populated.
2279                     if (sslCertificate != null) {
2280                         // Extract the certificate to strings.
2281                         val issuedToCName = sslCertificate.issuedTo.cName
2282                         val issuedToOName = sslCertificate.issuedTo.oName
2283                         val issuedToUName = sslCertificate.issuedTo.uName
2284                         val issuedByCName = sslCertificate.issuedBy.cName
2285                         val issuedByOName = sslCertificate.issuedBy.oName
2286                         val issuedByUName = sslCertificate.issuedBy.uName
2287                         val startDateLong = sslCertificate.validNotBeforeDate.time
2288                         val endDateLong = sslCertificate.validNotAfterDate.time
2289
2290                         // Add the certificate to the intent.
2291                         domainsIntent.putExtra(SSL_ISSUED_TO_CNAME, issuedToCName)
2292                         domainsIntent.putExtra(SSL_ISSUED_TO_ONAME, issuedToOName)
2293                         domainsIntent.putExtra(SSL_ISSUED_TO_UNAME, issuedToUName)
2294                         domainsIntent.putExtra(SSL_ISSUED_BY_CNAME, issuedByCName)
2295                         domainsIntent.putExtra(SSL_ISSUED_BY_ONAME, issuedByOName)
2296                         domainsIntent.putExtra(SSL_ISSUED_BY_UNAME, issuedByUName)
2297                         domainsIntent.putExtra(SSL_START_DATE, startDateLong)
2298                         domainsIntent.putExtra(SSL_END_DATE, endDateLong)
2299                     }
2300
2301                     // Make it so.
2302                     startActivity(domainsIntent)
2303                 }
2304
2305                 // Consume the event.
2306                 true
2307             }
2308
2309             else -> {  // There is no match with the options menu.  Pass the event up to the parent method.
2310                 // Don't consume the event.
2311                 super.onOptionsItemSelected(menuItem)
2312             }
2313         }
2314     }
2315
2316     override fun onNavigationItemSelected(menuItem: MenuItem): Boolean {
2317         // Run the commands that correspond to the selected menu item.
2318         when (menuItem.itemId) {
2319             R.id.clear_and_exit -> {  // Clear and exit.
2320                 // Clear and exit Privacy Browser.
2321                 clearAndExit()
2322             }
2323
2324             R.id.home -> {  // Home.
2325                 // Load the homepage.
2326                 loadUrl(currentWebView!!, sharedPreferences.getString(getString(R.string.homepage_key), getString(R.string.homepage_default_value))!!)
2327             }
2328
2329             R.id.back -> {  // Back.
2330                 // Check if the WebView can go back.
2331                 if (currentWebView!!.canGoBack()) {
2332                     // Get the current web back forward list.
2333                     val webBackForwardList = currentWebView!!.copyBackForwardList()
2334
2335                     // Get the previous entry data.
2336                     val previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex - 1).url
2337                     val previousFavoriteIcon = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex - 1).favicon!!
2338
2339                     // Apply the domain settings.
2340                     applyDomainSettings(currentWebView!!, previousUrl, resetTab = false, reloadWebsite = false, loadUrl = false)
2341
2342                     // Get the current tab.
2343                     val tab = tabLayout.getTabAt(tabLayout.selectedTabPosition)!!
2344
2345                     // Get the custom view from the tab.
2346                     val tabView = tab.customView!!
2347
2348                     // Get the favorite icon image view from the tab.
2349                     val tabFavoriteIconImageView = tabView.findViewById<ImageView>(R.id.favorite_icon_imageview)
2350
2351                     // Set the previous favorite icon.
2352                     tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(previousFavoriteIcon, 64, 64, true))
2353
2354                     // Load the previous website in the history.
2355                     currentWebView!!.goBack()
2356
2357                     // Update the URL edit text after a delay.
2358                     updateUrlEditTextAfterDelay()
2359                 }
2360             }
2361
2362             R.id.forward -> {  // Forward.
2363                 // Check if the WebView can go forward.
2364                 if (currentWebView!!.canGoForward()) {
2365                     // Get the current web back forward list.
2366                     val webBackForwardList = currentWebView!!.copyBackForwardList()
2367
2368                     // Get the next entry data.
2369                     val nextUrl = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex + 1).url
2370                     val nextFavoriteIcon = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex + 1).favicon!!
2371
2372                     // Apply the domain settings.
2373                     applyDomainSettings(currentWebView!!, nextUrl, resetTab = false, reloadWebsite = false, loadUrl = false)
2374
2375                     // Get the current tab.
2376                     val tab = tabLayout.getTabAt(tabLayout.selectedTabPosition)!!
2377
2378                     // Get the custom view from the tab.
2379                     val tabView = tab.customView!!
2380
2381                     // Get the favorite icon image view from the tab.
2382                     val tabFavoriteIconImageView = tabView.findViewById<ImageView>(R.id.favorite_icon_imageview)
2383
2384                     // Set the next favorite icon.
2385                     tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nextFavoriteIcon, 64, 64, true))
2386
2387                     // Load the next website in the history.
2388                     currentWebView!!.goForward()
2389
2390                     // Update the URL edit text after a delay.
2391                     updateUrlEditTextAfterDelay()
2392                 }
2393             }
2394
2395             R.id.scroll_to_bottom -> {  // Scroll to Bottom.
2396                 // Check if the WebView is scrolled to the top.
2397                 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.
2398                     currentWebView!!.scrollTo(0, 1_000_000_000)
2399                 } else {  // The WebView is not at the top; scroll to the top.
2400                     currentWebView!!.scrollTo(0, 0)
2401                 }
2402             }
2403
2404             R.id.history -> {  // History.
2405                 // Instantiate the URL history dialog.
2406                 val urlHistoryDialogFragment: DialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView!!.webViewFragmentId)
2407
2408                 // Show the URL history dialog.
2409                 urlHistoryDialogFragment.show(supportFragmentManager, getString(R.string.history))
2410             }
2411
2412             R.id.open -> {  // Open.
2413                 // Instantiate the open file dialog.
2414                 val openDialogFragment: DialogFragment = OpenDialog()
2415
2416                 // Show the open file dialog.
2417                 openDialogFragment.show(supportFragmentManager, getString(R.string.open))
2418             }
2419
2420             R.id.requests -> {  // Requests.
2421                 // Populate the resource requests.
2422                 RequestsActivity.resourceRequests = currentWebView!!.getResourceRequests()
2423
2424                 // Create an intent to launch the Requests activity.
2425                 val requestsIntent = Intent(this, RequestsActivity::class.java)
2426
2427                 // Add the block third-party requests status to the intent.
2428                 requestsIntent.putExtra(BLOCK_ALL_THIRD_PARTY_REQUESTS, currentWebView!!.blockAllThirdPartyRequests)
2429
2430                 // Make it so.
2431                 startActivity(requestsIntent)
2432             }
2433
2434             R.id.downloads -> {  // Downloads.
2435                 // Try the default system download manager.
2436                 try {
2437                     // Launch the default system Download Manager.
2438                     val defaultDownloadManagerIntent = Intent(DownloadManager.ACTION_VIEW_DOWNLOADS)
2439
2440                     // Launch as a new task so that the download manager and Privacy Browser show as separate windows in the recent tasks list.
2441                     defaultDownloadManagerIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2442
2443                     // Make it so.
2444                     startActivity(defaultDownloadManagerIntent)
2445                 } catch (defaultDownloadManagerException: Exception) {  // The system download manager is not available.
2446                     // Try a generic file manager.
2447                     try {
2448                         // Create a generic file manager intent.
2449                         val genericFileManagerIntent = Intent(Intent.ACTION_VIEW)
2450
2451                         // Open the download directory.
2452                         genericFileManagerIntent.setDataAndType(Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()), DocumentsContract.Document.MIME_TYPE_DIR)
2453
2454                         // Launch as a new task so that the file manager and Privacy Browser show as separate windows in the recent tasks list.
2455                         genericFileManagerIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2456
2457                         // Make it so.
2458                         startActivity(genericFileManagerIntent)
2459                     } catch (genericFileManagerException: Exception) {  // A generic file manager is not available.
2460                         // Try an alternate file manager.
2461                         try {
2462                             // Create an alternate file manager intent.
2463                             val alternateFileManagerIntent = Intent(Intent.ACTION_VIEW)
2464
2465                             // Open the download directory.
2466                             alternateFileManagerIntent.setDataAndType(Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()), "resource/folder")
2467
2468                             // Launch as a new task so that the file manager and Privacy Browser show as separate windows in the recent tasks list.
2469                             alternateFileManagerIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2470
2471                             // Open the alternate file manager.
2472                             startActivity(alternateFileManagerIntent)
2473                         } catch (alternateFileManagerException: Exception) {
2474                             // Display a snackbar.
2475                             Snackbar.make(currentWebView!!, R.string.no_file_manager_detected, Snackbar.LENGTH_INDEFINITE).show()
2476                         }
2477                     }
2478                 }
2479             }
2480
2481             R.id.domains -> {  // Domains.
2482                 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2483                 reapplyDomainSettingsOnRestart = true
2484
2485                 // Create a domains activity intent.
2486                 val domainsIntent = Intent(this, DomainsActivity::class.java)
2487
2488                 // Add the extra information to the intent.
2489                 domainsIntent.putExtra(CURRENT_IP_ADDRESSES, currentWebView!!.currentIpAddresses)
2490
2491                 // Get the current certificate.
2492                 val sslCertificate = currentWebView!!.certificate
2493
2494                 // Check to see if the SSL certificate is populated.
2495                 if (sslCertificate != null) {
2496                     // Extract the certificate to strings.
2497                     val issuedToCName = sslCertificate.issuedTo.cName
2498                     val issuedToOName = sslCertificate.issuedTo.oName
2499                     val issuedToUName = sslCertificate.issuedTo.uName
2500                     val issuedByCName = sslCertificate.issuedBy.cName
2501                     val issuedByOName = sslCertificate.issuedBy.oName
2502                     val issuedByUName = sslCertificate.issuedBy.uName
2503                     val startDateLong = sslCertificate.validNotBeforeDate.time
2504                     val endDateLong = sslCertificate.validNotAfterDate.time
2505
2506                     // Add the certificate to the intent.
2507                     domainsIntent.putExtra(SSL_ISSUED_TO_CNAME, issuedToCName)
2508                     domainsIntent.putExtra(SSL_ISSUED_TO_ONAME, issuedToOName)
2509                     domainsIntent.putExtra(SSL_ISSUED_TO_UNAME, issuedToUName)
2510                     domainsIntent.putExtra(SSL_ISSUED_BY_CNAME, issuedByCName)
2511                     domainsIntent.putExtra(SSL_ISSUED_BY_ONAME, issuedByOName)
2512                     domainsIntent.putExtra(SSL_ISSUED_BY_UNAME, issuedByUName)
2513                     domainsIntent.putExtra(SSL_START_DATE, startDateLong)
2514                     domainsIntent.putExtra(SSL_END_DATE, endDateLong)
2515                 }
2516
2517                 // Make it so.
2518                 startActivity(domainsIntent)
2519             }
2520
2521             R.id.settings -> {  // Settings.
2522                 // Set the reapply on restart flags.
2523                 reapplyAppSettingsOnRestart = true
2524                 reapplyDomainSettingsOnRestart = true
2525
2526                 // Create a settings intent.
2527                 val settingsIntent = Intent(this, SettingsActivity::class.java)
2528
2529                 // Make it so.
2530                 startActivity(settingsIntent)
2531             }
2532
2533             R.id.import_export -> { // Import/Export.
2534                 // Create an intent to launch the import/export activity.
2535                 val importExportIntent = Intent(this, ImportExportActivity::class.java)
2536
2537                 // Make it so.
2538                 startActivity(importExportIntent)
2539             }
2540
2541             R.id.logcat -> {  // Logcat.
2542                 // Create an intent to launch the logcat activity.
2543                 val logcatIntent = Intent(this, LogcatActivity::class.java)
2544
2545                 // Make it so.
2546                 startActivity(logcatIntent)
2547             }
2548
2549             R.id.webview_devtools -> {  // WebView DevTools.
2550                 // Create a WebView DevTools intent.
2551                 val webViewDevToolsIntent = Intent("com.android.webview.SHOW_DEV_UI")
2552
2553                 // Launch as a new task so that the WebView DevTools and Privacy Browser show as a separate windows in the recent tasks list.
2554                 webViewDevToolsIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2555
2556                 // Make it so.
2557                 startActivity(webViewDevToolsIntent)
2558             }
2559
2560             R.id.guide -> {  // Guide.
2561                 // Create an intent to launch the guide activity.
2562                 val guideIntent = Intent(this, GuideActivity::class.java)
2563
2564                 // Make it so.
2565                 startActivity(guideIntent)
2566             }
2567
2568             R.id.about -> {  // About
2569                 // Create an intent to launch the about activity.
2570                 val aboutIntent = Intent(this, AboutActivity::class.java)
2571
2572                 // Create a string array for the filter list versions.
2573                 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])
2574
2575                 // Add the filter list versions to the intent.
2576                 aboutIntent.putExtra(FILTERLIST_VERSIONS, filterListVersions)
2577
2578                 // Make it so.
2579                 startActivity(aboutIntent)
2580             }
2581         }
2582
2583         // Close the navigation drawer.
2584         drawerLayout.closeDrawer(GravityCompat.START)
2585
2586         // Return true.
2587         return true
2588     }
2589
2590     override fun onCreateContextMenu(contextMenu: ContextMenu, view: View, contextMenuInfo: ContextMenu.ContextMenuInfo?) {
2591         // Get the hit test result.
2592         val hitTestResult = currentWebView!!.hitTestResult
2593
2594         // Define the URL strings.
2595         val imageUrl: String?
2596         val linkUrl: String?
2597
2598         // Get a handle for the clipboard manager.
2599         val clipboardManager = (getSystemService(CLIPBOARD_SERVICE) as ClipboardManager)
2600
2601         // Process the link according to the type.
2602         when (hitTestResult.type) {
2603             // `SRC_ANCHOR_TYPE` is a link.
2604             WebView.HitTestResult.SRC_ANCHOR_TYPE -> {
2605                 // Get the target URL.
2606                 linkUrl = hitTestResult.extra!!
2607
2608                 // Set the target URL as the context menu title.
2609                 contextMenu.setHeaderTitle(linkUrl)
2610
2611                 // Add an open in new tab entry.
2612                 contextMenu.add(R.string.open_in_new_tab).setOnMenuItemClickListener {
2613                     // Load the link URL in a new tab and move to it.
2614                     addNewPage(linkUrl, adjacent = true, moveToTab = true)
2615
2616                     // Consume the event.
2617                     true
2618                 }
2619
2620                 // Add an open in background entry.
2621                 contextMenu.add(R.string.open_in_background).setOnMenuItemClickListener {
2622                     // Load the link URL in a new tab but do not move to it.
2623                     addNewPage(linkUrl, adjacent = true, moveToTab = false)
2624
2625                     // Consume the event.
2626                     true
2627                 }
2628
2629                 // Add an open with app entry.
2630                 contextMenu.add(R.string.open_with_app).setOnMenuItemClickListener {
2631                     // Open the URL with another app.
2632                     openWithApp(linkUrl)
2633
2634                     // Consume the event.
2635                     true
2636                 }
2637
2638                 // Add an open with browser entry.
2639                 contextMenu.add(R.string.open_with_browser).setOnMenuItemClickListener {
2640                     // Open the URL with another browser.
2641                     openWithBrowser(linkUrl)
2642
2643                     // Consume the event.
2644                     true
2645                 }
2646
2647                 // Add a copy URL entry.
2648                 contextMenu.add(R.string.copy_url).setOnMenuItemClickListener {
2649                     // Save the link URL in a clip data.
2650                     val srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl)
2651
2652                     // Set the clip data as the clipboard's primary clip.
2653                     clipboardManager.setPrimaryClip(srcAnchorTypeClipData)
2654
2655                     // Consume the event.
2656                     true
2657                 }
2658
2659                 // Add a Save URL entry.
2660                 contextMenu.add(R.string.save_url).setOnMenuItemClickListener {
2661                     // Check the download preference.
2662                     if (downloadWithExternalApp)  // Download with an external app.
2663                         downloadUrlWithExternalApp(linkUrl)
2664                     else  // Handle the download inside of Privacy Browser.  The dialog will be displayed once the file size and the content disposition have been acquired.
2665                         PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, linkUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
2666
2667                     // Consume the event.
2668                     true
2669                 }
2670
2671                 // Add a Share URL entry.
2672                 contextMenu.add(R.string.share_url).setOnMenuItemClickListener {
2673                     // Create the share intent.
2674                     val shareUrlIntent = Intent(Intent.ACTION_SEND)
2675
2676                     // Add the URL to the intent.
2677                     shareUrlIntent.putExtra(Intent.EXTRA_TEXT, linkUrl)
2678
2679                     // Set the MIME type.
2680                     shareUrlIntent.type = "text/plain"
2681
2682                     // Set the intent to open in a new task.
2683                     shareUrlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
2684
2685                     //Make it so.
2686                     startActivity(Intent.createChooser(shareUrlIntent, getString(R.string.share_url)))
2687
2688                     // Consume the event.
2689                     true
2690                 }
2691
2692                 // Add an empty cancel entry, which by default closes the context menu.
2693                 contextMenu.add(R.string.cancel)
2694             }
2695
2696             // `IMAGE_TYPE` is an image.
2697             WebView.HitTestResult.IMAGE_TYPE -> {
2698                 // Get the image URL.
2699                 imageUrl = hitTestResult.extra!!
2700
2701                 // Set the context menu title.
2702                 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.
2703                     contextMenu.setHeaderTitle(imageUrl.substring(0, 100))
2704                 else  // The image URL does not contain the full image data.  Set the image URL as the title of the context menu.
2705                     contextMenu.setHeaderTitle(imageUrl)
2706
2707                 // Add an open in new tab entry.
2708                 contextMenu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener {
2709                     // Load the image in a new tab.
2710                     addNewPage(imageUrl, adjacent = true, moveToTab = true)
2711
2712                     // Consume the event.
2713                     true
2714                 }
2715
2716                 // Add an open with app entry.
2717                 contextMenu.add(R.string.open_with_app).setOnMenuItemClickListener {
2718                     // Open the image URL with an external app.
2719                     openWithApp(imageUrl)
2720
2721                     // Consume the event.
2722                     true
2723                 }
2724
2725                 // Add an open with browser entry.
2726                 contextMenu.add(R.string.open_with_browser).setOnMenuItemClickListener {
2727                     // Open the image URL with an external browser.
2728                     openWithBrowser(imageUrl)
2729
2730                     // Consume the event.
2731                     true
2732                 }
2733
2734                 // Add a view image entry.
2735                 contextMenu.add(R.string.view_image).setOnMenuItemClickListener {
2736                     // Load the image in the current tab.
2737                     loadUrl(currentWebView!!, imageUrl)
2738
2739                     // Consume the event.
2740                     true
2741                 }
2742
2743                 // Add a save image entry.
2744                 contextMenu.add(R.string.save_image).setOnMenuItemClickListener {
2745                     // Check the download preference.
2746                     if (downloadWithExternalApp) {  // Download with an external app.
2747                         downloadUrlWithExternalApp(imageUrl)
2748                     } else {  // Handle the download inside of Privacy Browser.  The dialog will be displayed once the file size and the content disposition have been acquired.
2749                         PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, imageUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
2750                     }
2751
2752                     // Consume the event.
2753                     true
2754                 }
2755
2756                 // Add a copy URL entry.
2757                 contextMenu.add(R.string.copy_url).setOnMenuItemClickListener {
2758                     // Save the image URL in a clip data.
2759                     val imageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl)
2760
2761                     // Set the clip data as the clipboard's primary clip.
2762                     clipboardManager.setPrimaryClip(imageTypeClipData)
2763
2764                     // Consume the event.
2765                     true
2766                 }
2767
2768                 // Add a Share URL entry.
2769                 contextMenu.add(R.string.share_url).setOnMenuItemClickListener {
2770                     // Create the share intent.
2771                     val shareUrlIntent = Intent(Intent.ACTION_SEND)
2772
2773                     // Add the URL to the intent.
2774                     shareUrlIntent.putExtra(Intent.EXTRA_TEXT, imageUrl)
2775
2776                     // Set the MIME type.
2777                     shareUrlIntent.type = "text/plain"
2778
2779                     // Set the intent to open in a new task.
2780                     shareUrlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
2781
2782                     //Make it so.
2783                     startActivity(Intent.createChooser(shareUrlIntent, getString(R.string.share_url)))
2784
2785                     // Consume the event.
2786                     true
2787                 }
2788
2789                 // Add an empty cancel entry, which by default closes the context menu.
2790                 contextMenu.add(R.string.cancel)
2791             }
2792
2793             // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2794             WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE -> {
2795                 // Get the image URL.
2796                 imageUrl = hitTestResult.extra!!
2797
2798                 // Instantiate a handler.
2799                 val handler = Handler(Looper.getMainLooper())
2800
2801                 // Get a handle for the handler message.
2802                 val message = handler.obtainMessage()
2803
2804                 // Request the image details from the last touched node be returned in the message.
2805                 currentWebView!!.requestFocusNodeHref(message)
2806
2807                 // Get the link URL from the message data.
2808                 linkUrl = message.data.getString("url")!!
2809
2810                 // Set the link URL as the title of the context menu.
2811                 contextMenu.setHeaderTitle(linkUrl)
2812
2813                 // Add an open in new tab entry.
2814                 contextMenu.add(R.string.open_in_new_tab).setOnMenuItemClickListener {
2815                     // Load the link URL in a new tab and move to it.
2816                     addNewPage(linkUrl, adjacent = true, moveToTab = true)
2817
2818                     // Consume the event.
2819                     true
2820                 }
2821
2822                 // Add an open in background entry.
2823                 contextMenu.add(R.string.open_in_background).setOnMenuItemClickListener {
2824                     // Lod the link URL in a new tab but do not move to it.
2825                     addNewPage(linkUrl, adjacent = true, moveToTab = false)
2826
2827                     // Consume the event.
2828                     true
2829                 }
2830
2831                 // Add an open image in new tab entry.
2832                 contextMenu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener {
2833                     // Load the image in a new tab and move to it.
2834                     addNewPage(imageUrl, adjacent = true, moveToTab = true)
2835
2836                     // Consume the event.
2837                     true
2838                 }
2839
2840                 // Add an open with app entry.
2841                 contextMenu.add(R.string.open_with_app).setOnMenuItemClickListener {
2842                     // Open the link URL with an external app.
2843                     openWithApp(linkUrl)
2844
2845                     // Consume the event.
2846                     true
2847                 }
2848
2849                 // Add an open with browser entry.
2850                 contextMenu.add(R.string.open_with_browser).setOnMenuItemClickListener {
2851                     // Open the link URL with an external browser.
2852                     openWithBrowser(linkUrl)
2853
2854                     // Consume the event.
2855                     true
2856                 }
2857
2858                 // Add a view image entry.
2859                 contextMenu.add(R.string.view_image).setOnMenuItemClickListener {
2860                     // View the image in the current tab.
2861                     loadUrl(currentWebView!!, imageUrl)
2862
2863                     // Consume the event.
2864                     true
2865                 }
2866
2867                 // Add a Save Image entry.
2868                 contextMenu.add(R.string.save_image).setOnMenuItemClickListener {
2869                     // Check the download preference.
2870                     if (downloadWithExternalApp)  // Download with an external app.
2871                         downloadUrlWithExternalApp(imageUrl)
2872                     else  // Handle the download inside of Privacy Browser.  The dialog will be displayed once the file size and the content disposition have been acquired.
2873                         PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, imageUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
2874
2875                     // Consume the event.
2876                     true
2877                 }
2878
2879                 // Add a Share Image entry.
2880                 contextMenu.add(R.string.share_image).setOnMenuItemClickListener {
2881                     // Create the share intent.
2882                     val shareUrlIntent = Intent(Intent.ACTION_SEND)
2883
2884                     // Add the URL to the intent.
2885                     shareUrlIntent.putExtra(Intent.EXTRA_TEXT, imageUrl)
2886
2887                     // Set the MIME type.
2888                     shareUrlIntent.type = "text/plain"
2889
2890                     // Set the intent to open in a new task.
2891                     shareUrlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
2892
2893                     //Make it so.
2894                     startActivity(Intent.createChooser(shareUrlIntent, getString(R.string.share_url)))
2895
2896                     // Consume the event.
2897                     true
2898                 }
2899
2900                 // Add a copy URL entry.
2901                 contextMenu.add(R.string.copy_url).setOnMenuItemClickListener {
2902                     // Save the link URL in a clip data.
2903                     val srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl)
2904
2905                     // Set the clip data as the clipboard's primary clip.
2906                     clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData)
2907
2908                     // Consume the event.
2909                     true
2910                 }
2911
2912                 // Add a save URL entry.
2913                 contextMenu.add(R.string.save_url).setOnMenuItemClickListener {
2914                     // Check the download preference.
2915                     if (downloadWithExternalApp)  // Download with an external app.
2916                         downloadUrlWithExternalApp(linkUrl)
2917                     else  // Handle the download inside of Privacy Browser.  The dialog will be displayed once the file size and the content disposition have been acquired.
2918                         PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, linkUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
2919
2920                     // Consume the event.
2921                     true
2922                 }
2923
2924                 // Add a Share URL entry.
2925                 contextMenu.add(R.string.share_url).setOnMenuItemClickListener {
2926                     // Create the share intent.
2927                     val shareUrlIntent = Intent(Intent.ACTION_SEND)
2928
2929                     // Add the URL to the intent.
2930                     shareUrlIntent.putExtra(Intent.EXTRA_TEXT, linkUrl)
2931
2932                     // Set the MIME type.
2933                     shareUrlIntent.type = "text/plain"
2934
2935                     // Set the intent to open in a new task.
2936                     shareUrlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
2937
2938                     //Make it so.
2939                     startActivity(Intent.createChooser(shareUrlIntent, getString(R.string.share_url)))
2940
2941                     // Consume the event.
2942                     true
2943                 }
2944
2945                 // Add an empty cancel entry, which by default closes the context menu.
2946                 contextMenu.add(R.string.cancel)
2947             }
2948
2949             WebView.HitTestResult.EMAIL_TYPE -> {
2950                 // Get the target URL.
2951                 linkUrl = hitTestResult.extra
2952
2953                 // Set the target URL as the title of the context menu.
2954                 contextMenu.setHeaderTitle(linkUrl)
2955
2956                 // Add a write email entry.
2957                 contextMenu.add(R.string.write_email).setOnMenuItemClickListener {
2958                     // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2959                     val emailIntent = Intent(Intent.ACTION_SENDTO)
2960
2961                     // Parse the url and set it as the data for the intent.
2962                     emailIntent.data = Uri.parse("mailto:$linkUrl")
2963
2964                     // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2965                     emailIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2966
2967                     try {
2968                         // Make it so.
2969                         startActivity(emailIntent)
2970                     } catch (exception: ActivityNotFoundException) {
2971                         // Display a snackbar.
2972                         Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
2973                     }
2974
2975                     // Consume the event.
2976                     true
2977                 }
2978
2979                 // Add a copy email address entry.
2980                 contextMenu.add(R.string.copy_email_address).setOnMenuItemClickListener {
2981                     // Save the email address in a clip data.
2982                     val srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl)
2983
2984                     // Set the clip data as the clipboard's primary clip.
2985                     clipboardManager.setPrimaryClip(srcEmailTypeClipData)
2986
2987                     // Consume the event.
2988                     true
2989                 }
2990
2991                 // Add an empty cancel entry, which by default closes the context menu.
2992                 contextMenu.add(R.string.cancel)
2993             }
2994         }
2995     }
2996
2997     // The view parameter cannot be removed because it is called from the layout onClick.
2998     fun addTab(@Suppress("UNUSED_PARAMETER")view: View?) {
2999         // Add a new tab with a blank URL.
3000         addNewPage(urlString = "", adjacent = true, moveToTab = true)
3001     }
3002
3003     private fun addNewPage(urlString: String, adjacent: Boolean, moveToTab: Boolean) {
3004         // Clear the focus from the URL edit text, so that it will be populated with the information from the new tab.
3005         urlEditText.clearFocus()
3006
3007         // Add the new tab after the tab layout has quiesced.
3008         // Otherwise, there can be problems when restoring a large number of tabs and processing a new intent at the same time.  <https://redmine.stoutner.com/issues/1136>
3009         tabLayout.post {
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
3024     private fun addNewTab(newTabPosition: Int, moveToTab: Boolean) {
3025         // Check to see if the new page is ready.
3026         if (webViewStateAdapter!!.itemCount >= tabLayout.tabCount) {  // The new page is ready.
3027             // Create a new tab.
3028             val newTab = tabLayout.newTab()
3029
3030             // Set a custom view on the new tab.
3031             newTab.setCustomView(R.layout.tab_custom_view)
3032
3033             // Add the new tab.
3034             tabLayout.addTab(newTab, newTabPosition, moveToTab)
3035
3036             // 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.
3037             if (newTabPosition == 0)
3038                 tabLayout.selectTab(newTab)
3039
3040             // Scroll to the new tab position if moving to the new tab.
3041             if (moveToTab)
3042                 tabLayout.post {
3043                     tabLayout.setScrollPosition(newTabPosition, 0F, false, false)
3044                 }
3045
3046             // Show the app bar if it is at the bottom of the screen and the new tab is taking focus.
3047             if (bottomAppBar && moveToTab && appBarLayout.translationY != 0f) {
3048                 // Animate the bottom app bar onto the screen.
3049                 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0f)
3050
3051                 // Make it so.
3052                 objectAnimator.start()
3053             }
3054         } else {  // The new page is not ready.
3055             // Create a new tab handler.
3056             val newTabHandler = Handler(Looper.getMainLooper())
3057
3058             // Create a new tab runnable.
3059             val newTabRunnable = Runnable {
3060                 // Create the new tab.
3061                 addNewTab(newTabPosition, moveToTab)
3062             }
3063
3064             // Try adding the new tab again after 50 milliseconds.
3065             newTabHandler.postDelayed(newTabRunnable, 50)
3066         }
3067     }
3068
3069     private fun applyAppSettings() {
3070         // 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.
3071         defaultJavaScript = sharedPreferences.getBoolean(getString(R.string.javascript_key), false)
3072         defaultCookies = sharedPreferences.getBoolean(getString(R.string.cookies_key), false)
3073         defaultDomStorage = sharedPreferences.getBoolean(getString(R.string.dom_storage_key), false)
3074         defaultFormData = sharedPreferences.getBoolean(getString(R.string.save_form_data_key), false)  // Form data can be removed once the minimum API >= 26.
3075         defaultEasyList = sharedPreferences.getBoolean(getString(R.string.easylist_key), true)
3076         defaultEasyPrivacy = sharedPreferences.getBoolean(getString(R.string.easyprivacy_key), true)
3077         defaultFanboysAnnoyanceList = sharedPreferences.getBoolean(getString(R.string.fanboys_annoyance_list_key), true)
3078         defaultFanboysSocialBlockingList = sharedPreferences.getBoolean(getString(R.string.fanboys_social_blocking_list_key), true)
3079         defaultUltraList = sharedPreferences.getBoolean(getString(R.string.ultralist_key), true)
3080         defaultUltraPrivacy = sharedPreferences.getBoolean(getString(R.string.ultraprivacy_key), true)
3081         defaultBlockAllThirdPartyRequests = sharedPreferences.getBoolean(getString(R.string.block_all_third_party_requests_key), false)
3082         defaultFontSizeString = sharedPreferences.getString(getString(R.string.font_size_key), getString(R.string.font_size_default_value))!!
3083         defaultUserAgentName = sharedPreferences.getString(getString(R.string.user_agent_key), getString(R.string.user_agent_default_value))!!
3084         defaultSwipeToRefresh = sharedPreferences.getBoolean(getString(R.string.swipe_to_refresh_key), true)
3085         defaultWebViewTheme = sharedPreferences.getString(getString(R.string.webview_theme_key), getString(R.string.webview_theme_default_value))!!
3086         defaultWideViewport = sharedPreferences.getBoolean(getString(R.string.wide_viewport_key), true)
3087         defaultDisplayWebpageImages = sharedPreferences.getBoolean(getString(R.string.display_webpage_images_key), true)
3088
3089         // 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.
3090         webViewThemeEntryValuesStringArray = resources.getStringArray(R.array.webview_theme_entry_values)
3091
3092         // Get the user agent string arrays.  These are done here so that expensive resource requests are not made each time a domain is loaded.
3093         userAgentDataArray = resources.getStringArray(R.array.user_agent_data)
3094         userAgentNamesArray = resources.getStringArray(R.array.user_agent_names)
3095
3096         // Get the user agent array adapters.  These are done here so that expensive resource requests are not made each time a domain is loaded.
3097         userAgentDataArrayAdapter = ArrayAdapter.createFromResource(this, R.array.user_agent_data, R.layout.spinner_item)
3098         userAgentNamesArrayAdapter = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item)
3099
3100         // Store the values from the shared preferences in variables.
3101         incognitoModeEnabled = sharedPreferences.getBoolean(getString(R.string.incognito_mode_key), false)
3102         sanitizeTrackingQueries = sharedPreferences.getBoolean(getString(R.string.tracking_queries_key), true)
3103         sanitizeAmpRedirects = sharedPreferences.getBoolean(getString(R.string.amp_redirects_key), true)
3104         proxyMode = sharedPreferences.getString(getString(R.string.proxy_key), getString(R.string.proxy_default_value))!!
3105         fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean(getString(R.string.full_screen_browsing_mode_key), false)
3106         hideAppBar = sharedPreferences.getBoolean(getString(R.string.hide_app_bar_key), true)
3107         downloadWithExternalApp = sharedPreferences.getBoolean(getString(R.string.download_with_external_app_key), false)
3108         scrollAppBar = sharedPreferences.getBoolean(getString(R.string.scroll_app_bar_key), false)
3109
3110         // Apply the saved proxy mode if the app has been restarted.
3111         if (savedProxyMode != null) {
3112             // Apply the saved proxy mode.
3113             proxyMode = savedProxyMode!!
3114
3115             // Reset the saved proxy mode.
3116             savedProxyMode = null
3117         }
3118
3119         // Get the search string.
3120         val searchString = sharedPreferences.getString(getString(R.string.search_key), getString(R.string.search_default_value))!!
3121
3122         // Set the search string, using the custom search URL if specified.
3123         searchURL = if (searchString == getString(R.string.custom_url_item))
3124             sharedPreferences.getString(getString(R.string.search_custom_url_key), getString(R.string.search_custom_url_default_value))!!
3125         else
3126             searchString
3127
3128         // Apply the proxy.
3129         applyProxy(false)
3130
3131         // Adjust the layout and scrolling parameters according to the position of the app bar.
3132         if (bottomAppBar) {  // The app bar is on the bottom.
3133             // Adjust the UI.
3134             if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) {  // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
3135                 // Reset the WebView padding to fill the available space.
3136                 swipeRefreshLayout.setPadding(0, 0, 0, 0)
3137             } else {  // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
3138                 // Move the WebView above the app bar layout.
3139                 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
3140
3141                 // Show the app bar if it is scrolled off the screen.
3142                 if (appBarLayout.translationY != 0f) {
3143                     // Animate the bottom app bar onto the screen.
3144                     objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0f)
3145
3146                     // Make it so.
3147                     objectAnimator.start()
3148                 }
3149             }
3150         } else {  // The app bar is on the top.
3151             // Get the current layout parameters.  Using coordinator layout parameters allows the `setBehavior()` command and using app bar layout parameters allows the `setScrollFlags()` command.
3152             val swipeRefreshLayoutParams = swipeRefreshLayout.layoutParams as CoordinatorLayout.LayoutParams
3153             val toolbarLayoutParams = toolbar.layoutParams as AppBarLayout.LayoutParams
3154             val findOnPageLayoutParams = findOnPageLinearLayout.layoutParams as AppBarLayout.LayoutParams
3155             val tabsLayoutParams = tabsLinearLayout.layoutParams as AppBarLayout.LayoutParams
3156
3157             // Add the scrolling behavior to the layout parameters.
3158             if (scrollAppBar) {
3159                 // Enable scrolling of the app bar.
3160                 swipeRefreshLayoutParams.behavior = AppBarLayout.ScrollingViewBehavior()
3161                 toolbarLayoutParams.scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS or AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP
3162                 findOnPageLayoutParams.scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS or AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP
3163                 tabsLayoutParams.scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS or AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP
3164             } else {
3165                 // Disable scrolling of the app bar.
3166                 swipeRefreshLayoutParams.behavior = null
3167                 toolbarLayoutParams.scrollFlags = 0
3168                 findOnPageLayoutParams.scrollFlags = 0
3169                 tabsLayoutParams.scrollFlags = 0
3170
3171                 // Expand the app bar if it is currently collapsed.
3172                 appBarLayout.setExpanded(true)
3173             }
3174
3175             // Set the app bar scrolling for each WebView.
3176             for (i in 0 until webViewStateAdapter!!.itemCount) {
3177                 // Get the WebView tab fragment.
3178                 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
3179
3180                 // Get the fragment view.
3181                 val fragmentView = webViewTabFragment.view
3182
3183                 // Only modify the WebViews if they exist.
3184                 if (fragmentView != null) {
3185                     // Get the nested scroll WebView from the tab fragment.
3186                     val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
3187
3188                     // Set the app bar scrolling.
3189                     nestedScrollWebView.isNestedScrollingEnabled = scrollAppBar
3190                 }
3191             }
3192         }
3193
3194         // Update the full screen browsing mode settings.
3195         if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {  // Privacy Browser is currently in full screen browsing mode.
3196             // Update the visibility of the app bar, which might have changed in the settings.
3197             if (hideAppBar) {
3198                 // Hide the tab linear layout.
3199                 tabsLinearLayout.visibility = View.GONE
3200
3201                 // Hide the app bar.
3202                 appBar.hide()
3203             } else {
3204                 // Show the tab linear layout.
3205                 tabsLinearLayout.visibility = View.VISIBLE
3206
3207                 // Show the app bar.
3208                 appBar.show()
3209             }
3210
3211             /* Hide the system bars.
3212              * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3213              * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
3214              * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3215              * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3216              */
3217
3218             // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
3219             @Suppress("DEPRECATION")
3220             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
3221         } else {  // Privacy Browser is not in full screen browsing mode.
3222             // 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.
3223             inFullScreenBrowsingMode = false
3224
3225             // Show the tab linear layout.
3226             tabsLinearLayout.visibility = View.VISIBLE
3227
3228             // Show the app bar.
3229             appBar.show()
3230
3231             // Remove the `SYSTEM_UI` flags from the root frame layout.  The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
3232             @Suppress("DEPRECATION")
3233             rootFrameLayout.systemUiVisibility = 0
3234         }
3235     }
3236
3237     // `reloadWebsite` is used if returning from the Domains activity.  Otherwise JavaScript might not function correctly if it is newly enabled.
3238     @SuppressLint("SetJavaScriptEnabled")
3239     private fun applyDomainSettings(nestedScrollWebView: NestedScrollWebView, url: String?, resetTab: Boolean, reloadWebsite: Boolean, loadUrl: Boolean) {
3240         // Store the current URL.
3241         nestedScrollWebView.currentUrl = url!!
3242
3243         // Parse the URL into a URI.
3244         val uri = Uri.parse(url)
3245
3246         // Extract the domain from the URI.
3247         var newHostName = uri.host
3248
3249         // Strings don't like to be null.
3250         if (newHostName == null)
3251             newHostName = ""
3252
3253         // 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.
3254         if ((nestedScrollWebView.currentDomainName != newHostName) || (newHostName == "")) {  // A new domain is being loaded.
3255             // Set the new host name as the current domain name.
3256             nestedScrollWebView.currentDomainName = newHostName
3257
3258             // Reset the ignoring of pinned domain information.
3259             nestedScrollWebView.ignorePinnedDomainInformation = false
3260
3261             // Clear any pinned SSL certificate or IP addresses.
3262             nestedScrollWebView.clearPinnedSslCertificate()
3263             nestedScrollWebView.pinnedIpAddresses = ""
3264
3265             // Reset the favorite icon if specified.
3266             if (resetTab) {
3267                 // Initialize the favorite icon.
3268                 nestedScrollWebView.initializeFavoriteIcon()
3269
3270                 // Get the current page position.
3271                 val currentPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
3272
3273                 // Get the corresponding tab.
3274                 val tab = tabLayout.getTabAt(currentPagePosition)
3275
3276                 // Update the tab if it isn't null, which sometimes happens when restarting from the background.
3277                 if (tab != null) {
3278                     // Get the tab custom view.
3279                     val tabCustomView = tab.customView!!
3280
3281                     // Get the tab views.
3282                     val tabFavoriteIconImageView = tabCustomView.findViewById<ImageView>(R.id.favorite_icon_imageview)
3283                     val tabTitleTextView = tabCustomView.findViewById<TextView>(R.id.title_textview)
3284
3285                     // Store the current values in case they need to be restored.
3286                     nestedScrollWebView.previousFavoriteIconDrawable = tabFavoriteIconImageView.drawable
3287                     nestedScrollWebView.previousWebpageTitle = tabTitleTextView.text.toString()
3288
3289                     // Set the default favorite icon as the favorite icon for this tab.
3290                     tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nestedScrollWebView.getFavoriteIcon(), 64, 64, true))
3291
3292                     // Set the loading title text.
3293                     tabTitleTextView.setText(R.string.loading)
3294                 }
3295             }
3296
3297             // Initialize the domain name in database variable.
3298             var domainNameInDatabase: String? = null
3299
3300             // Check the hostname against the domain settings set.
3301             if (domainsSettingsSet.contains(newHostName)) {  // The hostname is contained in the domain settings set.
3302                 // Record the domain name in the database.
3303                 domainNameInDatabase = newHostName
3304
3305                 // Set the domain settings applied tracker to true.
3306                 nestedScrollWebView.domainSettingsApplied = true
3307             } else {  // The hostname is not contained in the domain settings set.
3308                 // Set the domain settings applied tracker to false.
3309                 nestedScrollWebView.domainSettingsApplied = false
3310             }
3311
3312             // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3313             while (!nestedScrollWebView.domainSettingsApplied && newHostName!!.contains(".")) {  // Stop checking if domain settings are already applied or there are no more `.` in the hostname.
3314                 if (domainsSettingsSet.contains("*.$newHostName")) {  // Check the host name prepended by `*.`.
3315                     // Set the domain settings applied tracker to true.
3316                     nestedScrollWebView.domainSettingsApplied = true
3317
3318                     // Store the applied domain names as it appears in the database.
3319                     domainNameInDatabase = "*.$newHostName"
3320                 }
3321
3322                 // Strip out the lowest subdomain of of the host name.
3323                 newHostName = newHostName.substring(newHostName.indexOf(".") + 1)
3324             }
3325
3326             // Apply either the domain settings or the default settings.
3327             if (nestedScrollWebView.domainSettingsApplied) {  // The url has custom domain settings.
3328                 // Get a cursor for the current host.
3329                 val currentDomainSettingsCursor = domainsDatabaseHelper!!.getCursorForDomainName(domainNameInDatabase!!)
3330
3331                 // Move to the first position.
3332                 currentDomainSettingsCursor.moveToFirst()
3333
3334                 // Get the settings from the cursor.
3335                 nestedScrollWebView.domainSettingsDatabaseId = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ID))
3336                 val javaScriptInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_JAVASCRIPT))
3337                 val cookiesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(COOKIES))
3338                 val domStorageInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_DOM_STORAGE))
3339                 val formDataInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_FORM_DATA))  // Form data can be removed once the minimum API >= 26.
3340                 val easyListInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_EASYLIST))
3341                 val easyPrivacyInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_EASYPRIVACY))
3342                 val fanboysAnnoyanceListInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_FANBOYS_ANNOYANCE_LIST))
3343                 val fanboysSocialBlockingListInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST))
3344                 val ultraListInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.ULTRALIST))
3345                 val ultraPrivacyInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_ULTRAPRIVACY))
3346                 val blockAllThirdPartyRequestsInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.BLOCK_ALL_THIRD_PARTY_REQUESTS))
3347                 val userAgentName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.USER_AGENT))
3348                 val fontSize = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(FONT_SIZE))
3349                 val swipeToRefreshInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(SWIPE_TO_REFRESH))
3350                 val webViewThemeInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(WEBVIEW_THEME))
3351                 val wideViewportInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(WIDE_VIEWPORT))
3352                 val displayWebpageImagesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DISPLAY_IMAGES))
3353                 val pinnedSslCertificate = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(PINNED_SSL_CERTIFICATE)) == 1)
3354                 val pinnedSslIssuedToCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_TO_COMMON_NAME))
3355                 val pinnedSslIssuedToOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_TO_ORGANIZATION))
3356                 val pinnedSslIssuedToUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_TO_ORGANIZATIONAL_UNIT))
3357                 val pinnedSslIssuedByCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_BY_COMMON_NAME))
3358                 val pinnedSslIssuedByOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_BY_ORGANIZATION))
3359                 val pinnedSslIssuedByUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_BY_ORGANIZATIONAL_UNIT))
3360                 val pinnedSslStartDate = Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.SSL_START_DATE)))
3361                 val pinnedSslEndDate = Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.SSL_END_DATE)))
3362                 val pinnedIpAddresses = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(PINNED_IP_ADDRESSES)) == 1)
3363                 val pinnedHostIpAddresses = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(IP_ADDRESSES))
3364
3365                 // Close the current host domain settings cursor.
3366                 currentDomainSettingsCursor.close()
3367
3368                 // Set the JavaScript status.
3369                 when (javaScriptInt) {
3370                     SYSTEM_DEFAULT -> nestedScrollWebView.settings.javaScriptEnabled = defaultJavaScript
3371                     ENABLED -> nestedScrollWebView.settings.javaScriptEnabled = true
3372                     DISABLED -> nestedScrollWebView.settings.javaScriptEnabled = false
3373                 }
3374
3375                 // Store the cookies status.
3376                 when (cookiesInt) {
3377                     SYSTEM_DEFAULT -> nestedScrollWebView.acceptCookies = defaultCookies
3378                     ENABLED -> nestedScrollWebView.acceptCookies = true
3379                     DISABLED -> nestedScrollWebView.acceptCookies = false
3380                 }
3381
3382                 // Apply the cookies status.
3383                 cookieManager.setAcceptCookie(nestedScrollWebView.acceptCookies)
3384
3385                 // Set the DOM storage status.
3386                 when (domStorageInt) {
3387                     SYSTEM_DEFAULT -> nestedScrollWebView.settings.domStorageEnabled = defaultDomStorage
3388                     ENABLED -> nestedScrollWebView.settings.domStorageEnabled = true
3389                     DISABLED -> nestedScrollWebView.settings.domStorageEnabled = false
3390                 }
3391
3392                 // Apply the form data setting if the API < 26.
3393                 @Suppress("DEPRECATION")
3394                 if (Build.VERSION.SDK_INT < 26) {
3395                     // Set the form data status.
3396                     when (formDataInt) {
3397                         SYSTEM_DEFAULT -> nestedScrollWebView.settings.saveFormData = defaultFormData
3398                         ENABLED -> nestedScrollWebView.settings.saveFormData = true
3399                         DISABLED -> nestedScrollWebView.settings.saveFormData = false
3400                     }
3401                 }
3402
3403                 // Set the EasyList status.
3404                 when (easyListInt) {
3405                     SYSTEM_DEFAULT -> nestedScrollWebView.easyListEnabled = defaultEasyList
3406                     ENABLED -> nestedScrollWebView.easyListEnabled = true
3407                     DISABLED -> nestedScrollWebView.easyListEnabled = false
3408                 }
3409
3410                 // Set the EasyPrivacy status.
3411                 when (easyPrivacyInt) {
3412                     SYSTEM_DEFAULT -> nestedScrollWebView.easyPrivacyEnabled = defaultEasyPrivacy
3413                     ENABLED -> nestedScrollWebView.easyPrivacyEnabled = true
3414                     DISABLED -> nestedScrollWebView.easyPrivacyEnabled = false
3415                 }
3416
3417                 // Set the Fanboy's Annoyance List status.
3418                 when (fanboysAnnoyanceListInt) {
3419                     SYSTEM_DEFAULT -> nestedScrollWebView.fanboysAnnoyanceListEnabled = defaultFanboysAnnoyanceList
3420                     ENABLED -> nestedScrollWebView.fanboysAnnoyanceListEnabled = true
3421                     DISABLED -> nestedScrollWebView.fanboysAnnoyanceListEnabled = false
3422                 }
3423
3424                 // Set the Fanboy's Social Blocking List status.
3425                 when (fanboysSocialBlockingListInt) {
3426                     SYSTEM_DEFAULT -> nestedScrollWebView.fanboysSocialBlockingListEnabled = defaultFanboysSocialBlockingList
3427                     ENABLED -> nestedScrollWebView.fanboysSocialBlockingListEnabled = true
3428                     DISABLED -> nestedScrollWebView.fanboysSocialBlockingListEnabled = false
3429                 }
3430
3431                 // Set the UltraList status.
3432                 when (ultraListInt) {
3433                     SYSTEM_DEFAULT -> nestedScrollWebView.ultraListEnabled = defaultUltraList
3434                     ENABLED -> nestedScrollWebView.ultraListEnabled = true
3435                     DISABLED -> nestedScrollWebView.ultraListEnabled = false
3436                 }
3437
3438                 // Set the UltraPrivacy status.
3439                 when (ultraPrivacyInt) {
3440                     SYSTEM_DEFAULT -> nestedScrollWebView.ultraPrivacyEnabled = defaultUltraPrivacy
3441                     ENABLED -> nestedScrollWebView.ultraPrivacyEnabled = true
3442                     DISABLED -> nestedScrollWebView.ultraPrivacyEnabled = false
3443                 }
3444
3445                 // Set the block all third-party requests status.
3446                 when (blockAllThirdPartyRequestsInt) {
3447                     SYSTEM_DEFAULT -> nestedScrollWebView.blockAllThirdPartyRequests = defaultBlockAllThirdPartyRequests
3448                     ENABLED -> nestedScrollWebView.blockAllThirdPartyRequests = true
3449                     DISABLED -> nestedScrollWebView.blockAllThirdPartyRequests = false
3450                 }
3451
3452                 // Set the user agent.
3453                 if (userAgentName == getString(R.string.system_default_user_agent)) {  // Use the system default user agent.
3454                     // Set the user agent according to the system default.
3455                     when (val defaultUserAgentArrayPosition = userAgentNamesArrayAdapter.getPosition(defaultUserAgentName)) {
3456                         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.
3457                             nestedScrollWebView.settings.userAgentString = defaultUserAgentName
3458
3459                         SETTINGS_WEBVIEW_DEFAULT_USER_AGENT ->  // Set the user agent to `""`, which uses the default value.
3460                             nestedScrollWebView.settings.userAgentString = ""
3461
3462                         SETTINGS_CUSTOM_USER_AGENT ->  // Set the default custom user agent.
3463                             nestedScrollWebView.settings.userAgentString = sharedPreferences.getString(getString(R.string.custom_user_agent_key), getString(R.string.custom_user_agent_default_value))
3464
3465                         else ->  // Get the user agent string from the user agent data array
3466                             nestedScrollWebView.settings.userAgentString = userAgentDataArray[defaultUserAgentArrayPosition]
3467                     }
3468                 } else {  // Set the user agent according to the stored name.
3469                     // Set the user agent.
3470                     when (val userAgentArrayPosition = userAgentNamesArrayAdapter.getPosition(userAgentName)) {
3471                         // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3472                         UNRECOGNIZED_USER_AGENT ->
3473                             nestedScrollWebView.settings.userAgentString = userAgentName
3474
3475                         // Set the user agent to `""`, which uses the default value.
3476                         SETTINGS_WEBVIEW_DEFAULT_USER_AGENT ->
3477                             nestedScrollWebView.settings.userAgentString = ""
3478
3479                         // Get the user agent string from the user agent data array.
3480                         else ->
3481                             nestedScrollWebView.settings.userAgentString = userAgentDataArray[userAgentArrayPosition]
3482                     }
3483                 }
3484
3485                 // Apply the font size.
3486                 try {  // Try the specified font size to see if it is valid.
3487                     if (fontSize == 0) {  // Apply the default font size.
3488                         // Set the font size from the value in the app settings.
3489                         nestedScrollWebView.settings.textZoom = defaultFontSizeString.toInt()
3490                     } else {  // Apply the font size from domain settings.
3491                         nestedScrollWebView.settings.textZoom = fontSize
3492                     }
3493                 } catch (exception: Exception) {  // The specified font size is invalid
3494                     // Set the font size to be 100%
3495                     nestedScrollWebView.settings.textZoom = 100
3496                 }
3497
3498                 // Set swipe to refresh.
3499                 when (swipeToRefreshInt) {
3500                     SYSTEM_DEFAULT -> {
3501                         // Store the swipe to refresh status in the nested scroll WebView.
3502                         nestedScrollWebView.swipeToRefresh = defaultSwipeToRefresh
3503
3504                         // Update the swipe refresh layout.
3505                         if (defaultSwipeToRefresh) {  // Swipe to refresh is enabled.
3506                             // 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).
3507                             if (currentWebView != null) {
3508                                 // Only enable the swipe refresh layout if the WebView is scrolled to the top.  It is updated every time the scroll changes.
3509                                 swipeRefreshLayout.isEnabled = (currentWebView!!.scrollY == 0)
3510                             }
3511                         } else {  // Swipe to refresh is disabled.
3512                             // Disable the swipe refresh layout.
3513                             swipeRefreshLayout.isEnabled = false
3514                         }
3515                     }
3516
3517                     ENABLED -> {
3518                         // Store the swipe to refresh status in the nested scroll WebView.
3519                         nestedScrollWebView.swipeToRefresh = true
3520
3521                         // 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).
3522                         if (currentWebView != null) {
3523                             // Only enable the swipe refresh layout if the WebView is scrolled to the top.  It is updated every time the scroll changes.
3524                             swipeRefreshLayout.isEnabled = (currentWebView!!.scrollY == 0)
3525                         }
3526                     }
3527
3528                     DISABLED -> {
3529                         // Store the swipe to refresh status in the nested scroll WebView.
3530                         nestedScrollWebView.swipeToRefresh = false
3531
3532                         // Disable swipe to refresh.
3533                         swipeRefreshLayout.isEnabled = false
3534                     }
3535                 }
3536
3537                 // Set the WebView theme if algorithmic darkening is supported.
3538                 if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {
3539                     // Set the WebView theme.
3540                     when (webViewThemeInt) {
3541                         SYSTEM_DEFAULT ->  // Set the WebView theme.
3542                             when (defaultWebViewTheme) {
3543                                 webViewThemeEntryValuesStringArray[1] ->  // The light theme is selected.  Turn off algorithmic darkening.
3544                                     WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
3545
3546                                 webViewThemeEntryValuesStringArray[2] ->  // The dark theme is selected.  Turn on algorithmic darkening.
3547                                     WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
3548
3549                                 else -> {  // The system default theme is selected.
3550                                     // Get the current system theme status.
3551                                     val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
3552
3553                                     // Set the algorithmic darkening according to the current system theme status.
3554                                     WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, currentThemeStatus == Configuration.UI_MODE_NIGHT_YES)
3555                                 }
3556                             }
3557
3558                         LIGHT_THEME ->  // Turn off algorithmic darkening.
3559                             WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
3560
3561                         DARK_THEME ->  // Turn on algorithmic darkening.
3562                             WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
3563                     }
3564                 }
3565
3566                 // Set the wide viewport status.
3567                 when (wideViewportInt) {
3568                     SYSTEM_DEFAULT -> nestedScrollWebView.settings.useWideViewPort = defaultWideViewport
3569                     ENABLED -> nestedScrollWebView.settings.useWideViewPort = true
3570                     DISABLED -> nestedScrollWebView.settings.useWideViewPort = false
3571                 }
3572
3573                 // Set the display webpage images status.
3574                 when (displayWebpageImagesInt) {
3575                     SYSTEM_DEFAULT -> nestedScrollWebView.settings.loadsImagesAutomatically = defaultDisplayWebpageImages
3576                     ENABLED -> nestedScrollWebView.settings.loadsImagesAutomatically = true
3577                     DISABLED -> nestedScrollWebView.settings.loadsImagesAutomatically = false
3578                 }
3579
3580                 // If there is a pinned SSL certificate, store it in the WebView.
3581                 if (pinnedSslCertificate)
3582                     nestedScrollWebView.setPinnedSslCertificate(pinnedSslIssuedToCName, pinnedSslIssuedToOName, pinnedSslIssuedToUName, pinnedSslIssuedByCName, pinnedSslIssuedByOName, pinnedSslIssuedByUName,
3583                         pinnedSslStartDate, pinnedSslEndDate)
3584
3585                 // If there is a pinned IP address, store it in the WebView.
3586                 if (pinnedIpAddresses)
3587                     nestedScrollWebView.pinnedIpAddresses = pinnedHostIpAddresses
3588
3589                 // Set a background on the URL relative layout to indicate that custom domain settings are being used.
3590                 urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.drawable.domain_settings_url_background)
3591             } else {  // The new URL does not have custom domain settings.  Load the defaults.
3592                 // Store the values from the shared preferences.
3593                 nestedScrollWebView.settings.javaScriptEnabled = defaultJavaScript
3594                 nestedScrollWebView.acceptCookies = defaultCookies
3595                 nestedScrollWebView.settings.domStorageEnabled = defaultDomStorage
3596                 nestedScrollWebView.easyListEnabled = defaultEasyList
3597                 nestedScrollWebView.easyPrivacyEnabled = defaultEasyPrivacy
3598                 nestedScrollWebView.fanboysAnnoyanceListEnabled = defaultFanboysAnnoyanceList
3599                 nestedScrollWebView.fanboysSocialBlockingListEnabled = defaultFanboysSocialBlockingList
3600                 nestedScrollWebView.ultraListEnabled = defaultUltraList
3601                 nestedScrollWebView.ultraPrivacyEnabled = defaultUltraPrivacy
3602                 nestedScrollWebView.blockAllThirdPartyRequests = defaultBlockAllThirdPartyRequests
3603
3604                 // Apply the default cookie setting.
3605                 cookieManager.setAcceptCookie(nestedScrollWebView.acceptCookies)
3606
3607                 // Apply the form data setting if the API < 26.
3608                 if (Build.VERSION.SDK_INT < 26)
3609                     @Suppress("DEPRECATION")
3610                     nestedScrollWebView.settings.saveFormData = defaultFormData
3611
3612                 // Apply the default font size setting.
3613                 try {
3614                     // Try to set the font size from the value in the app settings.
3615                     nestedScrollWebView.settings.textZoom = defaultFontSizeString.toInt()
3616                 } catch (exception: Exception) {
3617                     // If the app settings value is invalid, set the font size to 100%.
3618                     nestedScrollWebView.settings.textZoom = 100
3619                 }
3620
3621                 // Store the swipe to refresh status in the nested scroll WebView.
3622                 nestedScrollWebView.swipeToRefresh = defaultSwipeToRefresh
3623
3624                 // Update the swipe refresh layout.
3625                 if (defaultSwipeToRefresh) {  // Swipe to refresh is enabled.
3626                     // 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).
3627                     if (currentWebView != null) {
3628                         // Only enable the swipe refresh layout if the WebView is scrolled to the top.  It is updated every time the scroll changes.
3629                         swipeRefreshLayout.isEnabled = currentWebView!!.scrollY == 0
3630                     }
3631                 } else {  // Swipe to refresh is disabled.
3632                     // Disable the swipe refresh layout.
3633                     swipeRefreshLayout.isEnabled = false
3634                 }
3635
3636                 // Reset the domain settings database ID.
3637                 nestedScrollWebView.domainSettingsDatabaseId = -1
3638
3639                 // Set the user agent.
3640                 when (val userAgentArrayPosition = userAgentNamesArrayAdapter.getPosition(defaultUserAgentName)) {
3641                     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.
3642                         nestedScrollWebView.settings.userAgentString = defaultUserAgentName
3643
3644                     SETTINGS_WEBVIEW_DEFAULT_USER_AGENT ->  // Set the user agent to `""`, which uses the default value.
3645                         nestedScrollWebView.settings.userAgentString = ""
3646
3647                     SETTINGS_CUSTOM_USER_AGENT ->  // Set the default custom user agent.
3648                         nestedScrollWebView.settings.userAgentString = sharedPreferences.getString(getString(R.string.custom_user_agent_key), getString(R.string.custom_user_agent_default_value))
3649
3650                     else ->  // Get the user agent string from the user agent data array
3651                         nestedScrollWebView.settings.userAgentString = userAgentDataArray[userAgentArrayPosition]
3652                 }
3653
3654                 // Set the WebView theme if algorithmic darkening is supported.
3655                 if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {
3656                     // Set the WebView theme.
3657                     when (defaultWebViewTheme) {
3658                         webViewThemeEntryValuesStringArray[1] ->  // The light theme is selected.  Turn off algorithmic darkening.
3659                             WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
3660
3661                         webViewThemeEntryValuesStringArray[2] ->  // The dark theme is selected.  Turn on algorithmic darkening.
3662                             WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
3663
3664                         else -> {  // The system default theme is selected.  Get the current system theme status.
3665                             // Get the current theme status.
3666                             val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
3667
3668                             // Set the algorithmic darkening according to the current system theme status.
3669                             WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, currentThemeStatus == Configuration.UI_MODE_NIGHT_YES)
3670                         }
3671                     }
3672                 }
3673
3674                 // Set the viewport.
3675                 nestedScrollWebView.settings.useWideViewPort = defaultWideViewport
3676
3677                 // Set the loading of webpage images.
3678                 nestedScrollWebView.settings.loadsImagesAutomatically = defaultDisplayWebpageImages
3679
3680                 // Set a transparent background on the URL relative layout.
3681                 urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.color.transparent)
3682             }
3683
3684             // Update the privacy icons.
3685             updatePrivacyIcons(true)
3686         }
3687
3688         // Reload the website if returning from the Domains activity.
3689         if (reloadWebsite)
3690             nestedScrollWebView.reload()
3691
3692         // Disable the wide viewport if the source is being viewed.
3693         if (url.startsWith("view-source:"))
3694             nestedScrollWebView.settings.useWideViewPort = false
3695
3696         // 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.
3697         if (loadUrl)
3698             nestedScrollWebView.loadUrl(url)
3699     }
3700
3701     private fun applyProxy(reloadWebViews: Boolean) {
3702         // Set the proxy according to the mode.
3703         proxyHelper.setProxy(applicationContext, appBarLayout, proxyMode)
3704
3705         // Reset the waiting for proxy tracker.
3706         waitingForProxy = false
3707
3708         // Set the proxy.
3709         when (proxyMode) {
3710             ProxyHelper.NONE -> {
3711                 // Initialize a color background typed value.
3712                 val colorBackgroundTypedValue = TypedValue()
3713
3714                 // Get the color background from the theme.
3715                 theme.resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true)
3716
3717                 // Get the color background int from the typed value.
3718                 val colorBackgroundInt = colorBackgroundTypedValue.data
3719
3720                 // Set the default app bar layout background.
3721                 appBarLayout.setBackgroundColor(colorBackgroundInt)
3722             }
3723
3724             ProxyHelper.TOR -> {
3725                 // Set the app bar background to indicate proxying is enabled.
3726                 appBarLayout.setBackgroundResource(R.color.blue_background)
3727
3728                 // Check to see if Orbot is installed.
3729                 try {
3730                     // Get the package manager.
3731                     val packageManager = packageManager
3732
3733                     // 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.
3734                     packageManager.getPackageInfo("org.torproject.android", 0)
3735
3736                     // Check to see if the proxy is ready.
3737                     if (orbotStatus != ProxyHelper.ORBOT_STATUS_ON) {  // Orbot is not ready.
3738                         // Set the waiting for proxy status.
3739                         waitingForProxy = true
3740
3741                         // Show the waiting for proxy dialog if it isn't already displayed.
3742                         if (supportFragmentManager.findFragmentByTag(getString(R.string.waiting_for_proxy_dialog)) == null) {
3743                             // Get a handle for the waiting for proxy alert dialog.
3744                             val waitingForProxyDialogFragment = WaitingForProxyDialog()
3745
3746                             // Try to show the dialog.  Sometimes the window is not yet active if returning from Settings.
3747                             try {
3748                                 // Show the waiting for proxy alert dialog.
3749                                 waitingForProxyDialogFragment.show(supportFragmentManager, getString(R.string.waiting_for_proxy_dialog))
3750                             } catch (waitingForTorException: Exception) {
3751                                 // Add the dialog to the pending dialog array list.  It will be displayed in `onStart()`.
3752                                 pendingDialogsArrayList.add(PendingDialogDataClass(waitingForProxyDialogFragment, getString(R.string.waiting_for_proxy_dialog)))
3753                             }
3754                         }
3755                     }
3756                 } catch (exception: PackageManager.NameNotFoundException) {  // Orbot is not installed.
3757                     // Show the Orbot not installed dialog if it is not already displayed.
3758                     if (supportFragmentManager.findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
3759                         // Get a handle for the Orbot not installed alert dialog.
3760                         val orbotNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode)
3761
3762                         // Try to show the dialog.  Sometimes the window is not yet active if returning from Settings.
3763                         try {
3764                             // Display the Orbot not installed alert dialog.
3765                             orbotNotInstalledDialogFragment.show(supportFragmentManager, getString(R.string.proxy_not_installed_dialog))
3766                         } catch (orbotNotInstalledException: Exception) {
3767                             // Add the dialog to the pending dialog array list.  It will be displayed in `onStart()`.
3768                             pendingDialogsArrayList.add(PendingDialogDataClass(orbotNotInstalledDialogFragment, getString(R.string.proxy_not_installed_dialog)))
3769                         }
3770                     }
3771                 }
3772             }
3773
3774             ProxyHelper.I2P -> {
3775                 // Set the app bar background to indicate proxying is enabled.
3776                 appBarLayout.setBackgroundResource(R.color.blue_background)
3777
3778                 // Check to see if I2P is installed.
3779                 try {
3780                     // 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.
3781                     packageManager.getPackageInfo("net.i2p.android.router", 0)
3782                 } catch (fdroidException: PackageManager.NameNotFoundException) {  // The F-Droid flavor is not installed.
3783                     try {
3784                         // 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.
3785                         packageManager.getPackageInfo("net.i2p.android", 0)
3786                     } catch (googlePlayException: PackageManager.NameNotFoundException) {  // The Google Play flavor is not installed.
3787                         // Sow the I2P not installed dialog if it is not already displayed.
3788                         if (supportFragmentManager.findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
3789                             // Get a handle for the waiting for proxy alert dialog.
3790                             val i2pNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode)
3791
3792                             // Try to show the dialog.  Sometimes the window is not yet active if returning from Settings.
3793                             try {
3794                                 // Display the I2P not installed alert dialog.
3795                                 i2pNotInstalledDialogFragment.show(supportFragmentManager, getString(R.string.proxy_not_installed_dialog))
3796                             } catch (i2pNotInstalledException: Exception) {
3797                                 // Add the dialog to the pending dialog array list.  It will be displayed in `onStart()`.
3798                                 pendingDialogsArrayList.add(PendingDialogDataClass(i2pNotInstalledDialogFragment, getString(R.string.proxy_not_installed_dialog)))
3799                             }
3800                         }
3801                     }
3802                 }
3803             }
3804
3805             ProxyHelper.CUSTOM ->
3806                 // Set the app bar background to indicate proxying is enabled.
3807                 appBarLayout.setBackgroundResource(R.color.blue_background)
3808         }
3809
3810         // Reload the WebViews if requested and not waiting for the proxy.
3811         if (reloadWebViews && !waitingForProxy) {
3812             // Reload the WebViews.
3813             for (i in 0 until webViewStateAdapter!!.itemCount) {
3814                 // Get the WebView tab fragment.
3815                 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
3816
3817                 // Get the fragment view.
3818                 val fragmentView = webViewTabFragment.view
3819
3820                 // Only reload the WebViews if they exist.
3821                 if (fragmentView != null) {
3822                     // Get the nested scroll WebView from the tab fragment.
3823                     val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
3824
3825                     // Reload the WebView.
3826                     nestedScrollWebView.reload()
3827                 }
3828             }
3829         }
3830     }
3831
3832     // The view parameter cannot be removed because it is called from the layout onClick.
3833     fun bookmarksBack(@Suppress("UNUSED_PARAMETER")view: View?) {
3834         if (currentBookmarksFolderId == HOME_FOLDER_ID) {  // The home folder is displayed.
3835             // close the bookmarks drawer.
3836             drawerLayout.closeDrawer(GravityCompat.END)
3837         } else {  // A subfolder is displayed.
3838             // Set the former parent folder as the current folder.
3839             currentBookmarksFolderId = bookmarksDatabaseHelper!!.getParentFolderId(currentBookmarksFolderId)
3840
3841             // Load the new folder.
3842             loadBookmarksFolder()
3843         }
3844     }
3845
3846     private fun calculateSettingsInt(settingCurrentlyEnabled: Boolean, settingEnabledByDefault: Boolean): Int {
3847         return if (settingCurrentlyEnabled == settingEnabledByDefault)  // The current system default is used.
3848             SYSTEM_DEFAULT
3849         else if (settingCurrentlyEnabled)  // The setting is enabled, which is different from the system default.
3850             ENABLED
3851         else  // The setting is disabled, which is different from the system default.
3852             DISABLED
3853     }
3854
3855     private fun clearAndExit() {
3856         // Close the bookmarks cursor if it exists.
3857         bookmarksCursor?.close()
3858
3859         // Close the databases helpers if they exist.
3860         bookmarksDatabaseHelper?.close()
3861         domainsDatabaseHelper?.close()
3862
3863         // Get the status of the clear everything preference.
3864         val clearEverything = sharedPreferences.getBoolean(getString(R.string.clear_everything_key), true)
3865
3866         // Get a handle for the runtime.
3867         val runtime = Runtime.getRuntime()
3868
3869         // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
3870         // which links to `/data/data/com.stoutner.privacybrowser.standard`.
3871         val privateDataDirectoryString = applicationInfo.dataDir
3872
3873         // Clear cookies.
3874         if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_cookies_key), true)) {
3875             // Ass the cookie manager to delete all the cookies.
3876             cookieManager.removeAllCookies(null)
3877
3878             // Ask the cookie manager to flush the cookie database.
3879             cookieManager.flush()
3880
3881             // Manually delete the cookies database, as the cookie manager sometimes will not flush its changes to disk before system exit is run.
3882             try {
3883                 // Two commands must be used because `Runtime.exec()` does not like `*`.
3884                 val deleteCookiesProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/Cookies")
3885                 val deleteCookiesJournalProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/Cookies-journal")
3886
3887                 // Wait until the processes have finished.
3888                 deleteCookiesProcess.waitFor()
3889                 deleteCookiesJournalProcess.waitFor()
3890             } catch (exception: Exception) {
3891                 // Do nothing if an error is thrown.
3892             }
3893         }
3894
3895         // Clear DOM storage.
3896         if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_dom_storage_key), true)) {
3897             // Ask web storage to clear the DOM storage.
3898             WebStorage.getInstance().deleteAllData()
3899
3900             // Manually delete the DOM storage files and directories, as web storage sometimes will not flush its changes to disk before system exit is run.
3901             try {
3902                 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
3903                 val deleteLocalStorageProcess = runtime.exec(arrayOf("rm", "-rf", "$privateDataDirectoryString/app_webview/Local Storage/"))
3904
3905                 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
3906                 val deleteIndexProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview/IndexedDB")
3907                 val deleteQuotaManagerProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/QuotaManager")
3908                 val deleteQuotaManagerJournalProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/QuotaManager-journal")
3909                 val deleteDatabaseProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview/databases")
3910
3911                 // Wait until the processes have finished.
3912                 deleteLocalStorageProcess.waitFor()
3913                 deleteIndexProcess.waitFor()
3914                 deleteQuotaManagerProcess.waitFor()
3915                 deleteQuotaManagerJournalProcess.waitFor()
3916                 deleteDatabaseProcess.waitFor()
3917             } catch (exception: Exception) {
3918                 // Do nothing if an error is thrown.
3919             }
3920         }
3921
3922         // Clear form data if the API < 26.
3923         if (Build.VERSION.SDK_INT < 26 && (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_form_data_key), true))) {
3924             // Ask the WebView database to clear the form data.
3925             @Suppress("DEPRECATION")
3926             WebViewDatabase.getInstance(this).clearFormData()
3927
3928             // Manually delete the form data database, as the WebView database sometimes will not flush its changes to disk before system exit is run.
3929             try {
3930                 // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
3931                 val deleteWebDataProcess = runtime.exec(arrayOf("rm", "-f", "$privateDataDirectoryString/app_webview/Web Data"))
3932                 val deleteWebDataJournalProcess = runtime.exec(arrayOf("rm", "-f", "$privateDataDirectoryString/app_webview/Web Data-journal"))
3933
3934                 // Wait until the processes have finished.
3935                 deleteWebDataProcess.waitFor()
3936                 deleteWebDataJournalProcess.waitFor()
3937             } catch (exception: Exception) {
3938                 // Do nothing if an error is thrown.
3939             }
3940         }
3941
3942         // Clear the logcat.
3943         if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_logcat_key), true)) {
3944             try {
3945                 // Clear the logcat.  `-c` clears the logcat.  `-b all` clears all the buffers (instead of just crash, main, and system).
3946                 val process = Runtime.getRuntime().exec("logcat -b all -c")
3947
3948                 // Wait for the process to finish.
3949                 process.waitFor()
3950             } catch (exception: IOException) {
3951                 // Do nothing.
3952             } catch (exception: InterruptedException) {
3953                 // Do nothing.
3954             }
3955         }
3956
3957         // Clear the cache.
3958         if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_cache_key), true)) {
3959             // Clear the cache from each WebView.
3960             for (i in 0 until webViewStateAdapter!!.itemCount) {
3961                 // Get the WebView tab fragment.
3962                 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
3963
3964                 // Get the WebView fragment view.
3965                 val webViewFragmentView = webViewTabFragment.view
3966
3967                 // Only clear the cache if the WebView exists.
3968                 if (webViewFragmentView != null) {
3969                     // Get the nested scroll WebView from the tab fragment.
3970                     val nestedScrollWebView = webViewFragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
3971
3972                     // Clear the cache for this WebView.
3973                     nestedScrollWebView.clearCache(true)
3974                 }
3975             }
3976
3977             // Manually delete the cache directories.
3978             try {
3979                 // Delete the main cache directory.
3980                 val deleteCacheProcess = runtime.exec("rm -rf $privateDataDirectoryString/cache")
3981
3982                 // Delete the secondary `Service Worker` cache directory.
3983                 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
3984                 val deleteServiceWorkerProcess = runtime.exec(arrayOf("rm", "-rf", "$privateDataDirectoryString/app_webview/Default/Service Worker/"))
3985
3986                 // Wait until the processes have finished.
3987                 deleteCacheProcess.waitFor()
3988                 deleteServiceWorkerProcess.waitFor()
3989             } catch (exception: Exception) {
3990                 // Do nothing if an error is thrown.
3991             }
3992         }
3993
3994         // Wipe out each WebView.
3995         for (i in 0 until webViewStateAdapter!!.itemCount) {
3996             // Get the WebView tab fragment.
3997             val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
3998
3999             // Get the WebView frame layout.
4000             val webViewFrameLayout = webViewTabFragment.view as FrameLayout?
4001
4002             // Only wipe out the WebView if it exists.
4003             if (webViewFrameLayout != null) {
4004                 // Get the nested scroll WebView from the tab fragment.
4005                 val nestedScrollWebView = webViewFrameLayout.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
4006
4007                 // Clear SSL certificate preferences for this WebView.
4008                 nestedScrollWebView.clearSslPreferences()
4009
4010                 // Clear the back/forward history for this WebView.
4011                 nestedScrollWebView.clearHistory()
4012
4013                 // Remove all the views from the frame layout.
4014                 webViewFrameLayout.removeAllViews()
4015
4016                 // Destroy the internal state of the WebView.
4017                 nestedScrollWebView.destroy()
4018             }
4019         }
4020
4021         // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
4022         // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
4023         if (clearEverything) {
4024             try {
4025                 // Delete the folder.
4026                 val deleteAppWebviewProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview")
4027
4028                 // Wait until the process has finished.
4029                 deleteAppWebviewProcess.waitFor()
4030             } catch (exception: Exception) {
4031                 // Do nothing if an error is thrown.
4032             }
4033         }
4034
4035         // Close Privacy Browser.  `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
4036         finishAndRemoveTask()
4037
4038         // Remove the terminated program from RAM.  The status code is `0`.
4039         exitProcess(0)
4040     }
4041
4042     // The view parameter cannot be removed because it is called from the layout onClick.
4043     fun closeFindOnPage(@Suppress("UNUSED_PARAMETER")view: View?) {
4044         // Delete the contents of the find on page edit text.
4045         findOnPageEditText.text = null
4046
4047         // Clear the highlighted phrases if the WebView is not null.
4048         currentWebView?.clearMatches()
4049
4050         // Hide the find on page linear layout.
4051         findOnPageLinearLayout.visibility = View.GONE
4052
4053         // Show the toolbar.
4054         toolbar.visibility = View.VISIBLE
4055
4056         // Get a handle for the input method manager.
4057         val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
4058
4059         // Hide the keyboard.
4060         inputMethodManager.hideSoftInputFromWindow(toolbar.windowToken, 0)
4061     }
4062
4063     // The view parameter cannot be removed because it is called from the layout onClick.
4064     fun closeTab(@Suppress("UNUSED_PARAMETER")view: View?) {
4065         // Run the command according to the number of tabs.
4066         if (tabLayout.tabCount > 1) {  // There is more than one tab open.
4067             // Get the current tab number.
4068             val currentTabNumber = tabLayout.selectedTabPosition
4069
4070             // Delete the current tab.
4071             tabLayout.removeTabAt(currentTabNumber)
4072
4073             // 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,
4074             // meaning that the current WebView must be reset.  Otherwise it will happen automatically as the selected tab number changes.
4075             if (webViewStateAdapter!!.deletePage(currentTabNumber, webViewViewPager2))
4076                 setCurrentWebView(currentTabNumber)
4077         } else {  // There is only one tab open.
4078             clearAndExit()
4079         }
4080     }
4081
4082     override fun createBookmark(dialogFragment: DialogFragment, favoriteIconBitmap: Bitmap) {
4083         // Get the dialog.
4084         val dialog = dialogFragment.dialog!!
4085
4086         // Get the views from the dialog fragment.
4087         val createBookmarkNameEditText = dialog.findViewById<EditText>(R.id.create_bookmark_name_edittext)
4088         val createBookmarkUrlEditText = dialog.findViewById<EditText>(R.id.create_bookmark_url_edittext)
4089
4090         // Extract the strings from the edit texts.
4091         val bookmarkNameString = createBookmarkNameEditText.text.toString()
4092         val bookmarkUrlString = createBookmarkUrlEditText.text.toString()
4093
4094         // Create a favorite icon byte array output stream.
4095         val favoriteIconByteArrayOutputStream = ByteArrayOutputStream()
4096
4097         // Convert the favorite icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
4098         favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream)
4099
4100         // Convert the favorite icon byte array stream to a byte array.
4101         val favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray()
4102
4103         // Display the new bookmark below the current items in the (0 indexed) list.
4104         val newBookmarkDisplayOrder = bookmarksListView.count
4105
4106         // Create the bookmark.
4107         bookmarksDatabaseHelper!!.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolderId, newBookmarkDisplayOrder, favoriteIconByteArray)
4108
4109         // Update the bookmarks cursor with the current contents of this folder.
4110         bookmarksCursor = bookmarksDatabaseHelper!!.getBookmarksByDisplayOrder(currentBookmarksFolderId)
4111
4112         // Update the list view.
4113         bookmarksCursorAdapter.changeCursor(bookmarksCursor)
4114
4115         // Scroll to the new bookmark.
4116         bookmarksListView.setSelection(newBookmarkDisplayOrder)
4117     }
4118
4119     override fun createBookmarkFolder(dialogFragment: DialogFragment, favoriteIconBitmap: Bitmap) {
4120         // Get the dialog.
4121         val dialog = dialogFragment.dialog!!
4122
4123         // Get handles for the views in the dialog fragment.
4124         val folderNameEditText = dialog.findViewById<EditText>(R.id.folder_name_edittext)
4125         val defaultIconRadioButton = dialog.findViewById<RadioButton>(R.id.default_icon_radiobutton)
4126         val defaultIconImageView = dialog.findViewById<ImageView>(R.id.default_icon_imageview)
4127
4128         // Get new folder name string.
4129         val folderNameString = folderNameEditText.text.toString()
4130
4131         // Set the folder icon bitmap according to the dialog.
4132         val folderIconBitmap: Bitmap = if (defaultIconRadioButton.isChecked) {  // Use the default folder icon.
4133             // Get the default folder icon drawable.
4134             val folderIconDrawable = defaultIconImageView.drawable
4135
4136             // Convert the folder icon drawable to a bitmap drawable.
4137             val folderIconBitmapDrawable = folderIconDrawable as BitmapDrawable
4138
4139             // Convert the folder icon bitmap drawable to a bitmap.
4140             folderIconBitmapDrawable.bitmap
4141         } else {  // Use the WebView favorite icon.
4142             // Copy the favorite icon bitmap to the folder icon bitmap.
4143             favoriteIconBitmap
4144         }
4145
4146         // Create a folder icon byte array output stream.
4147         val folderIconByteArrayOutputStream = ByteArrayOutputStream()
4148
4149         // Convert the folder icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
4150         folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream)
4151
4152         // Convert the folder icon byte array stream to a byte array.
4153         val folderIconByteArray = folderIconByteArrayOutputStream.toByteArray()
4154
4155         // Move all the bookmarks down one in the display order.
4156         for (i in 0 until bookmarksListView.count) {
4157             // Get the bookmark database id.
4158             val databaseId = bookmarksListView.getItemIdAtPosition(i).toInt()
4159
4160             // Move the bookmark down one slot.
4161             bookmarksDatabaseHelper!!.updateDisplayOrder(databaseId, displayOrder = i + 1)
4162         }
4163
4164         // Create the folder, which will be placed at the top of the list view.
4165         bookmarksDatabaseHelper!!.createFolder(folderNameString, currentBookmarksFolderId, displayOrder = 0, folderIconByteArray)
4166
4167         // Update the bookmarks cursor with the current contents of this folder.
4168         bookmarksCursor = bookmarksDatabaseHelper!!.getBookmarksByDisplayOrder(currentBookmarksFolderId)
4169
4170         // Update the list view.
4171         bookmarksCursorAdapter.changeCursor(bookmarksCursor)
4172
4173         // Scroll to the new folder.
4174         bookmarksListView.setSelection(0)
4175     }
4176
4177     private fun downloadUrlWithExternalApp(url: String) {
4178         // Create a download intent.  Not specifying the action type will display the maximum number of options.
4179         val downloadIntent = Intent()
4180
4181         // Set the URI and the mime type.
4182         downloadIntent.setDataAndType(Uri.parse(url), "text/html")
4183
4184         // Flag the intent to open in a new task.
4185         downloadIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
4186
4187         // Show the chooser.
4188         startActivity(Intent.createChooser(downloadIntent, getString(R.string.download_with_external_app)))
4189     }
4190
4191     private fun exitFullScreenVideo() {
4192         // Re-enable the screen timeout.
4193         fullScreenVideoFrameLayout.keepScreenOn = false
4194
4195         // Unset the full screen video flag.
4196         displayingFullScreenVideo = false
4197
4198         // Remove all the views from the full screen video frame layout.
4199         fullScreenVideoFrameLayout.removeAllViews()
4200
4201         // Hide the full screen video frame layout.
4202         fullScreenVideoFrameLayout.visibility = View.GONE
4203
4204         // Enable the sliding drawers.
4205         drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED)
4206
4207         // Show the coordinator layout.
4208         coordinatorLayout.visibility = View.VISIBLE
4209
4210         // Apply the appropriate full screen mode flags.
4211         if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {  // Privacy Browser is currently in full screen browsing mode.
4212             // Hide the app bar if specified.
4213             if (hideAppBar) {
4214                 // Hide the tab linear layout.
4215                 tabsLinearLayout.visibility = View.GONE
4216
4217                 // Hide the app bar.
4218                 appBar.hide()
4219             }
4220
4221             /* Hide the system bars.
4222              * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4223              * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4224              * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4225              * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4226              */
4227
4228             // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4229             @Suppress("DEPRECATION")
4230             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
4231         } else {  // Switch to normal viewing mode.
4232             // Remove the `SYSTEM_UI` flags from the root frame layout.  The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4233             @Suppress("DEPRECATION")
4234             rootFrameLayout.systemUiVisibility = 0
4235         }
4236     }
4237
4238     // The view parameter cannot be removed because it is called from the layout onClick.
4239     fun findNextOnPage(@Suppress("UNUSED_PARAMETER")view: View?) {
4240         // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
4241         currentWebView!!.findNext(true)
4242     }
4243
4244     // The view parameter cannot be removed because it is called from the layout onClick.
4245     fun findPreviousOnPage(@Suppress("UNUSED_PARAMETER")view: View?) {
4246         // Go to the previous highlighted phrase on the page.  `false` goes backwards instead of forwards.
4247         currentWebView!!.findNext(false)
4248     }
4249
4250     override fun finishedPopulatingFilterLists(combinedFilterLists: ArrayList<ArrayList<List<Array<String>>>>) {
4251         // Store the filter lists.
4252         easyList = combinedFilterLists[0]
4253         easyPrivacy = combinedFilterLists[1]
4254         fanboysAnnoyanceList = combinedFilterLists[2]
4255         fanboysSocialList = combinedFilterLists[3]
4256         ultraList = combinedFilterLists[4]
4257         ultraPrivacy = combinedFilterLists[5]
4258
4259         // Check to see if the activity has been restarted with a saved state.
4260         if ((savedStateArrayList == null) || (savedStateArrayList!!.size == 0)) {  // The activity has not been restarted or it was restarted on start to change the theme.
4261             // Add the first tab.
4262             addNewPage(urlString = "", adjacent = false, moveToTab = false)
4263         } else {  // The activity has been restarted with a saved state.
4264             // Restore each tab.
4265             for (i in savedStateArrayList!!.indices) {
4266                 // Add a new tab.
4267                 tabLayout.addTab(tabLayout.newTab())
4268
4269                 // Get the new tab.
4270                 val newTab = tabLayout.getTabAt(i)!!
4271
4272                 // Set a custom view on the new tab.
4273                 newTab.setCustomView(R.layout.tab_custom_view)
4274
4275                 // Add the new page.
4276                 webViewStateAdapter!!.restorePage(savedStateArrayList!![i], savedNestedScrollWebViewStateArrayList!![i])
4277             }
4278
4279             // Reset the saved state variables.
4280             savedStateArrayList = null
4281             savedNestedScrollWebViewStateArrayList = null
4282
4283             // Get the intent that started the app.
4284             val intent = intent
4285
4286             // Reset the intent.  This prevents a duplicate tab from being created on restart.
4287             setIntent(Intent())
4288
4289             // Get the information from the intent.
4290             val intentAction = intent.action
4291             val intentUriData = intent.data
4292             val intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT)
4293
4294             // Determine if this is a web search.
4295             val isWebSearch = (intentAction != null) && (intentAction == Intent.ACTION_WEB_SEARCH)
4296
4297             // 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.
4298             if ((intentUriData != null) || (intentStringExtra != null) || isWebSearch) {  // A new tab is being loaded.
4299                 // Get the URL string.
4300                 val urlString = if (isWebSearch) {  // The intent is a web search.
4301                     // Sanitize the search input.
4302                     val encodedSearchString: String = try {
4303                         URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8")
4304                     } catch (exception: UnsupportedEncodingException) {
4305                         ""
4306                     }
4307
4308                     // Add the base search URL.
4309                     searchURL + encodedSearchString
4310                 } else { // The intent contains a URL formatted as a URI or a URL in the string extra.
4311                     // Get the URL string.
4312                     intentUriData?.toString() ?: intentStringExtra!!
4313                 }
4314
4315                 // Add a new tab if specified in the preferences.
4316                 if (sharedPreferences.getBoolean(getString(R.string.open_intents_in_new_tab_key), true)) {  // Load the URL in a new tab.
4317                     // Set the loading new intent flag.
4318                     loadingNewIntent = true
4319
4320                     // Add a new tab.
4321                     addNewPage(urlString, adjacent = false, moveToTab = true)
4322                 } else {  // Load the URL in the current tab.
4323                     // Make it so.
4324                     loadUrl(currentWebView!!, urlString)
4325                 }
4326             } else {  // A new tab is not being loaded.
4327                 // Restore the selected tab position.
4328                 if (savedTabPosition == 0) {  // The first tab is selected.
4329                     // Set the first page as the current WebView.
4330                     setCurrentWebView(0)
4331                 } else {  // The first tab is not selected.
4332                     // Select the tab when the layout has finished populating.
4333                     tabLayout.post {
4334                         // Get a handle for the tab.
4335                         val tab = tabLayout.getTabAt(savedTabPosition)!!
4336
4337                         // Select the tab.
4338                         tab.select()
4339                     }
4340                 }
4341             }
4342         }
4343     }
4344
4345     // Remove the warning that `OnTouchListener()` needs to override `performClick()`, as the only purpose of setting the `OnTouchListener()` is to make it do nothing.
4346     @SuppressLint("ClickableViewAccessibility")
4347     private fun initializeApp() {
4348         // Get a handle for the input method.
4349         val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
4350
4351         // Initialize the color spans for highlighting the URLs.
4352         initialGrayColorSpan = ForegroundColorSpan(getColor(R.color.gray_500))
4353         finalGrayColorSpan = ForegroundColorSpan(getColor(R.color.gray_500))
4354         redColorSpan = ForegroundColorSpan(getColor(R.color.red_text))
4355
4356         // Remove the formatting from the URL edit text when the user is editing the text.
4357         urlEditText.onFocusChangeListener = View.OnFocusChangeListener { _: View?, hasFocus: Boolean ->
4358             if (hasFocus) {  // The user is editing the URL text box.
4359                 // Remove the syntax highlighting.
4360                 urlEditText.text.removeSpan(redColorSpan)
4361                 urlEditText.text.removeSpan(initialGrayColorSpan)
4362                 urlEditText.text.removeSpan(finalGrayColorSpan)
4363             } else {  // The user has stopped editing the URL text box.
4364                 // Move to the beginning of the string.
4365                 urlEditText.setSelection(0)
4366
4367                 // Reapply the syntax highlighting.
4368                 UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
4369             }
4370         }
4371
4372         // Set the go button on the keyboard to load the URL in url text box.
4373         urlEditText.setOnKeyListener { _: View?, keyCode: Int, keyEvent: KeyEvent ->
4374             // If the event is a key-down event on the `enter` button, load the URL.
4375             if ((keyEvent.action == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {  // The enter key was pressed.
4376                 // Load the URL.
4377                 loadUrlFromTextBox()
4378
4379                 // Consume the event.
4380                 return@setOnKeyListener true
4381             } else {  // Some other key was pressed.
4382                 // Do not consume the event.
4383                 return@setOnKeyListener false
4384             }
4385         }
4386
4387         // Create an Orbot status broadcast receiver.
4388         orbotStatusBroadcastReceiver = object : BroadcastReceiver() {
4389             override fun onReceive(context: Context, intent: Intent) {
4390                 // Get the content of the status message.
4391                 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS")!!
4392
4393                 // If Privacy Browser is waiting on the proxy, load the website now that Orbot is connected.
4394                 if ((orbotStatus == ProxyHelper.ORBOT_STATUS_ON) && waitingForProxy) {
4395                     // Reset the waiting for proxy status.
4396                     waitingForProxy = false
4397
4398                     // Get a list of the current fragments.
4399                     val fragmentList = supportFragmentManager.fragments
4400
4401                     // Check each fragment to see if it is a waiting for proxy dialog.  Sometimes more than one is displayed.
4402                     for (i in fragmentList.indices) {
4403                         // Get the fragment tag.
4404                         val fragmentTag = fragmentList[i].tag
4405
4406                         // Check to see if it is the waiting for proxy dialog.
4407                         if (fragmentTag != null && fragmentTag == getString(R.string.waiting_for_proxy_dialog)) {
4408                             // Dismiss the waiting for proxy dialog.
4409                             (fragmentList[i] as DialogFragment).dismiss()
4410                         }
4411                     }
4412
4413                     // Reload existing URLs and load any URLs that are waiting for the proxy.
4414                     for (i in 0 until webViewStateAdapter!!.itemCount) {
4415                         // Get the WebView tab fragment.
4416                         val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
4417
4418                         // Get the fragment view.
4419                         val fragmentView = webViewTabFragment.view
4420
4421                         // Only process the WebViews if they exist.
4422                         if (fragmentView != null) {
4423                             // Get the nested scroll WebView from the tab fragment.
4424                             val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
4425
4426                             // Get the waiting for proxy URL string.
4427                             val waitingForProxyUrlString = nestedScrollWebView.waitingForProxyUrlString
4428
4429                             // Load the pending URL if it exists.
4430                             if (waitingForProxyUrlString.isNotEmpty()) {  // A URL is waiting to be loaded.
4431                                 // Load the URL.
4432                                 loadUrl(nestedScrollWebView, waitingForProxyUrlString)
4433
4434                                 // Reset the waiting for proxy URL string.
4435                                 nestedScrollWebView.waitingForProxyUrlString = ""
4436                             } else {  // No URL is waiting to be loaded.
4437                                 // Reload the existing URL.
4438                                 nestedScrollWebView.reload()
4439                             }
4440                         }
4441                     }
4442                 }
4443             }
4444         }
4445
4446         // Register the Orbot status broadcast receiver.  `ContextCompat` must be used until the minimum API >= 34.
4447         ContextCompat.registerReceiver(this, orbotStatusBroadcastReceiver, IntentFilter("org.torproject.android.intent.action.STATUS"), ContextCompat.RECEIVER_EXPORTED)
4448
4449         // Get handles for views that need to be modified.
4450         val bookmarksHeaderLinearLayout = findViewById<LinearLayout>(R.id.bookmarks_header_linearlayout)
4451         val launchBookmarksActivityFab = findViewById<FloatingActionButton>(R.id.launch_bookmarks_activity_fab)
4452         val createBookmarkFolderFab = findViewById<FloatingActionButton>(R.id.create_bookmark_folder_fab)
4453         val createBookmarkFab = findViewById<FloatingActionButton>(R.id.create_bookmark_fab)
4454
4455         // Handle tab selections.
4456         tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
4457             override fun onTabSelected(tab: TabLayout.Tab) {
4458                 // Close the find on page bar if it is open.
4459                 closeFindOnPage(null)
4460
4461                 // 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.
4462                 webViewViewPager2.post {
4463                     // Select the same page in the view pager.
4464                     webViewViewPager2.currentItem = tab.position
4465
4466                     // 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>
4467                     tabLayout.post {
4468                         setCurrentWebView(tab.position)
4469                     }
4470                 }
4471             }
4472
4473             override fun onTabUnselected(tab: TabLayout.Tab) {}
4474
4475             override fun onTabReselected(tab: TabLayout.Tab) {
4476                 // Only display the view SSL certificate dialog if the current WebView is not null.
4477                 // This can happen if the tab is programmatically reselected while the app is being restarted and is not yet populated.
4478                 if (currentWebView != null) {
4479                     // Instantiate the View SSL Certificate dialog.
4480                     val viewSslCertificateDialogFragment: DialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView!!.webViewFragmentId, currentWebView!!.getFavoriteIcon())
4481
4482                     // Display the View SSL Certificate dialog.
4483                     viewSslCertificateDialogFragment.show(supportFragmentManager, getString(R.string.view_ssl_certificate))
4484                 }
4485             }
4486         })
4487
4488         // Set a touch listener on the bookmarks header linear layout so that touches don't pass through to the button underneath.
4489         bookmarksHeaderLinearLayout.setOnTouchListener { _: View?, _: MotionEvent? -> true }
4490
4491         // Set the launch bookmarks activity floating action button to launch the bookmarks activity.
4492         launchBookmarksActivityFab.setOnClickListener {
4493             // Get a copy of the favorite icon bitmap.
4494             val currentFavoriteIconBitmap = currentWebView!!.getFavoriteIcon()
4495
4496             // Create a favorite icon byte array output stream.
4497             val currentFavoriteIconByteArrayOutputStream = ByteArrayOutputStream()
4498
4499             // Convert the favorite icon bitmap to a byte array.  `0` is for lossless compression (the only option for a PNG).
4500             currentFavoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, currentFavoriteIconByteArrayOutputStream)
4501
4502             // Convert the favorite icon byte array stream to a byte array.
4503             val currentFavoriteIconByteArray = currentFavoriteIconByteArrayOutputStream.toByteArray()
4504
4505             // Create an intent to launch the bookmarks activity.
4506             val bookmarksIntent = Intent(applicationContext, BookmarksActivity::class.java)
4507
4508             // Add the extra information to the intent.
4509             bookmarksIntent.putExtra(CURRENT_FOLDER_ID, currentBookmarksFolderId)
4510             bookmarksIntent.putExtra(CURRENT_TITLE, currentWebView!!.title)
4511             bookmarksIntent.putExtra(CURRENT_URL, currentWebView!!.url)
4512             bookmarksIntent.putExtra(CURRENT_FAVORITE_ICON_BYTE_ARRAY, currentFavoriteIconByteArray)
4513
4514             // Make it so.
4515             startActivity(bookmarksIntent)
4516         }
4517
4518         // Set the create new bookmark folder floating action button to display an alert dialog.
4519         createBookmarkFolderFab.setOnClickListener {
4520             // Create a create bookmark folder dialog.
4521             val createBookmarkFolderDialog: DialogFragment = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView!!.getFavoriteIcon())
4522
4523             // Show the create bookmark folder dialog.
4524             createBookmarkFolderDialog.show(supportFragmentManager, getString(R.string.create_folder))
4525         }
4526
4527         // Set the create new bookmark floating action button to display an alert dialog.
4528         createBookmarkFab.setOnClickListener {
4529             // Instantiate the create bookmark dialog.
4530             val createBookmarkDialog: DialogFragment = CreateBookmarkDialog.createBookmark(currentWebView!!.url!!, currentWebView!!.title!!, currentWebView!!.getFavoriteIcon())
4531
4532             // Display the create bookmark dialog.
4533             createBookmarkDialog.show(supportFragmentManager, getString(R.string.create_bookmark))
4534         }
4535
4536         // Search for the string on the page whenever a character changes in the find on page edit text.
4537         findOnPageEditText.addTextChangedListener(object : TextWatcher {
4538             override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
4539
4540             override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
4541
4542             override fun afterTextChanged(s: Editable) {
4543                 // 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.
4544                 currentWebView?.findAllAsync(findOnPageEditText.text.toString())
4545             }
4546         })
4547
4548         // Set the `check mark` button for the find on page edit text keyboard to close the soft keyboard.
4549         findOnPageEditText.setOnKeyListener { _: View?, keyCode: Int, keyEvent: KeyEvent ->
4550             if ((keyEvent.action == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {  // The `enter` key was pressed.
4551                 // Hide the soft keyboard.
4552                 inputMethodManager.hideSoftInputFromWindow(currentWebView!!.windowToken, 0)
4553
4554                 // Consume the event.
4555                 return@setOnKeyListener true
4556             } else {  // A different key was pressed.
4557                 // Do not consume the event.
4558                 return@setOnKeyListener false
4559             }
4560         }
4561
4562         // Implement swipe to refresh.
4563         swipeRefreshLayout.setOnRefreshListener {
4564             // Reload the website.
4565             currentWebView!!.reload()
4566         }
4567
4568         // Store the default progress view offsets.
4569         defaultProgressViewStartOffset = swipeRefreshLayout.progressViewStartOffset
4570         defaultProgressViewEndOffset = swipeRefreshLayout.progressViewEndOffset
4571
4572         // Set the refresh color scheme according to the theme.
4573         swipeRefreshLayout.setColorSchemeResources(R.color.blue_text)
4574
4575         // Initialize a color background typed value.
4576         val colorBackgroundTypedValue = TypedValue()
4577
4578         // Get the color background from the theme.
4579         theme.resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true)
4580
4581         // Get the color background int from the typed value.
4582         val colorBackgroundInt = colorBackgroundTypedValue.data
4583
4584         // Set the swipe refresh background color.
4585         swipeRefreshLayout.setProgressBackgroundColorSchemeColor(colorBackgroundInt)
4586
4587         // Set the drawer titles, which identify the drawer layouts in accessibility mode.
4588         drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer))
4589         drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks))
4590
4591         // Load the bookmarks folder.
4592         loadBookmarksFolder()
4593
4594         // Handle clicks on bookmarks.
4595         bookmarksListView.onItemClickListener = AdapterView.OnItemClickListener { _: AdapterView<*>?, _: View?, _: Int, id: Long ->
4596             // Convert the id from long to int to match the format of the bookmarks database.
4597             val databaseId = id.toInt()
4598
4599             // Get the bookmark cursor for this ID.
4600             val bookmarkCursor = bookmarksDatabaseHelper!!.getBookmark(databaseId)
4601
4602             // Move the bookmark cursor to the first row.
4603             bookmarkCursor.moveToFirst()
4604
4605             // Act upon the bookmark according to the type.
4606             if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndexOrThrow(IS_FOLDER)) == 1) {  // The selected bookmark is a folder.
4607                 // Store the folder ID.
4608                 currentBookmarksFolderId = bookmarkCursor.getLong(bookmarkCursor.getColumnIndexOrThrow(FOLDER_ID))
4609
4610                 // Load the new folder.
4611                 loadBookmarksFolder()
4612             } else {  // The selected bookmark is not a folder.
4613                 // Load the bookmark URL.
4614                 loadUrl(currentWebView!!, bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BOOKMARK_URL)))
4615
4616                 // Close the bookmarks drawer if it is not pinned.
4617                 if (!bookmarksDrawerPinned)
4618                     drawerLayout.closeDrawer(GravityCompat.END)
4619             }
4620
4621             // Close the cursor.
4622             bookmarkCursor.close()
4623         }
4624
4625         // Handle long-presses on bookmarks.
4626         bookmarksListView.onItemLongClickListener = AdapterView.OnItemLongClickListener { _: AdapterView<*>?, _: View?, _: Int, id: Long ->
4627             // Convert the database ID from `long` to `int`.
4628             val databaseId = id.toInt()
4629
4630             // Run the commands associated with the type.
4631             if (bookmarksDatabaseHelper!!.isFolder(databaseId)) {  // The bookmark is a folder.
4632                 // Get the folder ID.
4633                 val folderId = bookmarksDatabaseHelper!!.getFolderId(databaseId)
4634
4635                 // Get a cursor of all the bookmarks in the folder.
4636                 val bookmarksCursor = bookmarksDatabaseHelper!!.getFolderBookmarks(folderId)
4637
4638                 // Move to the first entry in the cursor.
4639                 bookmarksCursor.moveToFirst()
4640
4641                 // Open each bookmark
4642                 for (i in 0 until bookmarksCursor.count) {
4643                     // Load the bookmark in a new tab, moving to the tab for the first bookmark if the drawer is not pinned.
4644                     addNewPage(bookmarksCursor.getString(bookmarksCursor.getColumnIndexOrThrow(BOOKMARK_URL)), adjacent = false, moveToTab = !bookmarksDrawerPinned && (i == 0))
4645
4646                     // Move to the next bookmark.
4647                     bookmarksCursor.moveToNext()
4648                 }
4649
4650                 // Close the cursor.
4651                 bookmarksCursor.close()
4652             } else {  // The bookmark is not a folder.
4653                 // Get the bookmark cursor for this ID.
4654                 val bookmarkCursor = bookmarksDatabaseHelper!!.getBookmark(databaseId)
4655
4656                 // Move the bookmark cursor to the first row.
4657                 bookmarkCursor.moveToFirst()
4658
4659                 // Load the bookmark in a new tab and move to the tab if the drawer is not pinned.
4660                 addNewPage(bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BOOKMARK_URL)), adjacent = true, moveToTab = !bookmarksDrawerPinned)
4661
4662                 // Close the cursor.
4663                 bookmarkCursor.close()
4664             }
4665
4666             // Close the bookmarks drawer if it is not pinned.
4667             if (!bookmarksDrawerPinned)
4668                 drawerLayout.closeDrawer(GravityCompat.END)
4669
4670             // Consume the event.
4671             true
4672         }
4673
4674         // The drawer listener is used to update the navigation menu.
4675         drawerLayout.addDrawerListener(object : DrawerLayout.DrawerListener {
4676             override fun onDrawerSlide(drawerView: View, slideOffset: Float) {}
4677
4678             override fun onDrawerOpened(drawerView: View) {}
4679
4680             override fun onDrawerClosed(drawerView: View) {}
4681
4682             override fun onDrawerStateChanged(newState: Int) {
4683                 if (newState == DrawerLayout.STATE_SETTLING || newState == DrawerLayout.STATE_DRAGGING) {  // A drawer is opening or closing.
4684                     // Update the navigation menu items if the WebView is not null.
4685                     if (currentWebView != null) {
4686                         // Set the enabled status of the menu items.
4687                         navigationBackMenuItem.isEnabled = currentWebView!!.canGoBack()
4688                         navigationForwardMenuItem.isEnabled = currentWebView!!.canGoForward()
4689                         navigationScrollToBottomMenuItem.isEnabled = (currentWebView!!.canScrollVertically(-1) || currentWebView!!.canScrollVertically(1))
4690                         navigationHistoryMenuItem.isEnabled = currentWebView!!.canGoBack() || currentWebView!!.canGoForward()
4691
4692                         // Update the scroll menu item.
4693                         if (currentWebView!!.scrollY == 0) {  // The WebView is scrolled to the top.
4694                             // Set the title.
4695                             navigationScrollToBottomMenuItem.title = getString(R.string.scroll_to_bottom)
4696
4697                             // Set the icon.
4698                             navigationScrollToBottomMenuItem.icon = AppCompatResources.getDrawable(applicationContext, R.drawable.move_down_enabled)
4699                         } else {  // The WebView is not scrolled to the top.
4700                             // Set the title.
4701                             navigationScrollToBottomMenuItem.title = getString(R.string.scroll_to_top)
4702
4703                             // Set the icon.
4704                             navigationScrollToBottomMenuItem.icon = AppCompatResources.getDrawable(applicationContext, R.drawable.move_up_enabled)
4705                         }
4706
4707                         // Display the number of blocked requests.
4708                         navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + currentWebView!!.getRequestsCount(BLOCKED_REQUESTS)
4709
4710                         // Hide the keyboard (if displayed).
4711                         inputMethodManager.hideSoftInputFromWindow(currentWebView!!.windowToken, 0)
4712                     }
4713
4714                     // 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.
4715                     urlEditText.clearFocus()
4716
4717                     // 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.
4718                     // Clearing the focus from the WebView removes any text selection markers and context menus, which otherwise draw above the open drawers.
4719                     currentWebView?.clearFocus()
4720
4721                     if (bottomAppBar && navigationDrawerFirstView) {
4722                         // Reset the navigation drawer first view flag.
4723                         navigationDrawerFirstView = false
4724
4725                         // Get a handle for the navigation recycler view.
4726                         val navigationRecyclerView = navigationView.getChildAt(0) as RecyclerView
4727
4728                         // Get the navigation linear layout manager.
4729                         val navigationLinearLayoutManager = navigationRecyclerView.layoutManager as LinearLayoutManager
4730
4731                         // Scroll the navigation drawer to the bottom.
4732                         navigationLinearLayoutManager.scrollToPositionWithOffset(13, 0)
4733                     }
4734                 }
4735             }
4736         })
4737
4738         // Inflate a bare WebView to get the default user agent.  It is not used to render content on the screen.
4739         @SuppressLint("InflateParams") val webViewLayout = layoutInflater.inflate(R.layout.bare_webview, null, false)
4740
4741         // Get a handle for the WebView.
4742         val bareWebView = webViewLayout.findViewById<WebView>(R.id.bare_webview)
4743
4744         // Store the default user agent.
4745         webViewDefaultUserAgent = bareWebView.settings.userAgentString
4746
4747         // Destroy the bare WebView.
4748         bareWebView.destroy()
4749
4750         // Update the domains settings set.
4751         updateDomainsSettingsSet()
4752
4753         // Instantiate the check filter list helper.
4754         checkFilterListHelper = CheckFilterListHelper()
4755     }
4756
4757     @SuppressLint("ClickableViewAccessibility")
4758     override fun initializeWebView(nestedScrollWebView: NestedScrollWebView, pagePosition: Int, progressBar: ProgressBar, urlString: String, restoringState: Boolean) {
4759         // Get the WebView theme.
4760         val webViewTheme = sharedPreferences.getString(getString(R.string.webview_theme_key), getString(R.string.webview_theme_default_value))
4761
4762         // Get the WebView theme entry values string array.
4763         val webViewThemeEntryValuesStringArray = resources.getStringArray(R.array.webview_theme_entry_values)
4764
4765         // Set the WebView theme if algorithmic darkening is supported.
4766         if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {
4767             // Set the WebView them.  A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
4768             if (webViewTheme == webViewThemeEntryValuesStringArray[1]) {  // The light theme is selected.
4769                 // Turn off algorithmic darkening.
4770                 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
4771
4772                 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
4773                 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
4774                 nestedScrollWebView.visibility = View.VISIBLE
4775             } else if (webViewTheme == webViewThemeEntryValuesStringArray[2]) {  // The dark theme is selected.
4776                 // Turn on algorithmic darkening.
4777                 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
4778             } else {  // The system default theme is selected.
4779                 // Get the current theme status.
4780                 val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
4781
4782                 // Set the algorithmic darkening according to the current system theme status.
4783                 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) {  // The system is in day mode.
4784                     // Turn off algorithmic darkening.
4785                     WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
4786
4787                     // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
4788                     // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
4789                     nestedScrollWebView.visibility = View.VISIBLE
4790                 } else {  // The system is in night mode.
4791                     // Turn on algorithmic darkening.
4792                     WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
4793                 }
4794             }
4795         }
4796
4797         // Get a handle for the input method manager.
4798         val inputMethodManager = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
4799
4800         // Set the app bar scrolling.
4801         nestedScrollWebView.isNestedScrollingEnabled = scrollAppBar
4802
4803         // Allow pinch to zoom.
4804         nestedScrollWebView.settings.builtInZoomControls = true
4805
4806         // Hide zoom controls.
4807         nestedScrollWebView.settings.displayZoomControls = false
4808
4809         // Don't allow mixed content (HTTP and HTTPS) on the same website.
4810         nestedScrollWebView.settings.mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW
4811
4812         // Set the WebView to load in overview mode (zoomed out to the maximum width).
4813         nestedScrollWebView.settings.loadWithOverviewMode = true
4814
4815         // Explicitly disable geolocation.
4816         nestedScrollWebView.settings.setGeolocationEnabled(false)
4817
4818         // Allow loading of file:// URLs.  This is necessary for opening MHT web archives, which are copied into a temporary cache location.
4819         nestedScrollWebView.settings.allowFileAccess = true
4820
4821         // Create a double-tap gesture detector to toggle full-screen mode.
4822         val doubleTapGestureDetector = GestureDetector(this, object : GestureDetector.SimpleOnGestureListener() {
4823             // Override `onDoubleTap()`.  All other events are handled using the default settings.
4824             override fun onDoubleTap(motionEvent: MotionEvent): Boolean {
4825                 return if (fullScreenBrowsingModeEnabled) {  // Only process the double-tap if full screen browsing mode is enabled.
4826                     // Toggle the full screen browsing mode tracker.
4827                     inFullScreenBrowsingMode = !inFullScreenBrowsingMode
4828
4829                     // Toggle the full screen browsing mode.
4830                     if (inFullScreenBrowsingMode) {  // Switch to full screen mode.
4831                         // Hide the app bar if specified.
4832                         if (hideAppBar) {  // App bar hiding is enabled.
4833                             // Close the find on page bar if it is visible.
4834                             closeFindOnPage(null)
4835
4836                             // Hide the tab linear layout.
4837                             tabsLinearLayout.visibility = View.GONE
4838
4839                             // Hide the app bar.
4840                             appBar.hide()
4841
4842                             // Set layout and scrolling parameters according to the position of the app bar.
4843                             if (bottomAppBar) {  // The app bar is at the bottom.
4844                                 // Reset the WebView padding to fill the available space.
4845                                 swipeRefreshLayout.setPadding(0, 0, 0, 0)
4846                             } else {  // The app bar is at the top.
4847                                 // Check to see if the app bar is normally scrolled.
4848                                 if (scrollAppBar) {  // The app bar is scrolled when it is displayed.
4849                                     // Get the swipe refresh layout parameters.
4850                                     val swipeRefreshLayoutParams = swipeRefreshLayout.layoutParams as CoordinatorLayout.LayoutParams
4851
4852                                     // Remove the off-screen scrolling layout.
4853                                     swipeRefreshLayoutParams.behavior = null
4854                                 } else {  // The app bar is not scrolled when it is displayed.
4855                                     // Remove the padding from the top of the swipe refresh layout.
4856                                     swipeRefreshLayout.setPadding(0, 0, 0, 0)
4857
4858                                     // The swipe refresh circle must be moved above the now removed status bar location.
4859                                     swipeRefreshLayout.setProgressViewOffset(false, -200, defaultProgressViewEndOffset)
4860                                 }
4861                             }
4862                         } else {  // App bar hiding is not enabled.
4863                             // Adjust the UI for the bottom app bar.
4864                             if (bottomAppBar) {
4865                                 // Adjust the UI according to the scrolling of the app bar.
4866                                 if (scrollAppBar) {
4867                                     // Reset the WebView padding to fill the available space.
4868                                     swipeRefreshLayout.setPadding(0, 0, 0, 0)
4869                                 } else {
4870                                     // Move the WebView above the app bar layout.
4871                                     swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
4872                                 }
4873                             }
4874                         }
4875
4876                         /* Hide the system bars.
4877                          * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4878                          * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4879                          * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4880                          * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4881                          */
4882
4883                         // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4884                         @Suppress("DEPRECATION")
4885                         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
4886                     } else {  // Switch to normal viewing mode.
4887                         // Show the app bar if it was hidden.
4888                         if (hideAppBar) {
4889                             // Show the tab linear layout.
4890                             tabsLinearLayout.visibility = View.VISIBLE
4891
4892                             // Show the app bar.
4893                             appBar.show()
4894                         }
4895
4896                         // Set layout and scrolling parameters according to the position of the app bar.
4897                         if (bottomAppBar) {  // The app bar is at the bottom.
4898                             // Adjust the UI.
4899                             if (scrollAppBar) {
4900                                 // Reset the WebView padding to fill the available space.
4901                                 swipeRefreshLayout.setPadding(0, 0, 0, 0)
4902                             } else {
4903                                 // Move the WebView above the app bar layout.
4904                                 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
4905                             }
4906                         } else {  // The app bar is at the top.
4907                             // Check to see if the app bar is normally scrolled.
4908                             if (scrollAppBar) {  // The app bar is scrolled when it is displayed.
4909                                 // Get the swipe refresh layout parameters.
4910                                 val swipeRefreshLayoutParams = swipeRefreshLayout.layoutParams as CoordinatorLayout.LayoutParams
4911
4912                                 // Add the off-screen scrolling layout.
4913                                 swipeRefreshLayoutParams.behavior = AppBarLayout.ScrollingViewBehavior()
4914                             } else {  // The app bar is not scrolled when it is displayed.
4915                                 // The swipe refresh layout must be manually moved below the app bar layout.
4916                                 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0)
4917
4918                                 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
4919                                 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight)
4920                             }
4921                         }
4922
4923                         // Remove the `SYSTEM_UI` flags from the root frame layout.  The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4924                         @Suppress("DEPRECATION")
4925                         rootFrameLayout.systemUiVisibility = 0
4926                     }
4927
4928                     // Consume the double-tap.
4929                     true
4930                 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
4931                     // Return false.
4932                     false
4933                 }
4934             }
4935
4936             override fun onFling(motionEvent1: MotionEvent?, motionEvent2: MotionEvent, velocityX: Float, velocityY: Float): Boolean {
4937                 // Scroll the bottom app bar if enabled.
4938                 if (bottomAppBar && scrollAppBar && !objectAnimator.isRunning && (motionEvent1 != null)) {
4939                     // Calculate the Y change.
4940                     val motionY = motionEvent2.y - motionEvent1.y
4941
4942                     // Scroll the app bar if the change is greater than 50 pixels.
4943                     if (motionY > 50) {
4944                         // Animate the bottom app bar onto the screen.
4945                         objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0f)
4946                     } else if (motionY < -50) {
4947                         // Animate the bottom app bar off the screen.
4948                         objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", appBarLayout.height.toFloat())
4949                     }
4950
4951                     // Make it so.
4952                     objectAnimator.start()
4953                 }
4954
4955                 // Do not consume the event.
4956                 return false
4957             }
4958         })
4959
4960         // Pass all touch events on the WebView through the double-tap gesture detector.
4961         nestedScrollWebView.setOnTouchListener { view: View, motionEvent: MotionEvent? ->
4962             // Call `performClick()` on the view, which is required for accessibility.
4963             view.performClick()
4964
4965             // Check for double-taps.
4966             doubleTapGestureDetector.onTouchEvent(motionEvent!!)
4967         }
4968
4969         // Register the WebView for a context menu.  This is used to see link targets and download images.
4970         registerForContextMenu(nestedScrollWebView)
4971
4972         // Allow the downloading of files.
4973         nestedScrollWebView.setDownloadListener { downloadUrlString: String?, userAgent: String?, contentDisposition: String?, mimetype: String?, contentLength: Long ->
4974             // Check the download preference.
4975             if (downloadWithExternalApp) {  // Download with an external app.
4976                 downloadUrlWithExternalApp(downloadUrlString!!)
4977             } else {  // Handle the download inside of Privacy Browser.
4978                 // Define a formatted file size string.
4979
4980                 // Process the content length if it contains data.
4981                 val formattedFileSizeString = if (contentLength > 0) {  // The content length is greater than 0.
4982                     // Format the content length as a string.
4983                     NumberFormat.getInstance().format(contentLength) + " " + getString(R.string.bytes)
4984                 } else {  // The content length is not greater than 0.
4985                     // Set the formatted file size string to be `unknown size`.
4986                     getString(R.string.unknown_size)
4987                 }
4988
4989                 // Get the file name from the content disposition.
4990                 val fileNameString = UrlHelper.getFileName(this, contentDisposition, mimetype, downloadUrlString!!)
4991
4992                 // Instantiate the save dialog.
4993                 val saveDialogFragment = SaveDialog.saveUrl(downloadUrlString, fileNameString, formattedFileSizeString, userAgent!!, nestedScrollWebView.acceptCookies)
4994
4995                 // 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.
4996                 try {
4997                     // Show the save dialog.
4998                     saveDialogFragment.show(supportFragmentManager, getString(R.string.save_dialog))
4999                 } catch (exception: Exception) {  // The dialog could not be shown.
5000                     // Add the dialog to the pending dialog array list.  It will be displayed in `onStart()`.
5001                     pendingDialogsArrayList.add(PendingDialogDataClass(saveDialogFragment, getString(R.string.save_dialog)))
5002                 }
5003             }
5004
5005             // Get the current page position.
5006             val currentPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
5007
5008             // Get the corresponding tab.
5009             val tab = tabLayout.getTabAt(currentPagePosition)!!
5010
5011             // Get the tab custom view.
5012             val tabCustomView = tab.customView!!
5013
5014             // Get the tab views.
5015             val tabFavoriteIconImageView = tabCustomView.findViewById<ImageView>(R.id.favorite_icon_imageview)
5016             val tabTitleTextView = tabCustomView.findViewById<TextView>(R.id.title_textview)
5017
5018             // Restore the previous webpage favorite icon and title if the title is currently set to `Loading...`.
5019             if (tabTitleTextView.text.toString() == getString(R.string.loading)) {
5020                 // Restore the previous webpage title text.
5021                 tabTitleTextView.text = nestedScrollWebView.previousWebpageTitle
5022
5023                 // Restore the previous webpage favorite icon if it is not null.
5024                 if (nestedScrollWebView.previousFavoriteIconDrawable != null)
5025                     tabFavoriteIconImageView.setImageDrawable(nestedScrollWebView.previousFavoriteIconDrawable)
5026             }
5027         }
5028
5029         // Update the find on page count.
5030         nestedScrollWebView.setFindListener { activeMatchOrdinal, numberOfMatches, isDoneCounting ->
5031             if (isDoneCounting && (numberOfMatches == 0)) {  // There are no matches.
5032                 // Set the find on page count text view to be `0/0`.
5033                 findOnPageCountTextView.setText(R.string.zero_of_zero)
5034             } else if (isDoneCounting) {  // There are matches.
5035                 // The active match ordinal is zero-based.
5036                 val activeMatch = activeMatchOrdinal + 1
5037
5038                 // Build the match string.
5039                 val matchString = "$activeMatch/$numberOfMatches"
5040
5041                 // Update the find on page count text view.
5042                 findOnPageCountTextView.text = matchString
5043             }
5044         }
5045
5046         // Process scroll changes.
5047         nestedScrollWebView.setOnScrollChangeListener { _: View?, _: Int, _: Int, _: Int, _: Int ->
5048             // Set the swipe to refresh status.
5049             if (nestedScrollWebView.swipeToRefresh)  // Only enable swipe to refresh if the WebView is scrolled to the top.
5050                 swipeRefreshLayout.isEnabled = nestedScrollWebView.scrollY == 0
5051             else  // Disable swipe to refresh.
5052                 swipeRefreshLayout.isEnabled = false
5053
5054             // Reinforce the system UI visibility flags if in full screen browsing mode.
5055             // This hides the status and navigation bars, which are displayed if other elements are shown, like dialog boxes, the options menu, or the keyboard.
5056             if (inFullScreenBrowsingMode) {
5057                 /* Hide the system bars.
5058                  * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5059                  * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5060                  * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5061                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5062                  */
5063
5064                 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
5065                 @Suppress("DEPRECATION")
5066                 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
5067             }
5068         }
5069
5070         // Set the web chrome client.
5071         nestedScrollWebView.webChromeClient = object : WebChromeClient() {
5072             // Update the progress bar when a page is loading.
5073             override fun onProgressChanged(view: WebView, progress: Int) {
5074                 // Update the progress bar.
5075                 progressBar.progress = progress
5076
5077                 // Set the visibility of the progress bar.
5078                 if (progress < 100) {
5079                     // Show the progress bar.
5080                     progressBar.visibility = View.VISIBLE
5081                 } else {
5082                     // Hide the progress bar.
5083                     progressBar.visibility = View.GONE
5084
5085                     //Stop the swipe to refresh indicator if it is running
5086                     swipeRefreshLayout.isRefreshing = false
5087
5088                     // 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.
5089                     nestedScrollWebView.visibility = View.VISIBLE
5090                 }
5091             }
5092
5093             // Set the favorite icon when it changes.
5094             override fun onReceivedIcon(view: WebView, icon: Bitmap) {
5095                 // 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.
5096                 // This prevents low resolution icons from replacing high resolution one.
5097                 // The check for the visibility of the progress bar can possibly be removed once https://redmine.stoutner.com/issues/747 is fixed.
5098                 if ((progressBar.visibility == View.GONE) && (icon.height > nestedScrollWebView.getFavoriteIconHeight())) {
5099                     // Store the new favorite icon.
5100                     nestedScrollWebView.setFavoriteIcon(icon)
5101
5102                     // Get the current page position.
5103                     val currentPosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
5104
5105                     // Get the current tab.
5106                     val tab = tabLayout.getTabAt(currentPosition)
5107
5108                     // Check to see if the tab has been populated.
5109                     if (tab != null) {
5110                         // Get the custom view from the tab.
5111                         val tabView = tab.customView
5112
5113                         // Check to see if the custom tab view has been populated.
5114                         if (tabView != null) {
5115                             // Get the favorite icon image view from the tab.
5116                             val tabFavoriteIconImageView = tabView.findViewById<ImageView>(R.id.favorite_icon_imageview)
5117
5118                             // Display the favorite icon in the tab.
5119                             tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true))
5120                         }
5121                     }
5122                 }
5123             }
5124
5125             // Save a copy of the title when it changes.
5126             override fun onReceivedTitle(view: WebView, title: String) {
5127                 // Get the current page position.
5128                 val currentPosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
5129
5130                 // Get the current tab.
5131                 val tab = tabLayout.getTabAt(currentPosition)
5132
5133                 // Only populate the title text view if the tab has been fully created.
5134                 if (tab != null) {
5135                     // Get the custom view from the tab.
5136                     val tabView = tab.customView
5137
5138                     // Only populate the title text view if the tab view has been fully populated.
5139                     if (tabView != null) {
5140                         // Get the title text view from the tab.
5141                         val tabTitleTextView = tabView.findViewById<TextView>(R.id.title_textview)
5142
5143                         // Set the title according to the URL.
5144                         if (title == "about:blank") {
5145                             // Set the title to indicate a new tab.
5146                             tabTitleTextView.setText(R.string.new_tab)
5147                         } else {
5148                             // Set the title as the tab text.
5149                             tabTitleTextView.text = title
5150                         }
5151                     }
5152                 }
5153             }
5154
5155             // Enter full screen video.
5156             override fun onShowCustomView(video: View, callback: CustomViewCallback) {
5157                 // Set the full screen video flag.
5158                 displayingFullScreenVideo = true
5159
5160                 // Hide the keyboard.
5161                 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.windowToken, 0)
5162
5163                 // Hide the coordinator layout.
5164                 coordinatorLayout.visibility = View.GONE
5165
5166                 /* Hide the system bars.
5167                  * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5168                  * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5169                  * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5170                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5171                  */
5172
5173                 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
5174                 @Suppress("DEPRECATION")
5175                 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
5176
5177                 // Disable the sliding drawers.
5178                 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
5179
5180                 // Add the video view to the full screen video frame layout.
5181                 fullScreenVideoFrameLayout.addView(video)
5182
5183                 // Show the full screen video frame layout.
5184                 fullScreenVideoFrameLayout.visibility = View.VISIBLE
5185
5186                 // Disable the screen timeout while the video is playing.  YouTube does this automatically, but not all other videos do.
5187                 fullScreenVideoFrameLayout.keepScreenOn = true
5188             }
5189
5190             // Exit full screen video.
5191             override fun onHideCustomView() {
5192                 // Exit the full screen video.
5193                 exitFullScreenVideo()
5194             }
5195
5196             // Upload files.
5197             override fun onShowFileChooser(webView: WebView, filePathCallback: ValueCallback<Array<Uri>>, fileChooserParams: FileChooserParams): Boolean {
5198                 // Store the file path callback.
5199                 fileChooserCallback = filePathCallback
5200
5201                 // Create an intent to open a chooser based on the file chooser parameters.
5202                 val fileChooserIntent = fileChooserParams.createIntent()
5203
5204                 // Check to see if the file chooser intent resolves to an installed package.
5205                 if (fileChooserIntent.resolveActivity(packageManager) != null) {  // The file chooser intent is fine.
5206                     // Launch the file chooser intent.
5207                     browseFileUploadActivityResultLauncher.launch(fileChooserIntent)
5208                 } else {  // The file chooser intent will cause a crash.
5209                     // Create a generic intent to open a chooser.
5210                     val genericFileChooserIntent = Intent(Intent.ACTION_GET_CONTENT)
5211
5212                     // Request an openable file.
5213                     genericFileChooserIntent.addCategory(Intent.CATEGORY_OPENABLE)
5214
5215                     // Set the file type to everything.
5216                     genericFileChooserIntent.type = "*/*"
5217
5218                     // Launch the generic file chooser intent.
5219                     browseFileUploadActivityResultLauncher.launch(genericFileChooserIntent)
5220                 }
5221
5222                 // Handle the event.
5223                 return true
5224             }
5225         }
5226         nestedScrollWebView.webViewClient = object : WebViewClient() {
5227             // `shouldOverrideUrlLoading` makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
5228             override fun shouldOverrideUrlLoading(view: WebView, webResourceRequest: WebResourceRequest): Boolean {
5229                 // Get the URL from the web resource request.
5230                 var requestUrlString = webResourceRequest.url.toString()
5231
5232                 // Sanitize the url.
5233                 requestUrlString = sanitizeUrl(requestUrlString)
5234
5235                 // Handle the URL according to the type.
5236                 return if (requestUrlString.startsWith("http")) {  // Load the URL in Privacy Browser.
5237                     // Load the URL.  By using `loadUrl()`, instead of `loadUrlFromBase()`, the Referer header will never be sent.
5238                     loadUrl(nestedScrollWebView, requestUrlString)
5239
5240                     // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
5241                     // Custom headers cannot be added if false is returned and the WebView handles the loading of the URL.
5242                     true
5243                 } else if (requestUrlString.startsWith("mailto:")) {  // Load the email address in an external email program.
5244                     // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
5245                     val emailIntent = Intent(Intent.ACTION_SENDTO)
5246
5247                     // Parse the url and set it as the data for the intent.
5248                     emailIntent.data = Uri.parse(requestUrlString)
5249
5250                     // Open the email program in a new task instead of as part of Privacy Browser.
5251                     emailIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
5252
5253                     try {
5254                         // Make it so.
5255                         startActivity(emailIntent)
5256                     } catch (exception: ActivityNotFoundException) {
5257                         // Display a snackbar.
5258                         Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
5259                     }
5260
5261                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5262                     true
5263                 } else if (requestUrlString.startsWith("tel:")) {  // Load the phone number in the dialer.
5264                     // Create a dial intent.
5265                     val dialIntent = Intent(Intent.ACTION_DIAL)
5266
5267                     // Add the phone number to the intent.
5268                     dialIntent.data = Uri.parse(requestUrlString)
5269
5270                     // Open the dialer in a new task instead of as part of Privacy Browser.
5271                     dialIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
5272
5273                     try {
5274                         // Make it so.
5275                         startActivity(dialIntent)
5276                     } catch (exception: ActivityNotFoundException) {
5277                         // Display a snackbar.
5278                         Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
5279                     }
5280
5281                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5282                     true
5283                 } else {  // Load a system chooser to select an app that can handle the URL.
5284                     // Create a generic intent to open an app.
5285                     val genericIntent = Intent(Intent.ACTION_VIEW)
5286
5287                     // Add the URL to the intent.
5288                     genericIntent.data = Uri.parse(requestUrlString)
5289
5290                     // List all apps that can handle the URL instead of just opening the first one.
5291                     genericIntent.addCategory(Intent.CATEGORY_BROWSABLE)
5292
5293                     // Open the app in a new task instead of as part of Privacy Browser.
5294                     genericIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
5295
5296                     try {
5297                         // Make it so.
5298                         startActivity(genericIntent)
5299                     } catch (exception: ActivityNotFoundException) {
5300                         // Display a snackbar.
5301                         Snackbar.make(nestedScrollWebView, getString(R.string.unrecognized_url, requestUrlString), Snackbar.LENGTH_SHORT).show()
5302                     }
5303
5304                     // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5305                     true
5306                 }
5307             }
5308
5309             // Check requests against the block lists.
5310             override fun shouldInterceptRequest(view: WebView, webResourceRequest: WebResourceRequest): WebResourceResponse? {
5311                 // Get the URL.
5312                 val requestUrlString = webResourceRequest.url.toString()
5313
5314                 // Check to see if the resource request is for the main URL.
5315                 if (requestUrlString == nestedScrollWebView.currentUrl) {
5316                     // `return null` loads the resource request, which should never be blocked if it is the main URL.
5317                     return null
5318                 }
5319
5320                 // 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.
5321                 while (ultraPrivacy == null) {
5322                     try {
5323                         // Check to see if the filter lists have been populated after 100 ms.
5324                         Thread.sleep(100)
5325                     } catch (exception: InterruptedException) {
5326                         // Do nothing.
5327                     }
5328                 }
5329
5330                 // Create an empty web resource response to be used if the resource request is blocked.
5331                 val emptyWebResourceResponse = WebResourceResponse("text/plain", "utf8", ByteArrayInputStream("".toByteArray()))
5332
5333                 // Initialize the variables.
5334                 var allowListResultStringArray: Array<String>? = null
5335                 var isThirdPartyRequest = false
5336
5337                 // Get the current URL.  `.getUrl()` throws an error because operations on the WebView cannot be made from this thread.
5338                 var currentBaseDomain = nestedScrollWebView.currentDomainName
5339
5340                 // Store a copy of the current domain for use in later requests.
5341                 val currentDomain = currentBaseDomain
5342
5343                 // Get the request host name.
5344                 var requestBaseDomain = webResourceRequest.url.host
5345
5346                 // Only check for third-party requests if the current base domain is not empty and the request domain is not null.
5347                 if (currentBaseDomain.isNotEmpty() && (requestBaseDomain != null)) {
5348                     // Determine the current base domain.
5349                     while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) {  // There is at least one subdomain.
5350                         // Remove the first subdomain.
5351                         currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1)
5352                     }
5353
5354                     // Determine the request base domain.
5355                     while (requestBaseDomain!!.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) {  // There is at least one subdomain.
5356                         // Remove the first subdomain.
5357                         requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1)
5358                     }
5359
5360                     // Update the third party request tracker.
5361                     isThirdPartyRequest = currentBaseDomain != requestBaseDomain
5362                 }
5363
5364                 // Get the current WebView page position.
5365                 val webViewPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
5366
5367                 // Determine if the WebView is currently displayed.
5368                 val webViewDisplayed = (webViewPagePosition == tabLayout.selectedTabPosition)
5369
5370                 // Block third-party requests if enabled.
5371                 if (isThirdPartyRequest && nestedScrollWebView.blockAllThirdPartyRequests) {
5372                     // Add the result to the resource requests.
5373                     nestedScrollWebView.addResourceRequest(arrayOf(REQUEST_THIRD_PARTY, requestUrlString))
5374
5375                     // Increment the blocked requests counters.
5376                     nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5377                     nestedScrollWebView.incrementRequestsCount(THIRD_PARTY_REQUESTS)
5378
5379                     // Update the titles of the filter lists menu items if the WebView is currently displayed.
5380                     if (webViewDisplayed) {
5381                         // Updating the UI must be run from the UI thread.
5382                         runOnUiThread {
5383                             // Update the menu item titles.
5384                             navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5385
5386                             // Update the options menu if it has been populated.
5387                             if (optionsMenu != null) {
5388                                 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5389                                 optionsBlockAllThirdPartyRequestsMenuItem.title =
5390                                     nestedScrollWebView.getRequestsCount(THIRD_PARTY_REQUESTS).toString() + " - " + getString(R.string.block_all_third_party_requests)
5391                             }
5392                         }
5393                     }
5394
5395                     // The resource request was blocked.  Return an empty web resource response.
5396                     return emptyWebResourceResponse
5397                 }
5398
5399                 // Check UltraList if it is enabled.
5400                 if (nestedScrollWebView.ultraListEnabled) {
5401                     // Check the URL against UltraList.
5402                     val ultraListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, ultraList)
5403
5404                     // Process the UltraList results.
5405                     if (ultraListResults[0] == REQUEST_BLOCKED) {  // The resource request matched UltraList's block list.
5406                         // Add the result to the resource requests.
5407                         nestedScrollWebView.addResourceRequest(arrayOf(ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]))
5408
5409                         // Increment the blocked requests counters.
5410                         nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5411                         nestedScrollWebView.incrementRequestsCount(com.stoutner.privacybrowser.views.ULTRALIST)
5412
5413                         // Update the titles of the filter lists menu items if the WebView is currently displayed.
5414                         if (webViewDisplayed) {
5415                             // Updating the UI must be run from the UI thread.
5416                             runOnUiThread {
5417                                 // Update the menu item titles.
5418                                 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5419
5420                                 // Update the options menu if it has been populated.
5421                                 if (optionsMenu != null) {
5422                                     optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5423                                     optionsUltraListMenuItem.title = nestedScrollWebView.getRequestsCount(com.stoutner.privacybrowser.views.ULTRALIST).toString() + " - " + getString(R.string.ultralist)
5424                                 }
5425                             }
5426                         }
5427
5428                         // The resource request was blocked.  Return an empty web resource response.
5429                         return emptyWebResourceResponse
5430                     } else if (ultraListResults[0] == REQUEST_ALLOWED) {  // The resource request matched UltraList's allow list.
5431                         // Add an allow list entry to the resource requests array.
5432                         nestedScrollWebView.addResourceRequest(arrayOf(ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]))
5433
5434                         // The resource request has been allowed by UltraList.  `return null` loads the requested resource.
5435                         return null
5436                     }
5437                 }
5438
5439                 // Check UltraPrivacy if it is enabled.
5440                 if (nestedScrollWebView.ultraPrivacyEnabled) {
5441                     // Check the URL against UltraPrivacy.
5442                     val ultraPrivacyResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, ultraPrivacy!!)
5443
5444                     // Process the UltraPrivacy results.
5445                     if (ultraPrivacyResults[0] == REQUEST_BLOCKED) {  // The resource request matched UltraPrivacy's block list.
5446                         // Add the result to the resource requests.
5447                         nestedScrollWebView.addResourceRequest(arrayOf(ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5448                             ultraPrivacyResults[5]))
5449
5450                         // Increment the blocked requests counters.
5451                         nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5452                         nestedScrollWebView.incrementRequestsCount(ULTRAPRIVACY)
5453
5454                         // Update the titles of the filter lists menu items if the WebView is currently displayed.
5455                         if (webViewDisplayed) {
5456                             // Updating the UI must be run from the UI thread.
5457                             runOnUiThread {
5458                                 // Update the menu item titles.
5459                                 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5460
5461                                 // Update the options menu if it has been populated.
5462                                 if (optionsMenu != null) {
5463                                     optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5464                                     optionsUltraPrivacyMenuItem.title = nestedScrollWebView.getRequestsCount(ULTRAPRIVACY).toString() + " - " + getString(R.string.ultraprivacy)
5465                                 }
5466                             }
5467                         }
5468
5469                         // The resource request was blocked.  Return an empty web resource response.
5470                         return emptyWebResourceResponse
5471                     } else if (ultraPrivacyResults[0] == REQUEST_ALLOWED) {  // The resource request matched UltraPrivacy's allow list.
5472                         // Add an allow list entry to the resource requests array.
5473                         nestedScrollWebView.addResourceRequest(arrayOf(ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5474                             ultraPrivacyResults[5]))
5475
5476                         // The resource request has been allowed by UltraPrivacy.  `return null` loads the requested resource.
5477                         return null
5478                     }
5479                 }
5480
5481                 // Check EasyList if it is enabled.
5482                 if (nestedScrollWebView.easyListEnabled) {
5483                     // Check the URL against EasyList.
5484                     val easyListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, easyList)
5485
5486                     // Process the EasyList results.
5487                     if (easyListResults[0] == REQUEST_BLOCKED) {  // The resource request matched EasyList's block list.
5488                         // Add the result to the resource requests.
5489                         nestedScrollWebView.addResourceRequest(arrayOf(easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]))
5490
5491                         // Increment the blocked requests counters.
5492                         nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5493                         nestedScrollWebView.incrementRequestsCount(EASYLIST)
5494
5495                         // Update the titles of the filter lists menu items if the WebView is currently displayed.
5496                         if (webViewDisplayed) {
5497                             // Updating the UI must be run from the UI thread.
5498                             runOnUiThread {
5499                                 // Update the menu item titles.
5500                                 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5501
5502                                 // Update the options menu if it has been populated.
5503                                 if (optionsMenu != null) {
5504                                     optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5505                                     optionsEasyListMenuItem.title = nestedScrollWebView.getRequestsCount(EASYLIST).toString() + " - " + getString(R.string.easylist)
5506                                 }
5507                             }
5508                         }
5509
5510                         // The resource request was blocked.  Return an empty web resource response.
5511                         return emptyWebResourceResponse
5512                     } else if (easyListResults[0] == REQUEST_ALLOWED) {  // The resource request matched EasyList's allow list.
5513                         // Update the allow list result string array tracker.
5514                         allowListResultStringArray = arrayOf(easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5])
5515                     }
5516                 }
5517
5518                 // Check EasyPrivacy if it is enabled.
5519                 if (nestedScrollWebView.easyPrivacyEnabled) {
5520                     // Check the URL against EasyPrivacy.
5521                     val easyPrivacyResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, easyPrivacy)
5522
5523                     // Process the EasyPrivacy results.
5524                     if (easyPrivacyResults[0] == REQUEST_BLOCKED) {  // The resource request matched EasyPrivacy's block list.
5525                         // Add the result to the resource requests.
5526                         nestedScrollWebView.addResourceRequest(arrayOf(easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5]))
5527
5528                         // Increment the blocked requests counters.
5529                         nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5530                         nestedScrollWebView.incrementRequestsCount(EASYPRIVACY)
5531
5532                         // Update the titles of the filter lists menu items if the WebView is currently displayed.
5533                         if (webViewDisplayed) {
5534                             // Updating the UI must be run from the UI thread.
5535                             runOnUiThread {
5536                                 // Update the menu item titles.
5537                                 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5538
5539                                 // Update the options menu if it has been populated.
5540                                 if (optionsMenu != null) {
5541                                     optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5542                                     optionsEasyPrivacyMenuItem.title = nestedScrollWebView.getRequestsCount(EASYPRIVACY).toString() + " - " + getString(R.string.easyprivacy)
5543                                 }
5544                             }
5545                         }
5546
5547                         // The resource request was blocked.  Return an empty web resource response.
5548                         return emptyWebResourceResponse
5549                     } else if (easyPrivacyResults[0] == REQUEST_ALLOWED) {  // The resource request matched EasyPrivacy's allow list.
5550                         // Update the allow list result string array tracker.
5551                         allowListResultStringArray = arrayOf(easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5])
5552                     }
5553                 }
5554
5555                 // Check Fanboy’s Annoyance List if it is enabled.
5556                 if (nestedScrollWebView.fanboysAnnoyanceListEnabled) {
5557                     // Check the URL against Fanboy's Annoyance List.
5558                     val fanboysAnnoyanceListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, fanboysAnnoyanceList)
5559
5560                     // Process the Fanboy's Annoyance List results.
5561                     if (fanboysAnnoyanceListResults[0] == REQUEST_BLOCKED) {  // The resource request matched Fanboy's Annoyance List's block list.
5562                         // Add the result to the resource requests.
5563                         nestedScrollWebView.addResourceRequest(arrayOf(fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5564                             fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]))
5565
5566                         // Increment the blocked requests counters.
5567                         nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5568                         nestedScrollWebView.incrementRequestsCount(FANBOYS_ANNOYANCE_LIST)
5569
5570                         // Update the titles of the filter lists menu items if the WebView is currently displayed.
5571                         if (webViewDisplayed) {
5572                             // Updating the UI must be run from the UI thread.
5573                             runOnUiThread {
5574                                 // Update the menu item titles.
5575                                 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5576
5577                                 // Update the options menu if it has been populated.
5578                                 if (optionsMenu != null) {
5579                                     optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5580                                     optionsFanboysAnnoyanceListMenuItem.title = nestedScrollWebView.getRequestsCount(FANBOYS_ANNOYANCE_LIST).toString() + " - " + getString(R.string.fanboys_annoyance_list)
5581                                 }
5582                             }
5583                         }
5584
5585                         // The resource request was blocked.  Return an empty web resource response.
5586                         return emptyWebResourceResponse
5587                     } else if (fanboysAnnoyanceListResults[0] == REQUEST_ALLOWED) {  // The resource request matched Fanboy's Annoyance List's allow list.
5588                         // Update the allow list result string array tracker.
5589                         allowListResultStringArray = arrayOf(fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5590                             fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5])
5591                     }
5592                 } else if (nestedScrollWebView.fanboysSocialBlockingListEnabled) {  // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
5593                     // Check the URL against Fanboy's Annoyance List.
5594                     val fanboysSocialListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, fanboysSocialList)
5595
5596                     // Process the Fanboy's Social Blocking List results.
5597                     if (fanboysSocialListResults[0] == REQUEST_BLOCKED) {  // The resource request matched Fanboy's Social Blocking List's block list.
5598                         // Add the result to the resource requests.
5599                         nestedScrollWebView.addResourceRequest(arrayOf(fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5600                             fanboysSocialListResults[4], fanboysSocialListResults[5]))
5601
5602                         // Increment the blocked requests counters.
5603                         nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5604                         nestedScrollWebView.incrementRequestsCount(FANBOYS_SOCIAL_BLOCKING_LIST)
5605
5606                         // Update the titles of the filter lists menu items if the WebView is currently displayed.
5607                         if (webViewDisplayed) {
5608                             // Updating the UI must be run from the UI thread.
5609                             runOnUiThread {
5610                                 // Update the menu item titles.
5611                                 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5612
5613                                 // Update the options menu if it has been populated.
5614                                 if (optionsMenu != null) {
5615                                     optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5616                                     optionsFanboysSocialBlockingListMenuItem.title =
5617                                         nestedScrollWebView.getRequestsCount(FANBOYS_SOCIAL_BLOCKING_LIST).toString() + " - " + getString(R.string.fanboys_social_blocking_list)
5618                                 }
5619                             }
5620                         }
5621
5622                         // The resource request was blocked.  Return an empty web resource response.
5623                         return emptyWebResourceResponse
5624                     } else if (fanboysSocialListResults[0] == REQUEST_ALLOWED) {  // The resource request matched Fanboy's Social Blocking List's allow list.
5625                         // Update the allow list result string array tracker.
5626                         allowListResultStringArray = arrayOf(fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3], fanboysSocialListResults[4],
5627                             fanboysSocialListResults[5])
5628                     }
5629                 }
5630
5631                 // Add the request to the log because it hasn't been processed by any of the previous checks.
5632                 if (allowListResultStringArray != null) {  // The request was processed by an allow list.
5633                     nestedScrollWebView.addResourceRequest(allowListResultStringArray)
5634                 } else {  // The request didn't match any filter list entry.  Log it as a default request.
5635                     nestedScrollWebView.addResourceRequest(arrayOf(REQUEST_DEFAULT, requestUrlString))
5636                 }
5637
5638                 // The resource request has not been blocked.  `return null` loads the requested resource.
5639                 return null
5640             }
5641
5642             // Handle HTTP authentication requests.
5643             override fun onReceivedHttpAuthRequest(view: WebView, handler: HttpAuthHandler, host: String, realm: String) {
5644                 // Store the handler.
5645                 nestedScrollWebView.httpAuthHandler = handler
5646
5647                 // Instantiate an HTTP authentication dialog.
5648                 val httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm, nestedScrollWebView.webViewFragmentId)
5649
5650                 // Show the HTTP authentication dialog.
5651                 httpAuthenticationDialogFragment.show(supportFragmentManager, getString(R.string.http_authentication))
5652             }
5653
5654             override fun onPageStarted(webView: WebView, url: String, favicon: Bitmap?) {
5655                 // Get the app bar layout height.  This can't be done in `applyAppSettings()` because the app bar is not yet populated there.
5656                 // 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.
5657                 if (appBarLayout.height > 0)
5658                     appBarHeight = appBarLayout.height
5659
5660                 // Set the padding and layout settings according to the position of the app bar.
5661                 if (bottomAppBar) {  // The app bar is on the bottom.
5662                     // Adjust the UI.
5663                     if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) {  // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
5664                         // Reset the WebView padding to fill the available space.
5665                         swipeRefreshLayout.setPadding(0, 0, 0, 0)
5666                     } else {  // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
5667                         // Move the WebView above the app bar layout.
5668                         swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
5669                     }
5670                 } else {  // The app bar is on the top.
5671                     // 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.
5672                     if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) {  // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
5673                         // No padding is needed because it will automatically be placed below the app bar layout due to the scrolling layout behavior.
5674                         swipeRefreshLayout.setPadding(0, 0, 0, 0)
5675
5676                         // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5677                         swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10, defaultProgressViewEndOffset)
5678                     } else {  // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
5679                         // The swipe refresh layout must be manually moved below the app bar layout.
5680                         swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0)
5681
5682                         // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5683                         swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight)
5684                     }
5685                 }
5686
5687                 // Reset the list of resource requests.
5688                 nestedScrollWebView.clearResourceRequests()
5689
5690                 // Reset the requests counters.
5691                 nestedScrollWebView.resetRequestsCounters()
5692
5693                 // Get the current page position.
5694                 val currentPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
5695
5696                 // Update the URL text bar if the page is currently selected and the URL edit text is not currently being edited.
5697                 if ((tabLayout.selectedTabPosition == currentPagePosition) && !urlEditText.hasFocus()) {
5698                     // Display the formatted URL text.  The nested scroll WebView current URL preserves any initial `view-source:`, and opposed to the method URL variable.
5699                     urlEditText.setText(nestedScrollWebView.currentUrl)
5700
5701                     // Highlight the URL syntax.
5702                     UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
5703
5704                     // Hide the keyboard.
5705                     inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.windowToken, 0)
5706                 }
5707
5708                 // Reset the list of host IP addresses.
5709                 nestedScrollWebView.currentIpAddresses = ""
5710
5711                 // Get a URI for the current URL.
5712                 val currentUri = Uri.parse(url)
5713
5714                 // Get the current domain name.
5715                 val currentDomainName = currentUri.host
5716
5717                 // Get the IP addresses for the current domain.
5718                 if (!currentDomainName.isNullOrEmpty())
5719                     GetHostIpAddressesCoroutine.checkPinnedMismatch(currentDomainName, nestedScrollWebView, supportFragmentManager, getString(R.string.pinned_mismatch))
5720
5721                 // 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.)
5722                 if ((optionsMenu != null) && (webView == currentWebView)) {
5723                     // Set the title.
5724                     optionsRefreshMenuItem.setTitle(R.string.stop)
5725
5726                     // Set the icon if it is displayed in the AppBar.
5727                     if (displayAdditionalAppBarIcons)
5728                         optionsRefreshMenuItem.setIcon(R.drawable.close_blue)
5729                 }
5730             }
5731
5732             override fun onPageFinished(webView: WebView, url: String) {
5733                 // Flush any cookies to persistent storage.  The cookie manager has become very lazy about flushing cookies in recent versions.
5734                 if (nestedScrollWebView.acceptCookies)
5735                     cookieManager.flush()
5736
5737                 // Update the Refresh menu item if the options menu has been created and the WebView is currently displayed.
5738                 if (optionsMenu != null && (webView == currentWebView)) {
5739                     // Reset the Refresh title.
5740                     optionsRefreshMenuItem.setTitle(R.string.refresh)
5741
5742                     // Reset the icon if it is displayed in the app bar.
5743                     if (displayAdditionalAppBarIcons)
5744                         optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled)
5745                 }
5746
5747                 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
5748                 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
5749                 val privateDataDirectoryString = applicationInfo.dataDir
5750
5751                 // Clear the cache, history, and logcat if Incognito Mode is enabled.
5752                 if (incognitoModeEnabled) {
5753                     // Clear the cache.  `true` includes disk files.
5754                     nestedScrollWebView.clearCache(true)
5755
5756                     // Clear the back/forward history.
5757                     nestedScrollWebView.clearHistory()
5758
5759                     // Manually delete cache folders.
5760                     try {
5761                         // Delete the main cache directory.
5762                         Runtime.getRuntime().exec("rm -rf $privateDataDirectoryString/cache")
5763                     } catch (exception: IOException) {
5764                         // Do nothing if an error is thrown.
5765                     }
5766
5767                     // Clear the logcat.
5768                     try {
5769                         // Clear the logcat.  `-c` clears the logcat.  `-b all` clears all the buffers (instead of just crash, main, and system).
5770                         Runtime.getRuntime().exec("logcat -b all -c")
5771                     } catch (exception: IOException) {
5772                         // Do nothing.
5773                     }
5774                 }
5775
5776                 // Clear the `Service Worker` directory.
5777                 try {
5778                     // A string array must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
5779                     Runtime.getRuntime().exec(arrayOf("rm", "-rf", "$privateDataDirectoryString/app_webview/Default/Service Worker/"))
5780                 } catch (exception: IOException) {
5781                     // Do nothing.
5782                 }
5783
5784                 // Get the current page position.
5785                 val currentPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
5786
5787                 // 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.
5788                 val currentUrl = nestedScrollWebView.url
5789
5790                 // Get the current tab.
5791                 val tab = tabLayout.getTabAt(currentPagePosition)
5792
5793                 // Update the URL text bar if the page is currently selected and the user is not currently typing in the URL edit text.
5794                 // Crash records show that, in some crazy way, it is possible for the current URL to be blank at this point.
5795                 // Probably some sort of race condition when Privacy Browser is being resumed.
5796                 if ((tabLayout.selectedTabPosition == currentPagePosition) && !urlEditText.hasFocus() && (currentUrl != null)) {
5797                     // Check to see if the URL is `about:blank`.
5798                     if (currentUrl == "about:blank") {  // The WebView is blank.
5799                         // Display the hint in the URL edit text.
5800                         urlEditText.setText("")
5801
5802                         // Request focus for the URL text box.
5803                         urlEditText.requestFocus()
5804
5805                         // Display the keyboard.
5806                         inputMethodManager.showSoftInput(urlEditText, 0)
5807
5808                         // Apply the domain settings.  This clears any settings from the previous domain.
5809                         applyDomainSettings(nestedScrollWebView, "", resetTab = true, reloadWebsite = false, loadUrl = false)
5810
5811                         // Only populate the title text view if the tab has been fully created.
5812                         if (tab != null) {
5813                             // Get the custom view from the tab.
5814                             val tabView = tab.customView!!
5815
5816                             // Get the title text view from the tab.
5817                             val tabTitleTextView = tabView.findViewById<TextView>(R.id.title_textview)
5818
5819                             // Set the title as the tab text.
5820                             tabTitleTextView.setText(R.string.new_tab)
5821                         }
5822                     } else {  // The WebView has loaded a webpage.
5823                         // Update the URL edit text if it is not currently being edited.
5824                         if (!urlEditText.hasFocus()) {
5825                             // 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.
5826                             val sanitizedUrl = sanitizeUrl(currentUrl)
5827
5828                             // Display the final URL.  Getting the URL from the WebView instead of using the one provided by `onPageFinished()` makes websites like YouTube function correctly.
5829                             urlEditText.setText(sanitizedUrl)
5830
5831                             // Highlight the URL syntax.
5832                             UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
5833                         }
5834
5835                         // Only populate the title text view if the tab has been fully created.
5836                         if (tab != null) {
5837                             // Get the custom view from the tab.
5838                             val tabView = tab.customView!!
5839
5840                             // Get the title text view from the tab.
5841                             val tabTitleTextView = tabView.findViewById<TextView>(R.id.title_textview)
5842
5843                             // Set the title as the tab text.  Sometimes `onReceivedTitle()` is not called, especially when navigating history.
5844                             tabTitleTextView.text = nestedScrollWebView.title
5845                         }
5846                     }
5847                 }
5848             }
5849
5850             // Handle SSL Certificate errors.  Suppress the lint warning that ignoring the error might be dangerous.
5851             @SuppressLint("WebViewClientOnReceivedSslError")
5852             override fun onReceivedSslError(view: WebView, handler: SslErrorHandler, error: SslError) {
5853                 // Get the current website SSL certificate.
5854                 val currentWebsiteSslCertificate = error.certificate
5855
5856                 // Extract the individual pieces of information from the current website SSL certificate.
5857                 val currentWebsiteIssuedToCName = currentWebsiteSslCertificate.issuedTo.cName
5858                 val currentWebsiteIssuedToOName = currentWebsiteSslCertificate.issuedTo.oName
5859                 val currentWebsiteIssuedToUName = currentWebsiteSslCertificate.issuedTo.uName
5860                 val currentWebsiteIssuedByCName = currentWebsiteSslCertificate.issuedBy.cName
5861                 val currentWebsiteIssuedByOName = currentWebsiteSslCertificate.issuedBy.oName
5862                 val currentWebsiteIssuedByUName = currentWebsiteSslCertificate.issuedBy.uName
5863                 val currentWebsiteSslStartDate = currentWebsiteSslCertificate.validNotBeforeDate
5864                 val currentWebsiteSslEndDate = currentWebsiteSslCertificate.validNotAfterDate
5865
5866                 // Get the pinned SSL certificate.
5867                 val (pinnedSslCertificateStringArray, pinnedSslCertificateDateArray) = nestedScrollWebView.getPinnedSslCertificate()
5868
5869                 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
5870                 if (nestedScrollWebView.hasPinnedSslCertificate() &&
5871                     (currentWebsiteIssuedToCName == pinnedSslCertificateStringArray[0]) &&
5872                     (currentWebsiteIssuedToOName == pinnedSslCertificateStringArray[1]) &&
5873                     (currentWebsiteIssuedToUName == pinnedSslCertificateStringArray[2]) &&
5874                     (currentWebsiteIssuedByCName == pinnedSslCertificateStringArray[3]) &&
5875                     (currentWebsiteIssuedByOName == pinnedSslCertificateStringArray[4]) &&
5876                     (currentWebsiteIssuedByUName == pinnedSslCertificateStringArray[5]) &&
5877                     (currentWebsiteSslStartDate == pinnedSslCertificateDateArray[0]) &&
5878                     (currentWebsiteSslEndDate == pinnedSslCertificateDateArray[1])) {
5879
5880                     // An SSL certificate is pinned and matches the current domain certificate.  Proceed to the website without displaying an error.
5881                     handler.proceed()
5882                 } else {  // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
5883                     // Store the SSL error handler.
5884                     nestedScrollWebView.sslErrorHandler = handler
5885
5886                     // Instantiate an SSL certificate error alert dialog.
5887                     val sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error, nestedScrollWebView.webViewFragmentId)
5888
5889                     // 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.
5890                     try {
5891                         // Show the SSL certificate error dialog.
5892                         sslCertificateErrorDialogFragment.show(supportFragmentManager, getString(R.string.ssl_certificate_error))
5893                     } catch (exception: Exception) {
5894                         // Add the dialog to the pending dialog array list.  It will be displayed in `onStart()`.
5895                         pendingDialogsArrayList.add(PendingDialogDataClass(sslCertificateErrorDialogFragment, getString(R.string.ssl_certificate_error)))
5896                     }
5897                 }
5898             }
5899         }
5900
5901         // Check to see if the state is being restored.
5902         if (restoringState) {  // The state is being restored.
5903             // Resume the nested scroll WebView JavaScript timers.
5904             nestedScrollWebView.resumeTimers()
5905         } else if (pagePosition == 0) {  // The first page is being loaded.
5906             // Set this nested scroll WebView as the current WebView.
5907             currentWebView = nestedScrollWebView
5908
5909             // Get the intent that started the app.
5910             val launchingIntent = intent
5911
5912             // Reset the intent.  This prevents a duplicate tab from being created on restart.
5913             intent = Intent()
5914
5915             // Get the information from the intent.
5916             val launchingIntentAction = launchingIntent.action
5917             val launchingIntentUriData = launchingIntent.data
5918             val launchingIntentStringExtra = launchingIntent.getStringExtra(Intent.EXTRA_TEXT)
5919
5920             // Parse the launching intent URL.  Suppress the suggestions of using elvis expressions as they make the logic very difficult to follow.
5921             @Suppress("IfThenToElvis") val urlToLoadString = if ((launchingIntentAction != null) && (launchingIntentAction == Intent.ACTION_WEB_SEARCH)) {  // The intent contains a search string.
5922                 // Sanitize the search input and convert it to a search.
5923                 val encodedSearchString = try {
5924                     URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8")
5925                 } catch (exception: UnsupportedEncodingException) {
5926                     ""
5927                 }
5928
5929                 // Add the search URL to the encodedSearchString
5930                 searchURL + encodedSearchString
5931             } else if (launchingIntentUriData != null) {  // The launching intent contains a URL formatted as a URI.
5932                 // Get the URL from the URI.
5933                 launchingIntentUriData.toString()
5934             } else if (launchingIntentStringExtra != null) {  // The launching intent contains text that might be a URL.
5935                 // Get the URL from the string extra.
5936                 launchingIntentStringExtra
5937             } else if (urlString != "") {  // The activity has been restarted.
5938                 // Load the saved URL.
5939                 urlString
5940             } else {  // The is no saved URL and there is no URL in the intent.
5941                 // Load the homepage.
5942                 sharedPreferences.getString("homepage", getString(R.string.homepage_default_value))
5943             }
5944
5945             // Load the website if not waiting for the proxy.
5946             if (waitingForProxy) {  // Store the URL to be loaded in the Nested Scroll WebView.
5947                 nestedScrollWebView.waitingForProxyUrlString = urlToLoadString!!
5948             } else {  // Load the URL.
5949                 loadUrl(nestedScrollWebView, urlToLoadString!!)
5950             }
5951         } else {  // This is not the first tab.
5952             // Load the URL.
5953             loadUrl(nestedScrollWebView, urlString)
5954
5955             // Set the focus and display the keyboard if the URL is blank.
5956             if (urlString == "") {
5957                 // Request focus for the URL text box.
5958                 urlEditText.requestFocus()
5959
5960                 // Display the keyboard once the tab layout has settled.
5961                 tabLayout.post {
5962                     inputMethodManager.showSoftInput(urlEditText, 0)
5963                 }
5964             }
5965         }
5966     }
5967
5968     private fun loadBookmarksFolder() {
5969         // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
5970         bookmarksCursor = bookmarksDatabaseHelper!!.getBookmarksByDisplayOrder(currentBookmarksFolderId)
5971
5972         // Populate the bookmarks cursor adapter.
5973         bookmarksCursorAdapter = object : CursorAdapter(this, bookmarksCursor, false) {
5974             override fun newView(context: Context, cursor: Cursor, parent: ViewGroup): View {
5975                 // Inflate the individual item layout.
5976                 return layoutInflater.inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false)
5977             }
5978
5979             override fun bindView(view: View, context: Context, cursor: Cursor) {
5980                 // Get handles for the views.
5981                 val bookmarkFavoriteIcon = view.findViewById<ImageView>(R.id.bookmark_favorite_icon)
5982                 val bookmarkNameTextView = view.findViewById<TextView>(R.id.bookmark_name)
5983
5984                 // Get the favorite icon byte array from the cursor.
5985                 val favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndexOrThrow(FAVORITE_ICON))
5986
5987                 // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
5988                 val favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.size)
5989
5990                 // Display the bitmap in the bookmark favorite icon.
5991                 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap)
5992
5993                 // Display the bookmark name from the cursor in the bookmark name text view.
5994                 bookmarkNameTextView.text = cursor.getString(cursor.getColumnIndexOrThrow(BOOKMARK_NAME))
5995
5996                 // Make the font bold for folders.
5997                 if (cursor.getInt(cursor.getColumnIndexOrThrow(IS_FOLDER)) == 1)
5998                     bookmarkNameTextView.typeface = Typeface.DEFAULT_BOLD
5999                 else  // Reset the font to default for normal bookmarks.
6000                     bookmarkNameTextView.typeface = Typeface.DEFAULT
6001             }
6002         }
6003
6004         // Populate the list view with the adapter.
6005         bookmarksListView.adapter = bookmarksCursorAdapter
6006
6007         // Set the bookmarks drawer title.
6008         if (currentBookmarksFolderId == HOME_FOLDER_ID)  // The current bookmarks folder is the home folder.
6009             bookmarksTitleTextView.setText(R.string.bookmarks)
6010         else
6011             bookmarksTitleTextView.text = bookmarksDatabaseHelper!!.getFolderName(currentBookmarksFolderId)
6012     }
6013
6014     private fun loadUrl(nestedScrollWebView: NestedScrollWebView, url: String) {
6015         // Sanitize the URL.
6016         val urlString = sanitizeUrl(url)
6017
6018         // Apply the domain settings and load the URL.
6019         applyDomainSettings(nestedScrollWebView, urlString, resetTab = true, reloadWebsite = false, loadUrl = true)
6020     }
6021
6022     private fun loadUrlFromTextBox() {
6023         // 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.
6024         var unformattedUrlString = urlEditText.text.toString().trim { it <= ' ' }
6025
6026         // Create the formatted URL string.
6027         var urlString = ""
6028
6029         // Check to see if the unformatted URL string is a valid URL.  Otherwise, convert it into a search.
6030         if (unformattedUrlString.startsWith("content://") || unformattedUrlString.startsWith("view-source:")) {  // This is a content or source URL.
6031             // Load the entire content URL.
6032             urlString = unformattedUrlString
6033         } else if (Patterns.WEB_URL.matcher(unformattedUrlString).matches() || unformattedUrlString.startsWith("http://") || unformattedUrlString.startsWith("https://") ||
6034             unformattedUrlString.startsWith("file://")) {  // This is a standard URL.
6035
6036             // Add `https://` at the beginning if there is no protocol.  Otherwise the app will segfault.
6037             if (!unformattedUrlString.startsWith("http") && !unformattedUrlString.startsWith("file://"))
6038                 unformattedUrlString = "https://$unformattedUrlString"
6039
6040             // Initialize the unformatted URL.
6041             var unformattedUrl: URL? = null
6042
6043             // Convert the unformatted URL string to a URL.
6044             try {
6045                 unformattedUrl = URL(unformattedUrlString)
6046             } catch (exception: MalformedURLException) {
6047                 exception.printStackTrace()
6048             }
6049
6050             // Get the components of the URL.
6051             val scheme = unformattedUrl?.protocol
6052             val authority = unformattedUrl?.authority
6053             val path = unformattedUrl?.path
6054             val query = unformattedUrl?.query
6055             val fragment = unformattedUrl?.ref
6056
6057             // Create a URI.
6058             val uri = Uri.Builder()
6059
6060             // Build the URI from the components of the URL.
6061             uri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment)
6062
6063             // Decode the URI as a UTF-8 string in.
6064             try {
6065                 urlString = URLDecoder.decode(uri.build().toString(), "UTF-8")
6066             } catch (exception: UnsupportedEncodingException) {
6067                 // Do nothing.  The formatted URL string will remain blank.
6068             }
6069         } else if (unformattedUrlString.isNotEmpty()) {  // This is not a URL, but rather a search string.
6070             // Sanitize the search input.
6071             val encodedSearchString = try {
6072                 URLEncoder.encode(unformattedUrlString, "UTF-8")
6073             } catch (exception: UnsupportedEncodingException) {
6074                 ""
6075             }
6076
6077             // Add the base search URL.
6078             urlString = searchURL + encodedSearchString
6079         }
6080
6081         // 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.
6082         urlEditText.clearFocus()
6083
6084         // Make it so.
6085         loadUrl(currentWebView!!, urlString)
6086     }
6087
6088     override fun navigateHistory(url: String, steps: Int) {
6089         // Apply the domain settings.
6090         applyDomainSettings(currentWebView!!, url, resetTab = false, reloadWebsite = false, loadUrl = false)
6091
6092         // Load the history entry.
6093         currentWebView!!.goBackOrForward(steps)
6094
6095         // Update the URL edit text after a delay.
6096         updateUrlEditTextAfterDelay()
6097     }
6098
6099     override fun openFile(dialogFragment: DialogFragment) {
6100         // Get the dialog.
6101         val dialog = dialogFragment.dialog!!
6102
6103         // Get handles for the views.
6104         val fileNameEditText = dialog.findViewById<EditText>(R.id.file_name_edittext)
6105         val mhtCheckBox = dialog.findViewById<CheckBox>(R.id.mht_checkbox)
6106
6107         // Get the file path string.
6108         val openFilePath = fileNameEditText.text.toString()
6109
6110         // Apply the domain settings.  This resets the favorite icon and removes any domain settings.
6111         applyDomainSettings(currentWebView!!, openFilePath, resetTab = true, reloadWebsite = false, loadUrl = false)
6112
6113         // Open the file according to the type.
6114         if (mhtCheckBox.isChecked) {  // Force opening of an MHT file.
6115             try {
6116                 // Get the MHT file input stream.
6117                 val mhtFileInputStream = contentResolver.openInputStream(Uri.parse(openFilePath))
6118
6119                 // Create a temporary MHT file.
6120                 val temporaryMhtFile = File.createTempFile(TEMPORARY_MHT_FILE, ".mht", cacheDir)
6121
6122                 // Get a file output stream for the temporary MHT file.
6123                 val temporaryMhtFileOutputStream = FileOutputStream(temporaryMhtFile)
6124
6125                 // Create a transfer byte array.
6126                 val transferByteArray = ByteArray(1024)
6127
6128                 // Create an integer to track the number of bytes read.
6129                 var bytesRead: Int
6130
6131                 // Copy the temporary MHT file input stream to the MHT output stream.
6132                 while (mhtFileInputStream!!.read(transferByteArray).also { bytesRead = it } > 0)
6133                     temporaryMhtFileOutputStream.write(transferByteArray, 0, bytesRead)
6134
6135                 // Flush the temporary MHT file output stream.
6136                 temporaryMhtFileOutputStream.flush()
6137
6138                 // Close the streams.
6139                 temporaryMhtFileOutputStream.close()
6140                 mhtFileInputStream.close()
6141
6142                 // Load the temporary MHT file.
6143                 currentWebView!!.loadUrl(temporaryMhtFile.toString())
6144             } catch (exception: Exception) {
6145                 // Display a snackbar.
6146                 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
6147             }
6148         } else {  // Let the WebView handle opening of the file.
6149             // Open the file.
6150             currentWebView!!.loadUrl(openFilePath)
6151         }
6152     }
6153     // The view parameter cannot be removed because it is called from the layout onClick.
6154     fun openNavigationDrawer(@Suppress("UNUSED_PARAMETER")view: View) {
6155         // Open the navigation drawer.
6156         drawerLayout.openDrawer(GravityCompat.START)
6157     }
6158
6159     private fun openWithApp(url: String) {
6160         // Create an open with app intent with `ACTION_VIEW`.
6161         val openWithAppIntent = Intent(Intent.ACTION_VIEW)
6162
6163         // Set the URI but not the MIME type.  This should open all available apps.
6164         openWithAppIntent.data = Uri.parse(url)
6165
6166         // Flag the intent to open in a new task.
6167         openWithAppIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
6168
6169         // Try the intent.
6170         try {
6171             // Show the chooser.
6172             startActivity(openWithAppIntent)
6173         } catch (exception: ActivityNotFoundException) {  // There are no apps available to open the URL.
6174             // Show a snackbar with the error.
6175             Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
6176         }
6177     }
6178
6179     private fun openWithBrowser(url: String) {
6180
6181         // Create an open with browser intent with `ACTION_VIEW`.
6182         val openWithBrowserIntent = Intent(Intent.ACTION_VIEW)
6183
6184         // Set the URI and the MIME type.  `"text/html"` should load browser options.
6185         openWithBrowserIntent.setDataAndType(Uri.parse(url), "text/html")
6186
6187         // Flag the intent to open in a new task.
6188         openWithBrowserIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
6189
6190         // Try the intent.
6191         try {
6192             // Show the chooser.
6193             startActivity(openWithBrowserIntent)
6194         } catch (exception: ActivityNotFoundException) {  // There are no browsers available to open the URL.
6195             // Show a snackbar with the error.
6196             Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
6197         }
6198     }
6199
6200     override fun pinnedErrorGoBack() {
6201         // Get the current web back forward list.
6202         val webBackForwardList = currentWebView!!.copyBackForwardList()
6203
6204         // Get the previous entry URL.
6205         val previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex - 1).url
6206
6207         // Apply the domain settings.
6208         applyDomainSettings(currentWebView!!, previousUrl, resetTab = false, reloadWebsite = false, loadUrl = false)
6209
6210         // Go back.
6211         currentWebView!!.goBack()
6212
6213         // Update the URL edit text after a delay.
6214         updateUrlEditTextAfterDelay()
6215     }
6216
6217     private fun sanitizeUrl(urlString: String): String {
6218         // Initialize a sanitized URL string.
6219         var sanitizedUrlString = urlString
6220
6221         // Sanitize tracking queries.
6222         if (sanitizeTrackingQueries)
6223             sanitizedUrlString = SanitizeUrlHelper.sanitizeTrackingQueries(sanitizedUrlString)
6224
6225         // Sanitize AMP redirects.
6226         if (sanitizeAmpRedirects)
6227             sanitizedUrlString = SanitizeUrlHelper.sanitizeAmpRedirects(sanitizedUrlString)
6228
6229         // Return the sanitized URL string.
6230         return sanitizedUrlString
6231     }
6232
6233     override fun saveUrl(originalUrlString: String, fileNameString: String, dialogFragment: DialogFragment) {
6234         // Store the URL.  This will be used in the save URL activity result launcher.
6235         saveUrlString = if (originalUrlString.startsWith("data:")) {
6236             // Save the original URL.
6237             originalUrlString
6238         } else {
6239             // Get the dialog.
6240             val dialog = dialogFragment.dialog!!
6241
6242             // Get a handle for the dialog URL edit text.
6243             val dialogUrlEditText = dialog.findViewById<EditText>(R.id.url_edittext)
6244
6245             // Get the URL from the edit text, which may have been modified.
6246             dialogUrlEditText.text.toString()
6247         }
6248
6249         // Open the file picker.
6250         saveUrlActivityResultLauncher.launch(fileNameString)
6251     }
6252
6253     private fun setCurrentWebView(pageNumber: Int) {
6254         // Stop the swipe to refresh indicator if it is running
6255         swipeRefreshLayout.isRefreshing = false
6256
6257         // Try to set the current WebView.  This will fail if the WebView has not yet been populated.
6258         try {
6259             // Get the WebView tab fragment.
6260             val webViewTabFragment = webViewStateAdapter!!.getPageFragment(pageNumber)
6261
6262             // Get the fragment view.
6263             val webViewFragmentView = webViewTabFragment.view
6264
6265             // Store the current WebView.
6266             currentWebView = webViewFragmentView!!.findViewById(R.id.nestedscroll_webview)
6267
6268             // Update the status of swipe to refresh.
6269             if (currentWebView!!.swipeToRefresh) {  // Swipe to refresh is enabled.
6270                 // Enable the swipe refresh layout if the WebView is scrolled all the way to the top.  It is updated every time the scroll changes.
6271                 swipeRefreshLayout.isEnabled = (currentWebView!!.scrollY == 0)
6272             } else {  // Swipe to refresh is disabled.
6273                 // Disable the swipe refresh layout.
6274                 swipeRefreshLayout.isEnabled = false
6275             }
6276
6277             // Set the cookie status.
6278             cookieManager.setAcceptCookie(currentWebView!!.acceptCookies)
6279
6280             // Update the privacy icons.  `true` redraws the icons in the app bar.
6281             updatePrivacyIcons(true)
6282
6283             // Get a handle for the input method manager.
6284             val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
6285
6286             // Get the current URL.
6287             val urlString = currentWebView!!.url
6288
6289             // Update the URL edit text if not loading a new intent.  Otherwise, this will be handled by `onPageStarted()` (if called) and `onPageFinished()`.
6290             if (!loadingNewIntent) {  // A new intent is not being loaded.
6291                 if ((urlString == null) || (urlString == "about:blank")) {  // The WebView is blank.
6292                     // Display the hint in the URL edit text.
6293                     urlEditText.setText("")
6294
6295                     // Request focus for the URL text box.
6296                     urlEditText.requestFocus()
6297
6298                     // Display the keyboard.
6299                     inputMethodManager.showSoftInput(urlEditText, 0)
6300                 } else {  // The WebView has a loaded URL.
6301                     // Clear the focus from the URL text box.
6302                     urlEditText.clearFocus()
6303
6304                     // Hide the soft keyboard.
6305                     inputMethodManager.hideSoftInputFromWindow(currentWebView!!.windowToken, 0)
6306
6307                     // Display the current URL in the URL text box.
6308                     urlEditText.setText(urlString)
6309
6310                     // Highlight the URL syntax.
6311                     UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
6312                 }
6313             } else {  // A new intent is being loaded.
6314                 // Reset the loading new intent flag.
6315                 loadingNewIntent = false
6316             }
6317
6318             // Set the background to indicate the domain settings status.
6319             if (currentWebView!!.domainSettingsApplied) {
6320                 // Set a background on the URL relative layout to indicate that custom domain settings are being used.
6321                 urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.drawable.domain_settings_url_background)
6322             } else {
6323                 // Remove any background on the URL relative layout.
6324                 urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.color.transparent)
6325             }
6326         }  catch (exception: Exception) {  //  Try again in 10 milliseconds if the WebView has not yet been populated.
6327             // Create a handler to set the current WebView.
6328             val setCurrentWebViewHandler = Handler(Looper.getMainLooper())
6329
6330             // Create a runnable to set the current WebView.
6331             val setCurrentWebWebRunnable = Runnable {
6332                 // Set the current WebView.
6333                 setCurrentWebView(pageNumber)
6334             }
6335
6336             // Try setting the current WebView again after 10 milliseconds.
6337             setCurrentWebViewHandler.postDelayed(setCurrentWebWebRunnable, 10)
6338         }
6339     }
6340
6341     // The view parameter cannot be removed because it is called from the layout onClick.
6342     fun toggleBookmarksDrawerPinned(@Suppress("UNUSED_PARAMETER")view: View?) {
6343         // Toggle the bookmarks drawer pinned tracker.
6344         bookmarksDrawerPinned = !bookmarksDrawerPinned
6345
6346         // Update the bookmarks drawer pinned image view.
6347         updateBookmarksDrawerPinnedImageView()
6348     }
6349
6350     private fun updateBookmarksDrawerPinnedImageView() {
6351         // Set the current icon.
6352         if (bookmarksDrawerPinned)
6353             bookmarksDrawerPinnedImageView.setImageResource(R.drawable.pin_selected)
6354         else
6355             bookmarksDrawerPinnedImageView.setImageResource(R.drawable.pin)
6356     }
6357
6358     private fun updateDomainsSettingsSet() {
6359         // Reset the domains settings set.
6360         domainsSettingsSet = HashSet()
6361
6362         // Get a domains cursor.
6363         val domainsCursor = domainsDatabaseHelper!!.domainNameCursorOrderedByDomain
6364
6365         // Get the current count of domains.
6366         val domainsCount = domainsCursor.count
6367
6368         // Get the domain name column index.
6369         val domainNameColumnIndex = domainsCursor.getColumnIndexOrThrow(DOMAIN_NAME)
6370
6371         // Populate the domain settings set.
6372         for (i in 0 until domainsCount) {
6373             // Move the domains cursor to the current row.
6374             domainsCursor.moveToPosition(i)
6375
6376             // Store the domain name in the domain settings set.
6377             domainsSettingsSet.add(domainsCursor.getString(domainNameColumnIndex))
6378         }
6379
6380         // Close the domains cursor.
6381         domainsCursor.close()
6382     }
6383
6384     override fun updateFontSize(dialogFragment: DialogFragment) {
6385         // Get the dialog.
6386         val dialog = dialogFragment.dialog!!
6387
6388         // Get a handle for the font size edit text.
6389         val fontSizeEditText = dialog.findViewById<EditText>(R.id.font_size_edittext)
6390
6391         // Initialize the new font size variable with the current font size.
6392         var newFontSize = currentWebView!!.settings.textZoom
6393
6394         // Get the font size from the edit text.
6395         try {
6396             newFontSize = fontSizeEditText.text.toString().toInt()
6397         } catch (exception: Exception) {
6398             // If the edit text does not contain a valid font size do nothing.
6399         }
6400
6401         // Apply the new font size.
6402         currentWebView!!.settings.textZoom = newFontSize
6403     }
6404
6405     private fun updatePrivacyIcons(runInvalidateOptionsMenu: Boolean) {
6406         // Only update the privacy icons if the options menu and the current WebView have already been populated.
6407         if ((optionsMenu != null) && (currentWebView != null)) {
6408             // Update the privacy icon.
6409             if (currentWebView!!.settings.javaScriptEnabled)  // JavaScript is enabled.
6410                 optionsPrivacyMenuItem.setIcon(R.drawable.javascript_enabled)
6411             else if (currentWebView!!.acceptCookies)  // JavaScript is disabled but cookies are enabled.
6412                 optionsPrivacyMenuItem.setIcon(R.drawable.warning)
6413             else  // All the dangerous features are disabled.
6414                 optionsPrivacyMenuItem.setIcon(R.drawable.privacy_mode)
6415
6416             // Update the cookies icon.
6417             if (currentWebView!!.acceptCookies)
6418                 optionsCookiesMenuItem.setIcon(R.drawable.cookies_enabled)
6419             else
6420                 optionsCookiesMenuItem.setIcon(R.drawable.cookies_disabled)
6421
6422             // Update the refresh icon.
6423             if (optionsRefreshMenuItem.title == getString(R.string.refresh))  // The refresh icon is displayed.
6424                 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled)
6425             else  // The stop icon is displayed.
6426                 optionsRefreshMenuItem.setIcon(R.drawable.close_blue)
6427
6428             // `invalidateOptionsMenu()` calls `onPrepareOptionsMenu()` and redraws the icons in the app bar.
6429             if (runInvalidateOptionsMenu)
6430                 invalidateOptionsMenu()
6431         }
6432     }
6433
6434     fun updateUrlEditTextAfterDelay() {
6435         // Create a handler to update the URL edit box.
6436         val urlEditTextUpdateHandler = Handler(Looper.getMainLooper())
6437
6438         // Create a runnable to update the URL edit box.
6439         val urlEditTextUpdateRunnable = Runnable {
6440             // Update the URL edit text.
6441             urlEditText.setText(currentWebView!!.url)
6442
6443             // Disable the wide viewport if the source is being viewed.
6444             if (currentWebView!!.url!!.startsWith("view-source:"))
6445                 currentWebView!!.settings.useWideViewPort = false
6446         }
6447
6448         // Update the URL edit text after 50 milliseconds, so that the WebView has enough time to navigate to the new URL.
6449         urlEditTextUpdateHandler.postDelayed(urlEditTextUpdateRunnable, 50)
6450     }
6451 }