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