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