2 * Copyright 2015-2023 Soren Stoutner <soren@stoutner.com>.
4 * Download cookie code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
6 * This file is part of Privacy Browser Android <https://www.stoutner.com/privacy-browser-android>.
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.
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.
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/>.
22 package com.stoutner.privacybrowser.activities
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
93 import androidx.activity.OnBackPressedCallback
94 import androidx.activity.result.contract.ActivityResultContracts
95 import androidx.appcompat.app.ActionBar
96 import androidx.appcompat.app.ActionBarDrawerToggle
97 import androidx.appcompat.app.AppCompatActivity
98 import androidx.appcompat.app.AppCompatDelegate
99 import androidx.appcompat.content.res.AppCompatResources
100 import androidx.appcompat.widget.Toolbar
101 import androidx.coordinatorlayout.widget.CoordinatorLayout
102 import androidx.core.view.GravityCompat
103 import androidx.cursoradapter.widget.CursorAdapter
104 import androidx.drawerlayout.widget.DrawerLayout
105 import androidx.fragment.app.DialogFragment
106 import androidx.preference.PreferenceManager
107 import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
108 import androidx.viewpager2.widget.ViewPager2
109 import androidx.webkit.WebSettingsCompat
110 import androidx.webkit.WebViewFeature
112 import com.google.android.material.appbar.AppBarLayout
113 import com.google.android.material.floatingactionbutton.FloatingActionButton
114 import com.google.android.material.navigation.NavigationView
115 import com.google.android.material.snackbar.Snackbar
116 import com.google.android.material.tabs.TabLayout
118 import com.stoutner.privacybrowser.R
119 import com.stoutner.privacybrowser.adapters.WebViewStateAdapter
120 import com.stoutner.privacybrowser.coroutines.GetHostIpAddressesCoroutine
121 import com.stoutner.privacybrowser.coroutines.PopulateFilterListsCoroutine
122 import com.stoutner.privacybrowser.coroutines.PrepareSaveDialogCoroutine
123 import com.stoutner.privacybrowser.coroutines.SaveUrlCoroutine
124 import com.stoutner.privacybrowser.coroutines.SaveWebpageImageCoroutine
125 import com.stoutner.privacybrowser.dataclasses.PendingDialogDataClass
126 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog
127 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog
128 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog
129 import com.stoutner.privacybrowser.dialogs.FontSizeDialog
130 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog
131 import com.stoutner.privacybrowser.dialogs.OpenDialog
132 import com.stoutner.privacybrowser.dialogs.PinnedMismatchDialog
133 import com.stoutner.privacybrowser.dialogs.ProxyNotInstalledDialog
134 import com.stoutner.privacybrowser.dialogs.SaveDialog
135 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog
136 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog
137 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog
138 import com.stoutner.privacybrowser.dialogs.WaitingForProxyDialog
139 import com.stoutner.privacybrowser.fragments.WebViewTabFragment
140 import com.stoutner.privacybrowser.helpers.BOOKMARK_NAME
141 import com.stoutner.privacybrowser.helpers.BOOKMARK_URL
142 import com.stoutner.privacybrowser.helpers.COOKIES
143 import com.stoutner.privacybrowser.helpers.DARK_THEME
144 import com.stoutner.privacybrowser.helpers.DISABLED
145 import com.stoutner.privacybrowser.helpers.DISPLAY_IMAGES
146 import com.stoutner.privacybrowser.helpers.DOMAIN_NAME
147 import com.stoutner.privacybrowser.helpers.ENABLE_DOM_STORAGE
148 import com.stoutner.privacybrowser.helpers.ENABLE_EASYLIST
149 import com.stoutner.privacybrowser.helpers.ENABLE_EASYPRIVACY
150 import com.stoutner.privacybrowser.helpers.ENABLE_FANBOYS_ANNOYANCE_LIST
151 import com.stoutner.privacybrowser.helpers.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST
152 import com.stoutner.privacybrowser.helpers.ENABLE_FORM_DATA
153 import com.stoutner.privacybrowser.helpers.ENABLE_JAVASCRIPT
154 import com.stoutner.privacybrowser.helpers.ENABLE_ULTRAPRIVACY
155 import com.stoutner.privacybrowser.helpers.ENABLED
156 import com.stoutner.privacybrowser.helpers.FAVORITE_ICON
157 import com.stoutner.privacybrowser.helpers.FOLDER_ID
158 import com.stoutner.privacybrowser.helpers.FONT_SIZE
159 import com.stoutner.privacybrowser.helpers.ID
160 import com.stoutner.privacybrowser.helpers.IP_ADDRESSES
161 import com.stoutner.privacybrowser.helpers.IS_FOLDER
162 import com.stoutner.privacybrowser.helpers.LIGHT_THEME
163 import com.stoutner.privacybrowser.helpers.PINNED_IP_ADDRESSES
164 import com.stoutner.privacybrowser.helpers.PINNED_SSL_CERTIFICATE
165 import com.stoutner.privacybrowser.helpers.REQUEST_ALLOWED
166 import com.stoutner.privacybrowser.helpers.REQUEST_BLOCKED
167 import com.stoutner.privacybrowser.helpers.REQUEST_DEFAULT
168 import com.stoutner.privacybrowser.helpers.REQUEST_THIRD_PARTY
169 import com.stoutner.privacybrowser.helpers.SSL_ISSUED_BY_COMMON_NAME
170 import com.stoutner.privacybrowser.helpers.SSL_ISSUED_BY_ORGANIZATION
171 import com.stoutner.privacybrowser.helpers.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT
172 import com.stoutner.privacybrowser.helpers.SSL_ISSUED_TO_COMMON_NAME
173 import com.stoutner.privacybrowser.helpers.SSL_ISSUED_TO_ORGANIZATION
174 import com.stoutner.privacybrowser.helpers.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT
175 import com.stoutner.privacybrowser.helpers.SWIPE_TO_REFRESH
176 import com.stoutner.privacybrowser.helpers.SYSTEM_DEFAULT
177 import com.stoutner.privacybrowser.helpers.WEBVIEW_THEME
178 import com.stoutner.privacybrowser.helpers.WIDE_VIEWPORT
179 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper
180 import com.stoutner.privacybrowser.helpers.CheckFilterListHelper
181 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper
182 import com.stoutner.privacybrowser.helpers.ProxyHelper
183 import com.stoutner.privacybrowser.helpers.SanitizeUrlHelper
184 import com.stoutner.privacybrowser.helpers.UrlHelper
185 import com.stoutner.privacybrowser.views.BLOCKED_REQUESTS
186 import com.stoutner.privacybrowser.views.EASYLIST
187 import com.stoutner.privacybrowser.views.EASYPRIVACY
188 import com.stoutner.privacybrowser.views.FANBOYS_ANNOYANCE_LIST
189 import com.stoutner.privacybrowser.views.FANBOYS_SOCIAL_BLOCKING_LIST
190 import com.stoutner.privacybrowser.views.THIRD_PARTY_REQUESTS
191 import com.stoutner.privacybrowser.views.ULTRAPRIVACY
192 import com.stoutner.privacybrowser.views.NestedScrollWebView
194 import kotlinx.coroutines.CoroutineScope
195 import kotlinx.coroutines.Dispatchers
196 import kotlinx.coroutines.launch
197 import kotlinx.coroutines.withContext
199 import java.io.ByteArrayInputStream
200 import java.io.ByteArrayOutputStream
202 import java.io.FileInputStream
203 import java.io.FileOutputStream
204 import java.io.IOException
205 import java.io.UnsupportedEncodingException
207 import java.net.MalformedURLException
209 import java.net.URLDecoder
210 import java.net.URLEncoder
212 import java.text.NumberFormat
214 import java.util.ArrayList
215 import java.util.Date
216 import java.util.concurrent.Executors
217 import kotlin.system.exitProcess
219 // Define the public constants
220 const val CURRENT_URL = "current_url"
221 const val DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0
222 const val DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2
223 const val DOMAINS_CUSTOM_USER_AGENT = 12
224 const val SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1
225 const val SETTINGS_CUSTOM_USER_AGENT = 11
226 const val UNRECOGNIZED_USER_AGENT = -1
228 // Define the private class constants.
229 private const val BOOKMARKS_DRAWER_PINNED = "bookmarks_drawer_pinned"
230 private const val PROXY_MODE = "proxy_mode"
231 private const val SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST = "saved_nested_scroll_webview_state_array_list"
232 private const val SAVED_STATE_ARRAY_LIST = "saved_state_array_list"
233 private const val SAVED_TAB_POSITION = "saved_tab_position"
234 private const val TEMPORARY_MHT_FILE = "temporary_mht_file"
236 class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener, FontSizeDialog.UpdateFontSizeListener,
237 NavigationView.OnNavigationItemSelectedListener, OpenDialog.OpenListener, PinnedMismatchDialog.PinnedMismatchListener, PopulateFilterListsCoroutine.PopulateFilterListsListener, SaveDialog.SaveListener,
238 UrlHistoryDialog.NavigateHistoryListener, WebViewTabFragment.NewTabListener {
241 // Define the public static variables.
242 var currentBookmarksFolderId = 0L
243 val executorService = Executors.newFixedThreadPool(4)!!
244 var orbotStatus = "unknown"
245 val pendingDialogsArrayList = ArrayList<PendingDialogDataClass>()
246 var proxyMode = ProxyHelper.NONE
247 var restartFromBookmarksActivity = false
248 var webViewStateAdapter: WebViewStateAdapter? = null
250 // Declare the public static variables.
251 lateinit var appBarLayout: AppBarLayout
254 // Declare the class variables.
255 private lateinit var appBar: ActionBar
256 private lateinit var checkFilterListHelper: CheckFilterListHelper
257 private lateinit var bookmarksCursorAdapter: CursorAdapter
258 private lateinit var bookmarksListView: ListView
259 private lateinit var bookmarksDrawerPinnedImageView: ImageView
260 private lateinit var bookmarksTitleTextView: TextView
261 private lateinit var coordinatorLayout: CoordinatorLayout
262 private lateinit var cookieManager: CookieManager
263 private lateinit var defaultFontSizeString: String
264 private lateinit var defaultUserAgentName: String
265 private lateinit var defaultWebViewTheme: String
266 private lateinit var domainsSettingsSet: MutableSet<String>
267 private lateinit var drawerLayout: DrawerLayout
268 private lateinit var easyList: ArrayList<List<Array<String>>>
269 private lateinit var easyPrivacy: ArrayList<List<Array<String>>>
270 private lateinit var fanboysAnnoyanceList: ArrayList<List<Array<String>>>
271 private lateinit var fanboysSocialList: ArrayList<List<Array<String>>>
272 private lateinit var fileChooserCallback: ValueCallback<Array<Uri>>
273 private lateinit var finalGrayColorSpan: ForegroundColorSpan
274 private lateinit var findOnPageCountTextView: TextView
275 private lateinit var findOnPageEditText: EditText
276 private lateinit var findOnPageLinearLayout: LinearLayout
277 private lateinit var fullScreenVideoFrameLayout: FrameLayout
278 private lateinit var initialGrayColorSpan: ForegroundColorSpan
279 private lateinit var navigationBackMenuItem: MenuItem
280 private lateinit var navigationForwardMenuItem: MenuItem
281 private lateinit var navigationHistoryMenuItem: MenuItem
282 private lateinit var navigationRequestsMenuItem: MenuItem
283 private lateinit var optionsAddOrEditDomainMenuItem: MenuItem
284 private lateinit var optionsBlockAllThirdPartyRequestsMenuItem: MenuItem
285 private lateinit var optionsClearCookiesMenuItem: MenuItem
286 private lateinit var optionsClearDataMenuItem: MenuItem
287 private lateinit var optionsClearDomStorageMenuItem: MenuItem
288 private lateinit var optionsClearFormDataMenuItem: MenuItem
289 private lateinit var optionsCookiesMenuItem: MenuItem
290 private lateinit var optionsDarkWebViewMenuItem: MenuItem
291 private lateinit var optionsDisplayImagesMenuItem: MenuItem
292 private lateinit var optionsDomStorageMenuItem: MenuItem
293 private lateinit var optionsEasyListMenuItem: MenuItem
294 private lateinit var optionsEasyPrivacyMenuItem: MenuItem
295 private lateinit var optionsFanboysAnnoyanceListMenuItem: MenuItem
296 private lateinit var optionsFanboysSocialBlockingListMenuItem: MenuItem
297 private lateinit var optionsFilterListsMenuItem: MenuItem
298 private lateinit var optionsFontSizeMenuItem: MenuItem
299 private lateinit var optionsPrivacyMenuItem: MenuItem
300 private lateinit var optionsProxyCustomMenuItem: MenuItem
301 private lateinit var optionsProxyI2pMenuItem: MenuItem
302 private lateinit var optionsProxyMenuItem: MenuItem
303 private lateinit var optionsProxyNoneMenuItem: MenuItem
304 private lateinit var optionsProxyTorMenuItem: MenuItem
305 private lateinit var optionsRefreshMenuItem: MenuItem
306 private lateinit var optionsSaveFormDataMenuItem: MenuItem
307 private lateinit var optionsSwipeToRefreshMenuItem: MenuItem
308 private lateinit var optionsUltraListMenuItem: MenuItem
309 private lateinit var optionsUltraPrivacyMenuItem: MenuItem
310 private lateinit var optionsUserAgentChromeOnAndroidMenuItem: MenuItem
311 private lateinit var optionsUserAgentChromeOnWindowsMenuItem: MenuItem
312 private lateinit var optionsUserAgentChromiumOnLinuxMenuItem: MenuItem
313 private lateinit var optionsUserAgentCustomMenuItem: MenuItem
314 private lateinit var optionsUserAgentEdgeOnWindowsMenuItem: MenuItem
315 private lateinit var optionsUserAgentFirefoxOnAndroidMenuItem: MenuItem
316 private lateinit var optionsUserAgentFirefoxOnLinuxMenuItem: MenuItem
317 private lateinit var optionsUserAgentFirefoxOnWindowsMenuItem: MenuItem
318 private lateinit var optionsUserAgentInternetExplorerOnWindowsMenuItem: MenuItem
319 private lateinit var optionsUserAgentMenuItem: MenuItem
320 private lateinit var optionsUserAgentPrivacyBrowserMenuItem: MenuItem
321 private lateinit var optionsUserAgentSafariOnIosMenuItem: MenuItem
322 private lateinit var optionsUserAgentSafariOnMacosMenuItem: MenuItem
323 private lateinit var optionsUserAgentWebViewDefaultMenuItem: MenuItem
324 private lateinit var optionsViewSourceMenuItem: MenuItem
325 private lateinit var optionsWideViewportMenuItem: MenuItem
326 private lateinit var proxyHelper: ProxyHelper
327 private lateinit var redColorSpan: ForegroundColorSpan
328 private lateinit var rootFrameLayout: FrameLayout
329 private lateinit var saveUrlString: String
330 private lateinit var searchURL: String
331 private lateinit var sharedPreferences: SharedPreferences
332 private lateinit var swipeRefreshLayout: SwipeRefreshLayout
333 private lateinit var tabLayout: TabLayout
334 private lateinit var tabsLinearLayout: LinearLayout
335 private lateinit var toolbar: Toolbar
336 private lateinit var webViewDefaultUserAgent: String
337 private lateinit var webViewThemeEntryValuesStringArray: Array<String>
338 private lateinit var webViewViewPager2: ViewPager2
339 private lateinit var ultraList: ArrayList<List<Array<String>>>
340 private lateinit var urlEditText: EditText
341 private lateinit var urlRelativeLayout: RelativeLayout
342 private lateinit var userAgentDataArray: Array<String>
343 private lateinit var userAgentNamesArray: ArrayAdapter<CharSequence>
345 // Define the class variables.
346 private var actionBarDrawerToggle: ActionBarDrawerToggle? = null
347 private var appBarHeight = 0
348 private var bookmarksCursor: Cursor? = null
349 private var bookmarksDatabaseHelper: BookmarksDatabaseHelper? = null
350 private var bookmarksDrawerPinned = false
351 private var bottomAppBar = false
352 private var currentWebView: NestedScrollWebView? = null
353 private var defaultBlockAllThirdPartyRequests = false
354 private var defaultCookies = false
355 private var defaultDisplayWebpageImages = true
356 private var defaultDomStorage = false
357 private var defaultEasyList = true
358 private var defaultEasyPrivacy = true
359 private var defaultFanboysAnnoyanceList = true
360 private var defaultFanboysSocialBlockingList = true
361 private var defaultFormData = false // Form data can be removed once the minimum API >= 26.
362 private var defaultProgressViewEndOffset = 0
363 private var defaultProgressViewStartOffset = 0
364 private var defaultJavaScript = false
365 private var defaultSwipeToRefresh = true
366 private var defaultUltraList = true
367 private var defaultUltraPrivacy = true
368 private var defaultWideViewport = true
369 private var displayAdditionalAppBarIcons = false
370 private var displayingFullScreenVideo = false
371 private var domainsDatabaseHelper: DomainsDatabaseHelper? = null
372 private var downloadWithExternalApp = false
373 private var fullScreenBrowsingModeEnabled = false
374 private var hideAppBar = false
375 private var inFullScreenBrowsingMode = false
376 private var incognitoModeEnabled = false
377 private var loadingNewIntent = false
378 private var objectAnimator = ObjectAnimator()
379 private var optionsMenu: Menu? = null
380 private var orbotStatusBroadcastReceiver: BroadcastReceiver? = null
381 private var reapplyAppSettingsOnRestart = false
382 private var reapplyDomainSettingsOnRestart = false
383 private var sanitizeAmpRedirects = false
384 private var sanitizeTrackingQueries = false
385 private var savedProxyMode: String? = null
386 private var savedNestedScrollWebViewStateArrayList: ArrayList<Bundle>? = null
387 private var savedStateArrayList: ArrayList<Bundle>? = null
388 private var savedTabPosition = 0
389 private var scrollAppBar = false
390 private var ultraPrivacy: ArrayList<List<Array<String>>>? = null
391 private var waitingForProxy = false
393 // Define the save webpage image activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
394 private val browseFileUploadActivityResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { activityResult ->
395 // Pass the file to the WebView.
396 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(activityResult.resultCode, activityResult.data))
399 // Define the save URL activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
400 private val saveUrlActivityResultLauncher = registerForActivityResult<String, Uri>(ActivityResultContracts.CreateDocument("*/*")) { fileUri ->
401 // Only save the URL if the file URI is not null, which happens if the user exited the file picker by pressing back.
402 if (fileUri != null) {
403 // Instantiate the save URL coroutine.
404 val saveUrlCoroutine = SaveUrlCoroutine()
407 saveUrlCoroutine.save(this, this, saveUrlString, fileUri, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
410 // Reset the save URL string.
414 // Define the save webpage archive activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
415 private val saveWebpageArchiveActivityResultLauncher = registerForActivityResult<String, Uri>(ActivityResultContracts.CreateDocument("multipart/related")) { fileUri ->
416 // Only save the webpage archive if the file URI is not null, which happens if the user exited the file picker by pressing back.
417 if (fileUri != null) {
418 // Initialize the file name string from the file URI last path segment.
419 var fileNameString = fileUri.lastPathSegment
421 // Query the exact file name if the API >= 26.
422 if (Build.VERSION.SDK_INT >= 26) {
423 // Get a cursor from the content resolver.
424 val contentResolverCursor = contentResolver.query(fileUri, null, null, null)!!
426 // Move to the fist row.
427 contentResolverCursor.moveToFirst()
429 // Get the file name from the cursor.
430 fileNameString = contentResolverCursor.getString(contentResolverCursor.getColumnIndexOrThrow(OpenableColumns.DISPLAY_NAME))
433 contentResolverCursor.close()
436 // Use a coroutine to save the file.
437 CoroutineScope(Dispatchers.Main).launch {
439 // Create the file on the IO thread.
440 withContext(Dispatchers.IO) {
441 // Create a temporary MHT file.
442 val temporaryMhtFile = File.createTempFile(TEMPORARY_MHT_FILE, ".mht", cacheDir)
444 // The WebView must be accessed from the main thread.
445 withContext(Dispatchers.Main) {
446 currentWebView!!.saveWebArchive(temporaryMhtFile.toString(), false) { callbackValue ->
447 if (callbackValue != null) { // The temporary MHT file was saved successfully.
449 // Create a temporary MHT file input stream.
450 val temporaryMhtFileInputStream = FileInputStream(temporaryMhtFile)
452 // Get an output stream for the save webpage file path.
453 val mhtOutputStream = contentResolver.openOutputStream(fileUri)!!
455 // Create a transfer byte array.
456 val transferByteArray = ByteArray(1024)
458 // Create an integer to track the number of bytes read.
461 // Copy the temporary MHT file input stream to the MHT output stream.
462 while (temporaryMhtFileInputStream.read(transferByteArray).also { bytesRead = it } > 0)
463 mhtOutputStream.write(transferByteArray, 0, bytesRead)
465 // Close the streams.
466 mhtOutputStream.close()
467 temporaryMhtFileInputStream.close()
469 // Display a snackbar.
470 Snackbar.make(currentWebView!!, getString(R.string.saved, fileNameString), Snackbar.LENGTH_SHORT).show()
471 } catch (exception: Exception) {
472 // Display snackbar with the exception.
473 Snackbar.make(currentWebView!!, getString(R.string.error_saving_file, fileNameString, exception), Snackbar.LENGTH_INDEFINITE).show()
475 // Delete the temporary MHT file.
476 temporaryMhtFile.delete()
478 } else { // There was an unspecified error while saving the temporary MHT file.
479 // Display a snackbar.
480 Snackbar.make(currentWebView!!, getString(R.string.error_saving_file, fileNameString, getString(R.string.unknown_error)), Snackbar.LENGTH_INDEFINITE).show()
485 } catch (ioException: IOException) {
486 // Display a snackbar with the IO exception.
487 Snackbar.make(currentWebView!!, getString(R.string.error_saving_file, fileNameString, ioException), Snackbar.LENGTH_INDEFINITE).show()
493 // Define the save webpage image activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
494 private val saveWebpageImageActivityResultLauncher = registerForActivityResult<String, Uri>(ActivityResultContracts.CreateDocument("image/png")) { fileUri ->
495 // Only save the webpage image if the file URI is not null, which happens if the user exited the file picker by pressing back.
496 if (fileUri != null) {
497 // Instantiate the save webpage image coroutine.
498 val saveWebpageImageCoroutine = SaveWebpageImageCoroutine()
500 // Save the webpage image.
501 saveWebpageImageCoroutine.save(this, fileUri, currentWebView!!)
505 override fun onCreate(savedInstanceState: Bundle?) {
506 // Run the default commands.
507 super.onCreate(savedInstanceState)
509 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
510 PreferenceManager.setDefaultValues(this, R.xml.preferences, false)
512 // Get a handle for the shared preferences.
513 sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
515 // Get the preferences.
516 val appTheme = sharedPreferences.getString(getString(R.string.app_theme_key), getString(R.string.app_theme_default_value))
517 val allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false)
518 bottomAppBar = sharedPreferences.getBoolean(getString(R.string.bottom_app_bar_key), false)
519 displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false)
521 // Get the theme entry values string array.
522 val appThemeEntryValuesStringArray = resources.getStringArray(R.array.app_theme_entry_values)
524 // Get the current theme status.
525 val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
527 // 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.
528 if (appTheme == appThemeEntryValuesStringArray[1]) { // The light theme is selected.
529 // Apply the light theme.
530 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
531 } else if (appTheme == appThemeEntryValuesStringArray[2]) { // The dark theme is selected.
532 // Apply the dark theme.
533 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
534 } else { // The system default theme is selected.
535 if (Build.VERSION.SDK_INT >= 28) { // The system default theme is supported.
536 // Follow the system default theme.
537 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
538 } else { // The system default theme is not supported.
539 // Follow the battery saver mode.
540 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY)
544 // Do not continue if the app theme is different than the OS theme. The app always initially starts in the OS theme.
545 // 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.
546 // 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.
547 // See https://redmine.stoutner.com/issues/952.
548 if ((appTheme == appThemeEntryValuesStringArray[0]) || // The system default theme is used.
549 ((appTheme == appThemeEntryValuesStringArray[1]) && (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO)) || // The app is running in day theme as desired.
550 ((appTheme == appThemeEntryValuesStringArray[2]) && (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES))) { // The app is running in night theme as desired.
552 // Disable screenshots if not allowed.
553 if (!allowScreenshots) {
554 window.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
557 // Check to see if the activity has been restarted.
558 if (savedInstanceState != null) {
559 // Store the saved instance state variables. The deprecated `getParcelableArrayList` can be upgraded once the minimum API >= 33.
560 bookmarksDrawerPinned = savedInstanceState.getBoolean(BOOKMARKS_DRAWER_PINNED)
561 @Suppress("DEPRECATION")
562 savedStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_STATE_ARRAY_LIST)
563 @Suppress("DEPRECATION")
564 savedNestedScrollWebViewStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST)
565 savedTabPosition = savedInstanceState.getInt(SAVED_TAB_POSITION)
566 savedProxyMode = savedInstanceState.getString(PROXY_MODE)
569 // 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.
570 WebView.enableSlowWholeDocumentDraw()
572 // Set the content view according to the position of the app bar.
574 setContentView(R.layout.main_framelayout_bottom_appbar)
576 setContentView(R.layout.main_framelayout_top_appbar)
578 // Get handles for the views.
579 rootFrameLayout = findViewById(R.id.root_framelayout)
580 drawerLayout = findViewById(R.id.drawerlayout)
581 coordinatorLayout = findViewById(R.id.coordinatorlayout)
582 appBarLayout = findViewById(R.id.appbar_layout)
583 toolbar = findViewById(R.id.toolbar)
584 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout)
585 findOnPageEditText = findViewById(R.id.find_on_page_edittext)
586 findOnPageCountTextView = findViewById(R.id.find_on_page_count_textview)
587 tabsLinearLayout = findViewById(R.id.tabs_linearlayout)
588 tabLayout = findViewById(R.id.tablayout)
589 swipeRefreshLayout = findViewById(R.id.swiperefreshlayout)
590 webViewViewPager2 = findViewById(R.id.webview_viewpager2)
591 val navigationView = findViewById<NavigationView>(R.id.navigationview)
592 bookmarksListView = findViewById(R.id.bookmarks_drawer_listview)
593 bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview)
594 bookmarksDrawerPinnedImageView = findViewById(R.id.bookmarks_drawer_pinned_imageview)
595 fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout)
597 // Get a handle for the navigation menu.
598 val navigationMenu = navigationView.menu
600 // Get handles for the navigation menu items.
601 navigationBackMenuItem = navigationMenu.findItem(R.id.back)
602 navigationForwardMenuItem = navigationMenu.findItem(R.id.forward)
603 navigationHistoryMenuItem = navigationMenu.findItem(R.id.history)
604 navigationRequestsMenuItem = navigationMenu.findItem(R.id.requests)
606 // Listen for touches on the navigation menu.
607 navigationView.setNavigationItemSelectedListener(this)
609 // Set the support action bar.
610 setSupportActionBar(toolbar)
612 // Get a handle for the app bar.
613 appBar = supportActionBar!!
615 // Set the custom app bar layout, which shows the URL text bar.
616 appBar.setCustomView(R.layout.url_app_bar)
618 // Display the custom app bar layout.
619 appBar.displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM
621 // Get handles for the views in the URL app bar.
622 urlRelativeLayout = findViewById(R.id.url_relativelayout)
623 urlEditText = findViewById(R.id.url_edittext)
625 // Create the hamburger icon at the start of the AppBar.
626 actionBarDrawerToggle = ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer)
628 // Initially disable the sliding drawers. They will be enabled once the filter lists are loaded.
629 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
631 // Initially hide the user interface so that only the filter list loading screen is shown (if reloading).
632 drawerLayout.visibility = View.GONE
634 // Initialize the WebView state adapter.
635 webViewStateAdapter = WebViewStateAdapter(this)
637 // Set the pager adapter on the web view pager.
638 webViewViewPager2.adapter = webViewStateAdapter
640 // Store up to 100 tabs in memory.
641 webViewViewPager2.offscreenPageLimit = 100
643 // Disable swiping between pages in the view pager.
644 webViewViewPager2.isUserInputEnabled = false
646 // Get a handle for the cookie manager.
647 cookieManager = CookieManager.getInstance()
649 // Instantiate the helpers.
650 bookmarksDatabaseHelper = BookmarksDatabaseHelper(this)
651 domainsDatabaseHelper = DomainsDatabaseHelper(this)
652 proxyHelper = ProxyHelper()
654 // Update the bookmarks drawer pinned image view.
655 updateBookmarksDrawerPinnedImageView()
657 // Initialize the app.
660 // Apply the app settings from the shared preferences.
663 // Control what the system back command does.
664 val onBackPressedCallback: OnBackPressedCallback = object : OnBackPressedCallback(true) {
665 override fun handleOnBackPressed() {
666 // Process the different back options.
667 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
668 // Close the navigation drawer.
669 drawerLayout.closeDrawer(GravityCompat.START)
670 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)) { // The bookmarks drawer is open.
671 // close the bookmarks drawer.
672 drawerLayout.closeDrawer(GravityCompat.END)
673 } else if (displayingFullScreenVideo) { // A full screen video is shown.
674 // Exit the full screen video.
675 exitFullScreenVideo()
676 // It shouldn't be possible for the currentWebView to be null, but crash logs indicate it sometimes happens.
677 } else if (currentWebView != null && currentWebView!!.canGoBack()) { // There is at least one item in the current WebView history.
678 // Get the current web back forward list.
679 val webBackForwardList = currentWebView!!.copyBackForwardList()
681 // Get the previous entry URL.
682 val previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex - 1).url
684 // Apply the domain settings.
685 applyDomainSettings(currentWebView!!, previousUrl, resetTab = false, reloadWebsite = false, loadUrl = false)
688 currentWebView!!.goBack()
690 // Update the URL edit text after a delay.
691 updateUrlEditTextAfterDelay()
692 } else { // Close the current tab.
693 // A view is required because the method is also called by an XML `onClick`.
699 // Register the on back pressed callback.
700 onBackPressedDispatcher.addCallback(this, onBackPressedCallback)
702 // Instantiate the populate filter lists coroutine.
703 val populateFilterListsCoroutine = PopulateFilterListsCoroutine(this)
705 // Populate the filter lists.
706 populateFilterListsCoroutine.populateFilterLists(this)
710 public override fun onPostCreate(savedInstanceState: Bundle?) {
711 // Run the default commands.
712 super.onPostCreate(savedInstanceState)
714 // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished. This creates the navigation drawer icon.
715 // If the app is restarting to change the app theme the action bar drawer toggle will not yet be populated.
716 actionBarDrawerToggle?.syncState()
719 override fun onNewIntent(intent: Intent) {
720 // Run the default commands.
721 super.onNewIntent(intent)
723 // Get the information from the intent.
724 val intentAction = intent.action
725 val intentUriData = intent.data
726 val intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT)
728 // Determine if this is a web search.
729 val isWebSearch = (intentAction != null) && (intentAction == Intent.ACTION_WEB_SEARCH)
731 // Check to see if the app is being restarted from a saved state.
732 if (ultraPrivacy != null) { // The activity is not being restarted from a saved state.
733 // 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.
734 if ((intentUriData != null) || (intentStringExtra != null) || isWebSearch) {
735 // Exit the full screen video if it is displayed.
736 if (displayingFullScreenVideo) {
737 // Exit full screen video mode.
738 exitFullScreenVideo()
740 // Reload the current WebView. Otherwise, it can display entirely black.
741 currentWebView!!.reload()
745 val url = if (isWebSearch) { // The intent is a web search.
746 // Sanitize the search input and convert it to a search.
747 val encodedSearchString = try {
748 URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8")
749 } catch (exception: UnsupportedEncodingException) {
753 // Add the base search URL.
754 searchURL + encodedSearchString
755 } else { // The intent contains a URL in either the data or an extra.
756 intentUriData?.toString() ?: intentStringExtra
759 // Add a new tab if specified in the preferences.
760 if (sharedPreferences.getBoolean(getString(R.string.open_intents_in_new_tab_key), true)) { // Load the URL in a new tab.
761 // Set the loading new intent flag.
762 loadingNewIntent = true
765 addNewTab(url!!, true)
766 } else { // Load the URL in the current tab.
768 loadUrl(currentWebView!!, url!!)
771 // Close the navigation drawer if it is open.
772 if (drawerLayout.isDrawerVisible(GravityCompat.START))
773 drawerLayout.closeDrawer(GravityCompat.START)
775 // Close the bookmarks drawer if it is open.
776 if (drawerLayout.isDrawerVisible(GravityCompat.END))
777 drawerLayout.closeDrawer(GravityCompat.END)
779 } else { // The app has been restarted.
780 // If the new intent will open a new tab, set the saved tab position to be the size of the saved state array list.
781 // The tab position is 0 based, meaning the new tab will be the tab position that is restored.
782 if ((intentUriData != null) || (intentStringExtra != null) || isWebSearch)
783 savedTabPosition = savedStateArrayList!!.size
785 // Replace the intent that started the app with this one. This will load the tab after the others have been restored.
790 public override fun onRestart() {
791 // Run the default commands.
794 // Apply the app settings if returning from the Settings activity.
795 if (reapplyAppSettingsOnRestart) {
796 // Reset the reapply app settings on restart flag.
797 reapplyAppSettingsOnRestart = false
799 // Apply the app settings.
803 // Apply the domain settings if returning from the settings or domains activity.
804 if (reapplyDomainSettingsOnRestart) {
805 // Reset the reapply domain settings on restart flag.
806 reapplyDomainSettingsOnRestart = false
808 // Update the domains settings set.
809 updateDomainsSettingsSet()
811 // Reapply the domain settings for each tab.
812 for (i in 0 until webViewStateAdapter!!.itemCount) {
813 // Get the WebView tab fragment.
814 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
816 // Get the fragment view.
817 val fragmentView = webViewTabFragment.view
819 // Only reload the WebViews if they exist.
820 if (fragmentView != null) {
821 // Get the nested scroll WebView from the tab fragment.
822 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
824 // Reset the current domain name so the domain settings will be reapplied.
825 nestedScrollWebView.currentDomainName = ""
827 // Reapply the domain settings if the URL is not null, which happens for empty tabs when returning from settings.
828 if (nestedScrollWebView.url != null)
829 applyDomainSettings(nestedScrollWebView, nestedScrollWebView.url, resetTab = false, reloadWebsite = true, loadUrl = false)
834 // Update the bookmarks drawer if returning from the Bookmarks activity.
835 if (restartFromBookmarksActivity) {
836 // Reset the restart from bookmarks activity flag.
837 restartFromBookmarksActivity = false
839 // Close the bookmarks drawer.
840 drawerLayout.closeDrawer(GravityCompat.END)
842 // Reload the bookmarks drawer.
843 loadBookmarksFolder()
846 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
847 updatePrivacyIcons(true)
850 // `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.
851 public override fun onStart() {
852 // Run the default commands.
855 // 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.
856 if (webViewStateAdapter != null) {
857 for (i in 0 until webViewStateAdapter!!.itemCount) {
858 // Get the WebView tab fragment.
859 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
861 // Get the fragment view.
862 val fragmentView = webViewTabFragment.view
864 // Only resume the WebViews if they exist (they won't when the app is first created).
865 if (fragmentView != null) {
866 // Get the nested scroll WebView from the tab fragment.
867 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
869 // Resume the nested scroll WebView.
870 nestedScrollWebView.onResume()
875 // Resume the nested scroll WebView JavaScript timers. This is a global command that resumes JavaScript timers on all WebViews.
876 if (currentWebView != null)
877 currentWebView!!.resumeTimers()
879 // Reapply the proxy settings if the system is using a proxy. This redisplays the appropriate alert dialog.
880 if (proxyMode != ProxyHelper.NONE)
883 // Reapply any system UI flags.
884 if (displayingFullScreenVideo || inFullScreenBrowsingMode) { // The system is displaying a website or a video in full screen mode.
885 /* Hide the system bars.
886 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
887 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
888 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
889 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
892 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
893 @Suppress("DEPRECATION")
894 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
897 // Show any pending dialogs.
898 for (i in pendingDialogsArrayList.indices) {
899 // Get the pending dialog from the array list.
900 val (dialogFragment, tag) = pendingDialogsArrayList[i]
902 // Show the pending dialog.
903 dialogFragment.show(supportFragmentManager, tag)
906 // Clear the pending dialogs array list.
907 pendingDialogsArrayList.clear()
910 public override fun onSaveInstanceState(savedInstanceState: Bundle) {
911 // Run the default commands.
912 super.onSaveInstanceState(savedInstanceState)
914 // 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.
915 if (webViewStateAdapter != null) {
916 // Initialize the saved state array lists.
917 savedStateArrayList = ArrayList<Bundle>()
918 savedNestedScrollWebViewStateArrayList = ArrayList<Bundle>()
920 // Get the URLs from each tab.
921 for (i in 0 until webViewStateAdapter!!.itemCount) {
922 // Get the WebView tab fragment.
923 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
925 // Get the fragment view.
926 val fragmentView = webViewTabFragment.view
928 // Save the fragment state if it is not null.
929 if (fragmentView != null) {
930 // Get the nested scroll WebView from the tab fragment.
931 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
933 // Create the saved state bundle.
934 val savedStateBundle = Bundle()
936 // Get the current states.
937 nestedScrollWebView.saveState(savedStateBundle)
938 val savedNestedScrollWebViewStateBundle = nestedScrollWebView.saveNestedScrollWebViewState()
940 // Store the saved states in the array lists.
941 savedStateArrayList!!.add(savedStateBundle)
942 savedNestedScrollWebViewStateArrayList!!.add(savedNestedScrollWebViewStateBundle)
946 // Get the current tab position.
947 val currentTabPosition = tabLayout.selectedTabPosition
949 // Store the saved states in the bundle.
950 savedInstanceState.putBoolean(BOOKMARKS_DRAWER_PINNED, bookmarksDrawerPinned)
951 savedInstanceState.putString(PROXY_MODE, proxyMode)
952 savedInstanceState.putParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST, savedNestedScrollWebViewStateArrayList)
953 savedInstanceState.putParcelableArrayList(SAVED_STATE_ARRAY_LIST, savedStateArrayList)
954 savedInstanceState.putInt(SAVED_TAB_POSITION, currentTabPosition)
958 // `onStop()` runs after `onPause()`. It is used instead of `onPause()` so the commands are not called every time the screen is partially hidden.
959 public override fun onStop() {
960 // Run the default commands.
963 // 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.
964 if (webViewStateAdapter != null) {
965 // Pause each web view.
966 for (i in 0 until webViewStateAdapter!!.itemCount) {
967 // Get the WebView tab fragment.
968 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
970 // Get the fragment view.
971 val fragmentView = webViewTabFragment.view
973 // Only pause the WebViews if they exist (they won't when the app is first created).
974 if (fragmentView != null) {
975 // Get the nested scroll WebView from the tab fragment.
976 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
978 // Pause the nested scroll WebView.
979 nestedScrollWebView.onPause()
984 // Pause the WebView JavaScript timers. This is a global command that pauses JavaScript on all WebViews.
985 if (currentWebView != null)
986 currentWebView!!.pauseTimers()
989 public override fun onDestroy() {
990 // Unregister the orbot status broadcast receiver if it exists.
991 if (orbotStatusBroadcastReceiver != null) {
992 unregisterReceiver(orbotStatusBroadcastReceiver)
995 // Close the bookmarks cursor if it exists.
996 bookmarksCursor?.close()
998 // Close the databases if they exist.
999 bookmarksDatabaseHelper?.close()
1000 domainsDatabaseHelper?.close()
1002 // Run the default commands.
1006 override fun onConfigurationChanged(newConfig: Configuration) {
1007 // Run the default commands.
1008 super.onConfigurationChanged(newConfig)
1010 // Get the current page.
1011 val currentPage = webViewViewPager2.currentItem
1013 // Toggle the pages if there is more than one so that the view pager will recalculate their size.
1014 if (currentPage > 0) {
1015 // Switch to the previous page.
1016 webViewViewPager2.currentItem = (currentPage - 1)
1018 // Switch back to the current page after the view pager has quiesced.
1019 webViewViewPager2.post { webViewViewPager2.currentItem = currentPage }
1023 override fun onCreateOptionsMenu(menu: Menu): Boolean {
1024 // Inflate the menu. This adds items to the app bar if it is present.
1025 menuInflater.inflate(R.menu.webview_options_menu, menu)
1027 // Get handles for the menu items.
1028 optionsPrivacyMenuItem = menu.findItem(R.id.javascript)
1029 optionsRefreshMenuItem = menu.findItem(R.id.refresh)
1030 val optionsBookmarksMenuItem = menu.findItem(R.id.bookmarks)
1031 optionsCookiesMenuItem = menu.findItem(R.id.cookies)
1032 optionsDomStorageMenuItem = menu.findItem(R.id.dom_storage)
1033 optionsSaveFormDataMenuItem = menu.findItem(R.id.save_form_data) // Form data can be removed once the minimum API >= 26.
1034 optionsClearDataMenuItem = menu.findItem(R.id.clear_data)
1035 optionsClearCookiesMenuItem = menu.findItem(R.id.clear_cookies)
1036 optionsClearDomStorageMenuItem = menu.findItem(R.id.clear_dom_storage)
1037 optionsClearFormDataMenuItem = menu.findItem(R.id.clear_form_data) // Form data can be removed once the minimum API >= 26.
1038 optionsEasyListMenuItem = menu.findItem(R.id.easylist)
1039 optionsEasyPrivacyMenuItem = menu.findItem(R.id.easyprivacy)
1040 optionsFanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list)
1041 optionsFanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list)
1042 optionsFilterListsMenuItem = menu.findItem(R.id.filterlists)
1043 optionsUltraListMenuItem = menu.findItem(R.id.ultralist)
1044 optionsUltraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy)
1045 optionsBlockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests)
1046 optionsProxyMenuItem = menu.findItem(R.id.proxy)
1047 optionsProxyNoneMenuItem = menu.findItem(R.id.proxy_none)
1048 optionsProxyTorMenuItem = menu.findItem(R.id.proxy_tor)
1049 optionsProxyI2pMenuItem = menu.findItem(R.id.proxy_i2p)
1050 optionsProxyCustomMenuItem = menu.findItem(R.id.proxy_custom)
1051 optionsUserAgentMenuItem = menu.findItem(R.id.user_agent)
1052 optionsUserAgentPrivacyBrowserMenuItem = menu.findItem(R.id.user_agent_privacy_browser)
1053 optionsUserAgentWebViewDefaultMenuItem = menu.findItem(R.id.user_agent_webview_default)
1054 optionsUserAgentFirefoxOnAndroidMenuItem = menu.findItem(R.id.user_agent_firefox_on_android)
1055 optionsUserAgentChromeOnAndroidMenuItem = menu.findItem(R.id.user_agent_chrome_on_android)
1056 optionsUserAgentSafariOnIosMenuItem = menu.findItem(R.id.user_agent_safari_on_ios)
1057 optionsUserAgentFirefoxOnLinuxMenuItem = menu.findItem(R.id.user_agent_firefox_on_linux)
1058 optionsUserAgentChromiumOnLinuxMenuItem = menu.findItem(R.id.user_agent_chromium_on_linux)
1059 optionsUserAgentFirefoxOnWindowsMenuItem = menu.findItem(R.id.user_agent_firefox_on_windows)
1060 optionsUserAgentChromeOnWindowsMenuItem = menu.findItem(R.id.user_agent_chrome_on_windows)
1061 optionsUserAgentEdgeOnWindowsMenuItem = menu.findItem(R.id.user_agent_edge_on_windows)
1062 optionsUserAgentInternetExplorerOnWindowsMenuItem = menu.findItem(R.id.user_agent_internet_explorer_on_windows)
1063 optionsUserAgentSafariOnMacosMenuItem = menu.findItem(R.id.user_agent_safari_on_macos)
1064 optionsUserAgentCustomMenuItem = menu.findItem(R.id.user_agent_custom)
1065 optionsSwipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh)
1066 optionsWideViewportMenuItem = menu.findItem(R.id.wide_viewport)
1067 optionsDisplayImagesMenuItem = menu.findItem(R.id.display_images)
1068 optionsDarkWebViewMenuItem = menu.findItem(R.id.dark_webview)
1069 optionsFontSizeMenuItem = menu.findItem(R.id.font_size)
1070 optionsViewSourceMenuItem = menu.findItem(R.id.view_source)
1071 optionsAddOrEditDomainMenuItem = menu.findItem(R.id.add_or_edit_domain)
1073 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1074 updatePrivacyIcons(false)
1076 // Only display the form data menu items if the API < 26.
1077 optionsSaveFormDataMenuItem.isVisible = Build.VERSION.SDK_INT < 26
1078 optionsClearFormDataMenuItem.isVisible = Build.VERSION.SDK_INT < 26
1080 // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
1081 optionsClearFormDataMenuItem.isEnabled = Build.VERSION.SDK_INT < 26
1083 // 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.
1084 if (displayAdditionalAppBarIcons) { // Display the additional icons.
1085 optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
1086 optionsBookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM)
1087 optionsCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM)
1088 } else { //Do not display the additional icons.
1089 optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER)
1090 optionsBookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER)
1091 optionsCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER)
1094 // Replace `Refresh` with `Stop` if a URL is already loading.
1095 if ((currentWebView != null) && (currentWebView!!.progress != 100)) {
1097 optionsRefreshMenuItem.setTitle(R.string.stop)
1099 // 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.
1100 if (displayAdditionalAppBarIcons)
1101 optionsRefreshMenuItem.setIcon(R.drawable.close_blue)
1104 // Store a handle for the options menu.
1111 override fun onPrepareOptionsMenu(menu: Menu): Boolean {
1112 // Initialize the current user agent string and the font size.
1113 var currentUserAgent = getString(R.string.user_agent_privacy_browser)
1116 // 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.
1117 if (currentWebView != null) {
1118 // Set the add or edit domain text.
1119 if (currentWebView!!.domainSettingsApplied)
1120 optionsAddOrEditDomainMenuItem.setTitle(R.string.edit_domain_settings)
1122 optionsAddOrEditDomainMenuItem.setTitle(R.string.add_domain_settings)
1124 // Get the current user agent from the WebView.
1125 currentUserAgent = currentWebView!!.settings.userAgentString
1127 // Get the current font size from the the WebView.
1128 fontSize = currentWebView!!.settings.textZoom
1130 // Set the status of the menu item checkboxes.
1131 optionsDomStorageMenuItem.isChecked = currentWebView!!.settings.domStorageEnabled
1132 @Suppress("DEPRECATION")
1133 optionsSaveFormDataMenuItem.isChecked = currentWebView!!.settings.saveFormData // Form data can be removed once the minimum API >= 26.
1134 optionsEasyListMenuItem.isChecked = currentWebView!!.easyListEnabled
1135 optionsEasyPrivacyMenuItem.isChecked = currentWebView!!.easyPrivacyEnabled
1136 optionsFanboysAnnoyanceListMenuItem.isChecked = currentWebView!!.fanboysAnnoyanceListEnabled
1137 optionsFanboysSocialBlockingListMenuItem.isChecked = currentWebView!!.fanboysSocialBlockingListEnabled
1138 optionsUltraListMenuItem.isChecked = currentWebView!!.ultraListEnabled
1139 optionsUltraPrivacyMenuItem.isChecked = currentWebView!!.ultraPrivacyEnabled
1140 optionsBlockAllThirdPartyRequestsMenuItem.isChecked = currentWebView!!.blockAllThirdPartyRequests
1141 optionsSwipeToRefreshMenuItem.isChecked = currentWebView!!.swipeToRefresh
1142 optionsWideViewportMenuItem.isChecked = currentWebView!!.settings.useWideViewPort
1143 optionsDisplayImagesMenuItem.isChecked = currentWebView!!.settings.loadsImagesAutomatically
1145 // Set the display names for the filter lists with the number of blocked requests.
1146 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + currentWebView!!.getRequestsCount(BLOCKED_REQUESTS)
1147 optionsEasyListMenuItem.title = currentWebView!!.getRequestsCount(EASYLIST).toString() + " - " + getString(R.string.easylist)
1148 optionsEasyPrivacyMenuItem.title = currentWebView!!.getRequestsCount(EASYPRIVACY).toString() + " - " + getString(R.string.easyprivacy)
1149 optionsFanboysAnnoyanceListMenuItem.title = currentWebView!!.getRequestsCount(FANBOYS_ANNOYANCE_LIST).toString() + " - " + getString(R.string.fanboys_annoyance_list)
1150 optionsFanboysSocialBlockingListMenuItem.title = currentWebView!!.getRequestsCount(FANBOYS_SOCIAL_BLOCKING_LIST).toString() + " - " + getString(R.string.fanboys_social_blocking_list)
1151 optionsUltraListMenuItem.title = currentWebView!!.getRequestsCount(com.stoutner.privacybrowser.views.ULTRALIST).toString() + " - " + getString(R.string.ultralist)
1152 optionsUltraPrivacyMenuItem.title = currentWebView!!.getRequestsCount(ULTRAPRIVACY).toString() + " - " + getString(R.string.ultraprivacy)
1153 optionsBlockAllThirdPartyRequestsMenuItem.title = currentWebView!!.getRequestsCount(THIRD_PARTY_REQUESTS).toString() + " - " + getString(R.string.block_all_third_party_requests)
1155 // Enable DOM Storage if JavaScript is enabled.
1156 optionsDomStorageMenuItem.isEnabled = currentWebView!!.settings.javaScriptEnabled
1158 // Get the current theme status.
1159 val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
1161 // Enable dark WebView if night mode is enabled.
1162 optionsDarkWebViewMenuItem.isEnabled = (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES)
1164 // Set the checkbox status for dark WebView if algorithmic darkening is supported.
1165 if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING))
1166 optionsDarkWebViewMenuItem.isChecked = WebSettingsCompat.isAlgorithmicDarkeningAllowed(currentWebView!!.settings)
1168 // Set the view source title according to the current URL.
1169 if (currentWebView!!.currentUrl.startsWith("view-source:"))
1170 optionsViewSourceMenuItem.title = getString(R.string.view_rendered_website)
1172 optionsViewSourceMenuItem.title = getString(R.string.view_source)
1175 // Set the cookies menu item checked status.
1176 optionsCookiesMenuItem.isChecked = cookieManager.acceptCookie()
1178 // Enable Clear Cookies if there are any.
1179 optionsClearCookiesMenuItem.isEnabled = cookieManager.hasCookies()
1181 // 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`.
1182 val privateDataDirectoryString = applicationInfo.dataDir
1184 // Get the storage directories.
1185 val localStorageDirectory = File("$privateDataDirectoryString/app_webview/Local Storage/")
1186 val indexedDBDirectory = File("$privateDataDirectoryString/app_webview/IndexedDB")
1188 // Initialize the number of files counters.
1189 var localStorageDirectoryNumberOfFiles = 0
1190 var indexedDBDirectoryNumberOfFiles = 0
1192 // 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.
1193 if (localStorageDirectory.exists())
1194 localStorageDirectoryNumberOfFiles = (localStorageDirectory.list())?.size ?: 0
1196 // Get a count of the number of files in the IndexedDB directory. The list can be null, in which case a `0` is returned.
1197 if (indexedDBDirectory.exists())
1198 indexedDBDirectoryNumberOfFiles = (indexedDBDirectory.list())?.size ?: 0
1200 // Enable Clear DOM Storage if there is any.
1201 optionsClearDomStorageMenuItem.isEnabled = localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0
1203 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
1204 if (Build.VERSION.SDK_INT < 26) {
1205 // Get the WebView database.
1206 val webViewDatabase = WebViewDatabase.getInstance(this)
1208 // Enable the clear form data menu item if there is anything to clear.
1209 @Suppress("DEPRECATION")
1210 optionsClearFormDataMenuItem.isEnabled = webViewDatabase.hasFormData()
1213 // Enable Clear Data if any of the submenu items are enabled.
1214 optionsClearDataMenuItem.isEnabled = (optionsClearCookiesMenuItem.isEnabled || optionsClearDomStorageMenuItem.isEnabled || optionsClearFormDataMenuItem.isEnabled)
1216 // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
1217 optionsFanboysSocialBlockingListMenuItem.isEnabled = !optionsFanboysAnnoyanceListMenuItem.isChecked
1219 // Set the proxy title and check the applied proxy.
1221 ProxyHelper.NONE -> {
1222 // Set the proxy title.
1223 optionsProxyMenuItem.title = getString(R.string.proxy) + " - " + getString(R.string.proxy_none)
1225 // Check the proxy None radio button.
1226 optionsProxyNoneMenuItem.isChecked = true
1229 ProxyHelper.TOR -> {
1230 // Set the proxy title.
1231 optionsProxyMenuItem.title = getString(R.string.proxy) + " - " + getString(R.string.proxy_tor)
1233 // Check the proxy Tor radio button.
1234 optionsProxyTorMenuItem.isChecked = true
1237 ProxyHelper.I2P -> {
1238 // Set the proxy title.
1239 optionsProxyMenuItem.title = getString(R.string.proxy) + " - " + getString(R.string.proxy_i2p)
1241 // Check the proxy I2P radio button.
1242 optionsProxyI2pMenuItem.isChecked = true
1245 ProxyHelper.CUSTOM -> {
1246 // Set the proxy title.
1247 optionsProxyMenuItem.title = getString(R.string.proxy) + " - " + getString(R.string.proxy_custom)
1249 // Check the proxy Custom radio button.
1250 optionsProxyCustomMenuItem.isChecked = true
1254 // Select the current user agent menu item.
1255 when (currentUserAgent) {
1256 resources.getStringArray(R.array.user_agent_data)[0] -> { // Privacy Browser.
1257 // Update the user agent menu item title.
1258 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_privacy_browser)
1260 // Select the Privacy Browser radio box.
1261 optionsUserAgentPrivacyBrowserMenuItem.isChecked = true
1264 webViewDefaultUserAgent -> { // WebView Default.
1265 // Update the user agent menu item title.
1266 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_webview_default)
1268 // Select the WebView Default radio box.
1269 optionsUserAgentWebViewDefaultMenuItem.isChecked = true
1272 resources.getStringArray(R.array.user_agent_data)[2] -> { // Firefox on Android.
1273 // Update the user agent menu item title.
1274 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_android)
1276 // Select the Firefox on Android radio box.
1277 optionsUserAgentFirefoxOnAndroidMenuItem.isChecked = true
1280 resources.getStringArray(R.array.user_agent_data)[3] -> { // Chrome on Android.
1281 // Update the user agent menu item title.
1282 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_android)
1284 // Select the Chrome on Android radio box.
1285 optionsUserAgentChromeOnAndroidMenuItem.isChecked = true
1288 resources.getStringArray(R.array.user_agent_data)[4] -> { // Safari on iOS.
1289 // Update the user agent menu item title.
1290 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_ios)
1292 // Select the Safari on iOS radio box.
1293 optionsUserAgentSafariOnIosMenuItem.isChecked = true
1296 resources.getStringArray(R.array.user_agent_data)[5] -> { // Firefox on Linux.
1297 // Update the user agent menu item title.
1298 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_linux)
1300 // Select the Firefox on Linux radio box.
1301 optionsUserAgentFirefoxOnLinuxMenuItem.isChecked = true
1304 resources.getStringArray(R.array.user_agent_data)[6] -> { // Chromium on Linux.
1305 // Update the user agent menu item title.
1306 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chromium_on_linux)
1308 // Select the Chromium on Linux radio box.
1309 optionsUserAgentChromiumOnLinuxMenuItem.isChecked = true
1312 resources.getStringArray(R.array.user_agent_data)[7] -> { // Firefox on Windows.
1313 // Update the user agent menu item title.
1314 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_windows)
1316 // Select the Firefox on Windows radio box.
1317 optionsUserAgentFirefoxOnWindowsMenuItem.isChecked = true
1320 resources.getStringArray(R.array.user_agent_data)[8] -> { // Chrome on Windows.
1321 // Update the user agent menu item title.
1322 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_windows)
1324 // Select the Chrome on Windows radio box.
1325 optionsUserAgentChromeOnWindowsMenuItem.isChecked = true
1328 resources.getStringArray(R.array.user_agent_data)[9] -> { // Edge on Windows.
1329 // Update the user agent menu item title.
1330 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_edge_on_windows)
1332 // Select the Edge on Windows radio box.
1333 optionsUserAgentEdgeOnWindowsMenuItem.isChecked = true
1336 resources.getStringArray(R.array.user_agent_data)[10] -> { // Internet Explorer on Windows.
1337 // Update the user agent menu item title.
1338 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_internet_explorer_on_windows)
1340 // Select the Internet on Windows radio box.
1341 optionsUserAgentInternetExplorerOnWindowsMenuItem.isChecked = true
1344 resources.getStringArray(R.array.user_agent_data)[11] -> { // Safari on macOS.
1345 // Update the user agent menu item title.
1346 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_macos)
1348 // Select the Safari on macOS radio box.
1349 optionsUserAgentSafariOnMacosMenuItem.isChecked = true
1352 else -> { // Custom user agent.
1353 // Update the user agent menu item title.
1354 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_custom)
1356 // Select the Custom radio box.
1357 optionsUserAgentCustomMenuItem.isChecked = true
1361 // Set the font size title.
1362 optionsFontSizeMenuItem.title = getString(R.string.font_size) + " - " + fontSize + "%"
1364 // Run all the other default commands.
1365 super.onPrepareOptionsMenu(menu)
1367 // Display the menu.
1371 override fun onOptionsItemSelected(menuItem: MenuItem): Boolean {
1372 // Run the commands that correlate to the selected menu item.
1373 return when (menuItem.itemId) {
1374 R.id.javascript -> { // JavaScript.
1375 // Toggle the JavaScript status.
1376 currentWebView!!.settings.javaScriptEnabled = !currentWebView!!.settings.javaScriptEnabled
1378 // Update the privacy icon.
1379 updatePrivacyIcons(true)
1381 // Display a snackbar.
1382 if (currentWebView!!.settings.javaScriptEnabled) // JavaScrip is enabled.
1383 Snackbar.make(webViewViewPager2, R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show()
1384 else if (cookieManager.acceptCookie()) // JavaScript is disabled, but cookies are enabled.
1385 Snackbar.make(webViewViewPager2, R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show()
1386 else // Privacy mode.
1387 Snackbar.make(webViewViewPager2, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show()
1389 // Reload the current WebView.
1390 currentWebView!!.reload()
1392 // Consume the event.
1396 R.id.refresh -> { // Refresh.
1397 // Run the command that correlates to the current status of the menu item.
1398 if (menuItem.title == getString(R.string.refresh)) // The refresh button was pushed.
1399 currentWebView!!.reload()
1400 else // The stop button was pushed.
1401 currentWebView!!.stopLoading()
1403 // Consume the event.
1407 R.id.bookmarks -> { // Bookmarks.
1408 // Open the bookmarks drawer.
1409 drawerLayout.openDrawer(GravityCompat.END)
1411 // Consume the event.
1415 R.id.cookies -> { // Cookies.
1416 // Toggle the cookie status.
1417 cookieManager.setAcceptCookie(!cookieManager.acceptCookie())
1419 // Store the cookie status.
1420 currentWebView!!.acceptCookies = cookieManager.acceptCookie()
1422 // Update the menu checkbox.
1423 menuItem.isChecked = cookieManager.acceptCookie()
1425 // Update the privacy icon.
1426 updatePrivacyIcons(true)
1428 // Display a snackbar.
1429 if (cookieManager.acceptCookie()) // Cookies are enabled.
1430 Snackbar.make(webViewViewPager2, R.string.cookies_enabled, Snackbar.LENGTH_SHORT).show()
1431 else if (currentWebView!!.settings.javaScriptEnabled) // JavaScript is still enabled.
1432 Snackbar.make(webViewViewPager2, R.string.cookies_disabled, Snackbar.LENGTH_SHORT).show()
1433 else // Privacy mode.
1434 Snackbar.make(webViewViewPager2, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show()
1436 // Reload the current WebView.
1437 currentWebView!!.reload()
1439 // Consume the event.
1443 R.id.dom_storage -> { // DOM storage.
1444 // Toggle the DOM storage status.
1445 currentWebView!!.settings.domStorageEnabled = !currentWebView!!.settings.domStorageEnabled
1447 // Update the menu checkbox.
1448 menuItem.isChecked = currentWebView!!.settings.domStorageEnabled
1450 // Update the privacy icon.
1451 updatePrivacyIcons(true)
1453 // Display a snackbar.
1454 if (currentWebView!!.settings.domStorageEnabled)
1455 Snackbar.make(webViewViewPager2, R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show()
1457 Snackbar.make(webViewViewPager2, R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show()
1459 // Reload the current WebView.
1460 currentWebView!!.reload()
1462 // Consume the event.
1466 R.id.save_form_data -> { // Form data. This can be removed once the minimum API >= 26.
1467 // Switch the status of saveFormDataEnabled.
1468 @Suppress("DEPRECATION")
1469 currentWebView!!.settings.saveFormData = !currentWebView!!.settings.saveFormData
1471 // Update the menu checkbox.
1472 @Suppress("DEPRECATION")
1473 menuItem.isChecked = currentWebView!!.settings.saveFormData
1475 // Display a snackbar.
1476 @Suppress("DEPRECATION")
1477 if (currentWebView!!.settings.saveFormData)
1478 Snackbar.make(webViewViewPager2, R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show()
1480 Snackbar.make(webViewViewPager2, R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show()
1482 // Update the privacy icon.
1483 updatePrivacyIcons(true)
1485 // Reload the current WebView.
1486 currentWebView!!.reload()
1488 // Consume the event.
1492 R.id.clear_cookies -> { // Clear cookies.
1493 // Create a snackbar.
1494 Snackbar.make(webViewViewPager2, R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1495 .setAction(R.string.undo) {} // Everything will be handled by `onDismissed()` below.
1496 .addCallback(object : Snackbar.Callback() {
1497 override fun onDismissed(snackbar: Snackbar, event: Int) {
1498 if (event != DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1499 // Delete the cookies.
1500 cookieManager.removeAllCookies(null)
1506 // Consume the event.
1510 R.id.clear_dom_storage -> { // Clear DOM storage.
1511 // Create a snackbar.
1512 Snackbar.make(webViewViewPager2, R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1513 .setAction(R.string.undo) {} // Everything will be handled by `onDismissed()` below.
1514 .addCallback(object : Snackbar.Callback() {
1515 override fun onDismissed(snackbar: Snackbar, event: Int) {
1516 if (event != DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1517 // Get a handle for the web storage.
1518 val webStorage = WebStorage.getInstance()
1520 // Delete the DOM Storage.
1521 webStorage.deleteAllData()
1523 // Initialize a handler to manually delete the DOM storage files and directories.
1524 val deleteDomStorageHandler = Handler(Looper.getMainLooper())
1526 // Setup a runnable to manually delete the DOM storage files and directories.
1527 val deleteDomStorageRunnable = Runnable {
1529 // Get a handle for the runtime.
1530 val runtime = Runtime.getRuntime()
1532 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1533 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1534 val privateDataDirectoryString = applicationInfo.dataDir
1536 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1537 val deleteLocalStorageProcess = runtime.exec(arrayOf("rm", "-rf", "$privateDataDirectoryString/app_webview/Local Storage/"))
1539 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1540 val deleteIndexProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview/IndexedDB")
1541 val deleteQuotaManagerProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/QuotaManager")
1542 val deleteQuotaManagerJournalProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/QuotaManager-journal")
1543 val deleteDatabasesProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview/databases")
1545 // Wait for the processes to finish.
1546 deleteLocalStorageProcess.waitFor()
1547 deleteIndexProcess.waitFor()
1548 deleteQuotaManagerProcess.waitFor()
1549 deleteQuotaManagerJournalProcess.waitFor()
1550 deleteDatabasesProcess.waitFor()
1551 } catch (exception: Exception) {
1552 // Do nothing if an error is thrown.
1556 // Manually delete the DOM storage files after 200 milliseconds.
1557 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200)
1563 // Consume the event.
1567 R.id.clear_form_data -> { // Clear form data. This can be remove once the minimum API >= 26.
1568 // Create a snackbar.
1569 Snackbar.make(webViewViewPager2, R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1570 .setAction(R.string.undo) {} // Everything will be handled by `onDismissed()` below.
1571 .addCallback(object : Snackbar.Callback() {
1572 override fun onDismissed(snackbar: Snackbar, event: Int) {
1573 if (event != DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1574 // Get a handle for the webView database.
1575 val webViewDatabase = WebViewDatabase.getInstance(applicationContext)
1577 // Delete the form data.
1578 @Suppress("DEPRECATION")
1579 webViewDatabase.clearFormData()
1585 // Consume the event.
1589 R.id.easylist -> { // EasyList.
1590 // Toggle the EasyList status.
1591 currentWebView!!.easyListEnabled = !currentWebView!!.easyListEnabled
1593 // Update the menu checkbox.
1594 menuItem.isChecked = currentWebView!!.easyListEnabled
1596 // Reload the current WebView.
1597 currentWebView!!.reload()
1599 // Consume the event.
1603 R.id.easyprivacy -> { // EasyPrivacy.
1604 // Toggle the EasyPrivacy status.
1605 currentWebView!!.easyPrivacyEnabled = !currentWebView!!.easyPrivacyEnabled
1607 // Update the menu checkbox.
1608 menuItem.isChecked = currentWebView!!.easyPrivacyEnabled
1610 // Reload the current WebView.
1611 currentWebView!!.reload()
1613 // Consume the event.
1617 R.id.fanboys_annoyance_list -> { // Fanboy's Annoyance List.
1618 // Toggle Fanboy's Annoyance List status.
1619 currentWebView!!.fanboysAnnoyanceListEnabled = !currentWebView!!.fanboysAnnoyanceListEnabled
1621 // Update the menu checkbox.
1622 menuItem.isChecked = currentWebView!!.fanboysAnnoyanceListEnabled
1624 // Update the status of Fanboy's Social Blocking List.
1625 optionsFanboysSocialBlockingListMenuItem.isEnabled = !currentWebView!!.fanboysAnnoyanceListEnabled
1627 // Reload the current WebView.
1628 currentWebView!!.reload()
1630 // Consume the event.
1634 R.id.fanboys_social_blocking_list -> { // Fanboy's Social Blocking List.
1635 // Toggle Fanboy's Social Blocking List status.
1636 currentWebView!!.fanboysSocialBlockingListEnabled = !currentWebView!!.fanboysSocialBlockingListEnabled
1638 // Update the menu checkbox.
1639 menuItem.isChecked = currentWebView!!.fanboysSocialBlockingListEnabled
1641 // Reload the current WebView.
1642 currentWebView!!.reload()
1644 // Consume the event.
1648 R.id.ultralist -> { // UltraList.
1649 // Toggle the UltraList status.
1650 currentWebView!!.ultraListEnabled = !currentWebView!!.ultraListEnabled
1652 // Update the menu checkbox.
1653 menuItem.isChecked = currentWebView!!.ultraListEnabled
1655 // Reload the current WebView.
1656 currentWebView!!.reload()
1658 // Consume the event.
1662 R.id.ultraprivacy -> { // UltraPrivacy.
1663 // Toggle the UltraPrivacy status.
1664 currentWebView!!.ultraPrivacyEnabled = !currentWebView!!.ultraPrivacyEnabled
1666 // Update the menu checkbox.
1667 menuItem.isChecked = currentWebView!!.ultraPrivacyEnabled
1669 // Reload the current WebView.
1670 currentWebView!!.reload()
1672 // Consume the event.
1676 R.id.block_all_third_party_requests -> { // Block all third-party requests.
1677 //Toggle the third-party requests blocker status.
1678 currentWebView!!.blockAllThirdPartyRequests = !currentWebView!!.blockAllThirdPartyRequests
1680 // Update the menu checkbox.
1681 menuItem.isChecked = currentWebView!!.blockAllThirdPartyRequests
1683 // Reload the current WebView.
1684 currentWebView!!.reload()
1686 // Consume the event.
1690 R.id.proxy_none -> { // Proxy - None.
1691 // Update the proxy mode.
1692 proxyMode = ProxyHelper.NONE
1694 // Apply the proxy mode.
1697 // Consume the event.
1701 R.id.proxy_tor -> { // Proxy - Tor.
1702 // Update the proxy mode.
1703 proxyMode = ProxyHelper.TOR
1705 // Apply the proxy mode.
1708 // Consume the event.
1712 R.id.proxy_i2p -> { // Proxy - I2P.
1713 // Update the proxy mode.
1714 proxyMode = ProxyHelper.I2P
1716 // Apply the proxy mode.
1719 // Consume the event.
1723 R.id.proxy_custom -> { // Proxy - Custom.
1724 // Update the proxy mode.
1725 proxyMode = ProxyHelper.CUSTOM
1727 // Apply the proxy mode.
1730 // Consume the event.
1734 R.id.user_agent_privacy_browser -> { // User Agent - Privacy Browser.
1735 // Update the user agent.
1736 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[0]
1738 // Reload the current WebView.
1739 currentWebView!!.reload()
1741 // Consume the event.
1745 R.id.user_agent_webview_default -> { // User Agent - WebView Default.
1746 // Update the user agent.
1747 currentWebView!!.settings.userAgentString = ""
1749 // Reload the current WebView.
1750 currentWebView!!.reload()
1752 // Consume the event.
1756 R.id.user_agent_firefox_on_android -> { // User Agent - Firefox on Android.
1757 // Update the user agent.
1758 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[2]
1760 // Reload the current WebView.
1761 currentWebView!!.reload()
1763 // Consume the event.
1767 R.id.user_agent_chrome_on_android -> { // User Agent - Chrome on Android.
1768 // Update the user agent.
1769 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[3]
1771 // Reload the current WebView.
1772 currentWebView!!.reload()
1774 // Consume the event.
1778 R.id.user_agent_safari_on_ios -> { // User Agent - Safari on iOS.
1779 // Update the user agent.
1780 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[4]
1782 // Reload the current WebView.
1783 currentWebView!!.reload()
1785 // Consume the event.
1789 R.id.user_agent_firefox_on_linux -> { // User Agent - Firefox on Linux.
1790 // Update the user agent.
1791 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[5]
1793 // Reload the current WebView.
1794 currentWebView!!.reload()
1796 // Consume the event.
1800 R.id.user_agent_chromium_on_linux -> { // User Agent - Chromium on Linux.
1801 // Update the user agent.
1802 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[6]
1804 // Reload the current WebView.
1805 currentWebView!!.reload()
1807 // Consume the event.
1811 R.id.user_agent_firefox_on_windows -> { // User Agent - Firefox on Windows.
1812 // Update the user agent.
1813 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[7]
1815 // Reload the current WebView.
1816 currentWebView!!.reload()
1818 // Consume the event.
1822 R.id.user_agent_chrome_on_windows -> { // User Agent - Chrome on Windows.
1823 // Update the user agent.
1824 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[8]
1826 // Reload the current WebView.
1827 currentWebView!!.reload()
1829 // Consume the event.
1833 R.id.user_agent_edge_on_windows -> { // User Agent - Edge on Windows.
1834 // Update the user agent.
1835 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[9]
1837 // Reload the current WebView.
1838 currentWebView!!.reload()
1840 // Consume the event.
1844 R.id.user_agent_internet_explorer_on_windows -> { // User Agent - Internet Explorer on Windows.
1845 // Update the user agent.
1846 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[10]
1848 // Reload the current WebView.
1849 currentWebView!!.reload()
1851 // Consume the event.
1855 R.id.user_agent_safari_on_macos -> { // User Agent - Safari on macOS.
1856 // Update the user agent.
1857 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[11]
1859 // Reload the current WebView.
1860 currentWebView!!.reload()
1862 // Consume the event.
1866 R.id.user_agent_custom -> { // User Agent - Custom.
1867 // Update the user agent.
1868 currentWebView!!.settings.userAgentString = sharedPreferences.getString(getString(R.string.custom_user_agent_key), getString(R.string.custom_user_agent_default_value))
1870 // Reload the current WebView.
1871 currentWebView!!.reload()
1873 // Consume the event.
1877 R.id.font_size -> { // Font size.
1878 // Instantiate the font size dialog.
1879 val fontSizeDialogFragment: DialogFragment = FontSizeDialog.displayDialog(currentWebView!!.settings.textZoom)
1881 // Show the font size dialog.
1882 fontSizeDialogFragment.show(supportFragmentManager, getString(R.string.font_size))
1884 // Consume the event.
1888 R.id.swipe_to_refresh -> { // Swipe to refresh.
1889 // Toggle the stored status of swipe to refresh.
1890 currentWebView!!.swipeToRefresh = !currentWebView!!.swipeToRefresh
1892 // Update the swipe refresh layout.
1893 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.
1894 swipeRefreshLayout.isEnabled = currentWebView!!.scrollY == 0
1895 else // Swipe to refresh is disabled.
1896 swipeRefreshLayout.isEnabled = false
1898 // Consume the event.
1902 R.id.wide_viewport -> { // Wide viewport.
1903 // Toggle the viewport.
1904 currentWebView!!.settings.useWideViewPort = !currentWebView!!.settings.useWideViewPort
1906 // Consume the event.
1910 R.id.display_images -> { // Display images.
1911 // Toggle the displaying of images.
1912 if (currentWebView!!.settings.loadsImagesAutomatically) { // Images are currently loaded automatically.
1913 // Disable loading of images.
1914 currentWebView!!.settings.loadsImagesAutomatically = false
1916 // Reload the website to remove existing images.
1917 currentWebView!!.reload()
1918 } else { // Images are not currently loaded automatically.
1919 // Enable loading of images. Missing images will be loaded without the need for a reload.
1920 currentWebView!!.settings.loadsImagesAutomatically = true
1923 // Consume the event.
1927 R.id.dark_webview -> { // Dark WebView.
1928 // Toggle dark WebView if supported.
1929 if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING))
1930 WebSettingsCompat.setAlgorithmicDarkeningAllowed(currentWebView!!.settings, !WebSettingsCompat.isAlgorithmicDarkeningAllowed(currentWebView!!.settings)
1933 // Consume the event.
1937 R.id.find_on_page -> { // Find on page.
1938 // Set the minimum height of the find on page linear layout to match the toolbar.
1939 findOnPageLinearLayout.minimumHeight = toolbar.height
1941 // Hide the toolbar.
1942 toolbar.visibility = View.GONE
1944 // Show the find on page linear layout.
1945 findOnPageLinearLayout.visibility = View.VISIBLE
1947 // Display the keyboard. The app must wait 200 ms before running the command to work around a bug in Android.
1948 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1949 findOnPageEditText.postDelayed({
1950 // Set the focus on the find on page edit text.
1951 findOnPageEditText.requestFocus()
1953 // Get a handle for the input method manager.
1954 val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
1956 // Display the keyboard. `0` sets no input flags.
1957 inputMethodManager.showSoftInput(findOnPageEditText, 0)
1960 // Consume the event.
1964 R.id.print -> { // Print.
1965 // Get a print manager instance.
1966 val printManager = (getSystemService(PRINT_SERVICE) as PrintManager)
1968 // Create a print document adapter from the current WebView.
1969 val printDocumentAdapter = currentWebView!!.createPrintDocumentAdapter(getString(R.string.print))
1971 // Print the document.
1972 printManager.print(getString(R.string.privacy_browser_webpage), printDocumentAdapter, null)
1974 // Consume the event.
1978 R.id.save_url -> { // Save URL.
1979 // Check the download preference.
1980 if (downloadWithExternalApp) // Download with an external app.
1981 downloadUrlWithExternalApp(currentWebView!!.currentUrl)
1982 else // Handle the download inside of Privacy Browser. The dialog will be displayed once the file size and the content disposition have been acquired.
1983 PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, currentWebView!!.currentUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
1985 // Consume the event.
1989 R.id.save_archive -> {
1990 // Open the file picker with a default file name built from the current domain name.
1991 saveWebpageArchiveActivityResultLauncher.launch(currentWebView!!.currentDomainName + ".mht")
1993 // Consume the event.
1997 R.id.save_image -> { // Save image.
1998 // Open the file picker with a default file name built from the current domain name.
1999 saveWebpageImageActivityResultLauncher.launch(currentWebView!!.currentDomainName + ".png")
2001 // Consume the event.
2005 R.id.add_to_homescreen -> { // Add to homescreen.
2006 // Instantiate the create home screen shortcut dialog.
2007 val createHomeScreenShortcutDialogFragment: DialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView!!.title!!, currentWebView!!.url!!, currentWebView!!.getFavoriteIcon())
2009 // Show the create home screen shortcut dialog.
2010 createHomeScreenShortcutDialogFragment.show(supportFragmentManager, getString(R.string.create_shortcut))
2012 // Consume the event.
2016 R.id.view_source -> { // View source.
2017 // Open a new tab according to the current URL.
2018 if (currentWebView!!.currentUrl.startsWith("view-source:")) { // The source is currently viewed.
2019 // Open the rendered website in a new tab.
2020 addNewTab(currentWebView!!.currentUrl.substring(12, currentWebView!!.currentUrl.length), true)
2021 } else { // The rendered website is currently viewed.
2022 // Open the source in a new tab.
2023 addNewTab("view-source:${currentWebView!!.currentUrl}", true)
2026 // Consume the event.
2030 R.id.view_headers -> { // View headers.
2031 // Create an intent to launch the view headers activity.
2032 val viewHeadersIntent = Intent(this, ViewHeadersActivity::class.java)
2034 // Add the variables to the intent.
2035 viewHeadersIntent.putExtra(CURRENT_URL, currentWebView!!.url)
2036 viewHeadersIntent.putExtra(USER_AGENT, currentWebView!!.settings.userAgentString)
2039 startActivity(viewHeadersIntent)
2041 // Consume the event.
2045 R.id.share_message -> { // Share a message.
2046 // Prepare the share string.
2047 val shareString = currentWebView!!.title + " – " + currentWebView!!.url
2049 // Create the share intent.
2050 val shareMessageIntent = Intent(Intent.ACTION_SEND)
2052 // Add the share string to the intent.
2053 shareMessageIntent.putExtra(Intent.EXTRA_TEXT, shareString)
2055 // Set the MIME type.
2056 shareMessageIntent.type = "text/plain"
2058 // Set the intent to open in a new task.
2059 shareMessageIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
2062 startActivity(Intent.createChooser(shareMessageIntent, getString(R.string.share_message)))
2064 // Consume the event.
2068 R.id.share_url -> { // Share URL.
2069 // Create the share intent.
2070 val shareUrlIntent = Intent(Intent.ACTION_SEND)
2072 // Add the URL to the intent.
2073 shareUrlIntent.putExtra(Intent.EXTRA_TEXT, currentWebView!!.url)
2075 // Add the title to the intent.
2076 shareUrlIntent.putExtra(Intent.EXTRA_SUBJECT, currentWebView!!.title)
2078 // Set the MIME type.
2079 shareUrlIntent.type = "text/plain"
2081 // Set the intent to open in a new task.
2082 shareUrlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
2085 startActivity(Intent.createChooser(shareUrlIntent, getString(R.string.share_url)))
2087 // Consume the event.
2091 R.id.open_with_app -> { // Open with app.
2092 // Open the URL with an outside app.
2093 openWithApp(currentWebView!!.url!!)
2095 // Consume the event.
2099 R.id.open_with_browser -> { // Open with browser.
2100 // Open the URL with an outside browser.
2101 openWithBrowser(currentWebView!!.url!!)
2103 // Consume the event.
2107 R.id.add_or_edit_domain -> { // Add or edit domain.
2108 // Reapply the domain settings on returning to `MainWebViewActivity`.
2109 reapplyDomainSettingsOnRestart = true
2111 // Check if domain settings are currently applied.
2112 if (currentWebView!!.domainSettingsApplied) { // Edit the current domain settings.
2113 // Create an intent to launch the domains activity.
2114 val domainsIntent = Intent(this, DomainsActivity::class.java)
2116 // Add the extra information to the intent.
2117 domainsIntent.putExtra(LOAD_DOMAIN, currentWebView!!.domainSettingsDatabaseId)
2118 domainsIntent.putExtra(CLOSE_ON_BACK, true)
2119 domainsIntent.putExtra(CURRENT_URL, currentWebView!!.url)
2120 domainsIntent.putExtra(CURRENT_IP_ADDRESSES, currentWebView!!.currentIpAddresses)
2122 // Get the current certificate.
2123 val sslCertificate = currentWebView!!.certificate
2125 // Check to see if the SSL certificate is populated.
2126 if (sslCertificate != null) {
2127 // Extract the certificate to strings.
2128 val issuedToCName = sslCertificate.issuedTo.cName
2129 val issuedToOName = sslCertificate.issuedTo.oName
2130 val issuedToUName = sslCertificate.issuedTo.uName
2131 val issuedByCName = sslCertificate.issuedBy.cName
2132 val issuedByOName = sslCertificate.issuedBy.oName
2133 val issuedByUName = sslCertificate.issuedBy.uName
2134 val startDateLong = sslCertificate.validNotBeforeDate.time
2135 val endDateLong = sslCertificate.validNotAfterDate.time
2137 // Add the certificate to the intent.
2138 domainsIntent.putExtra(SSL_ISSUED_TO_CNAME, issuedToCName)
2139 domainsIntent.putExtra(SSL_ISSUED_TO_ONAME, issuedToOName)
2140 domainsIntent.putExtra(SSL_ISSUED_TO_UNAME, issuedToUName)
2141 domainsIntent.putExtra(SSL_ISSUED_BY_CNAME, issuedByCName)
2142 domainsIntent.putExtra(SSL_ISSUED_BY_ONAME, issuedByOName)
2143 domainsIntent.putExtra(SSL_ISSUED_BY_UNAME, issuedByUName)
2144 domainsIntent.putExtra(SSL_START_DATE, startDateLong)
2145 domainsIntent.putExtra(SSL_END_DATE, endDateLong)
2149 startActivity(domainsIntent)
2150 } else { // Add a new domain.
2151 // Get the current URI.
2152 val currentUri = Uri.parse(currentWebView!!.url)
2154 // Get the current domain from the URI. Use an empty string if it is null.
2155 val currentDomain = currentUri.host?: ""
2157 // Create the domain and store the database ID.
2158 val newDomainDatabaseId = domainsDatabaseHelper!!.addDomain(currentDomain)
2160 // Create an intent to launch the domains activity.
2161 val domainsIntent = Intent(this, DomainsActivity::class.java)
2163 // Add the extra information to the intent.
2164 domainsIntent.putExtra(LOAD_DOMAIN, newDomainDatabaseId)
2165 domainsIntent.putExtra(CLOSE_ON_BACK, true)
2166 domainsIntent.putExtra(CURRENT_URL, currentWebView!!.url)
2167 domainsIntent.putExtra(CURRENT_IP_ADDRESSES, currentWebView!!.currentIpAddresses)
2169 // Get the current certificate.
2170 val sslCertificate = currentWebView!!.certificate
2172 // Check to see if the SSL certificate is populated.
2173 if (sslCertificate != null) {
2174 // Extract the certificate to strings.
2175 val issuedToCName = sslCertificate.issuedTo.cName
2176 val issuedToOName = sslCertificate.issuedTo.oName
2177 val issuedToUName = sslCertificate.issuedTo.uName
2178 val issuedByCName = sslCertificate.issuedBy.cName
2179 val issuedByOName = sslCertificate.issuedBy.oName
2180 val issuedByUName = sslCertificate.issuedBy.uName
2181 val startDateLong = sslCertificate.validNotBeforeDate.time
2182 val endDateLong = sslCertificate.validNotAfterDate.time
2184 // Add the certificate to the intent.
2185 domainsIntent.putExtra(SSL_ISSUED_TO_CNAME, issuedToCName)
2186 domainsIntent.putExtra(SSL_ISSUED_TO_ONAME, issuedToOName)
2187 domainsIntent.putExtra(SSL_ISSUED_TO_UNAME, issuedToUName)
2188 domainsIntent.putExtra(SSL_ISSUED_BY_CNAME, issuedByCName)
2189 domainsIntent.putExtra(SSL_ISSUED_BY_ONAME, issuedByOName)
2190 domainsIntent.putExtra(SSL_ISSUED_BY_UNAME, issuedByUName)
2191 domainsIntent.putExtra(SSL_START_DATE, startDateLong)
2192 domainsIntent.putExtra(SSL_END_DATE, endDateLong)
2196 startActivity(domainsIntent)
2199 // Consume the event.
2203 else -> { // There is no match with the options menu. Pass the event up to the parent method.
2204 // Don't consume the event.
2205 super.onOptionsItemSelected(menuItem)
2210 override fun onNavigationItemSelected(menuItem: MenuItem): Boolean {
2211 // Run the commands that correspond to the selected menu item.
2212 when (menuItem.itemId) {
2213 R.id.clear_and_exit -> { // Clear and exit.
2214 // Clear and exit Privacy Browser.
2218 R.id.home -> { // Home.
2219 // Load the homepage.
2220 loadUrl(currentWebView!!, sharedPreferences.getString(getString(R.string.homepage_key), getString(R.string.homepage_default_value))!!)
2223 R.id.back -> { // Back.
2224 // Check if the WebView can go back.
2225 if (currentWebView!!.canGoBack()) {
2226 // Get the current web back forward list.
2227 val webBackForwardList = currentWebView!!.copyBackForwardList()
2229 // Get the previous entry URL.
2230 val previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex - 1).url
2232 // Apply the domain settings.
2233 applyDomainSettings(currentWebView!!, previousUrl, resetTab = false, reloadWebsite = false, loadUrl = false)
2235 // Load the previous website in the history.
2236 currentWebView!!.goBack()
2238 // Update the URL edit text after a delay.
2239 updateUrlEditTextAfterDelay()
2243 R.id.forward -> { // Forward.
2244 // Check if the WebView can go forward.
2245 if (currentWebView!!.canGoForward()) {
2246 // Get the current web back forward list.
2247 val webBackForwardList = currentWebView!!.copyBackForwardList()
2249 // Get the next entry URL.
2250 val nextUrl = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex + 1).url
2252 // Apply the domain settings.
2253 applyDomainSettings(currentWebView!!, nextUrl, resetTab = false, reloadWebsite = false, loadUrl = false)
2255 // Load the next website in the history.
2256 currentWebView!!.goForward()
2258 // Update the URL edit text after a delay.
2259 updateUrlEditTextAfterDelay()
2263 R.id.history -> { // History.
2264 // Instantiate the URL history dialog.
2265 val urlHistoryDialogFragment: DialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView!!.webViewFragmentId)
2267 // Show the URL history dialog.
2268 urlHistoryDialogFragment.show(supportFragmentManager, getString(R.string.history))
2271 R.id.open -> { // Open.
2272 // Instantiate the open file dialog.
2273 val openDialogFragment: DialogFragment = OpenDialog()
2275 // Show the open file dialog.
2276 openDialogFragment.show(supportFragmentManager, getString(R.string.open))
2279 R.id.requests -> { // Requests.
2280 // Populate the resource requests.
2281 RequestsActivity.resourceRequests = currentWebView!!.getResourceRequests()
2283 // Create an intent to launch the Requests activity.
2284 val requestsIntent = Intent(this, RequestsActivity::class.java)
2286 // Add the block third-party requests status to the intent.
2287 requestsIntent.putExtra(BLOCK_ALL_THIRD_PARTY_REQUESTS, currentWebView!!.blockAllThirdPartyRequests)
2290 startActivity(requestsIntent)
2293 R.id.downloads -> { // Downloads.
2294 // Try the default system download manager.
2296 // Launch the default system Download Manager.
2297 val defaultDownloadManagerIntent = Intent(DownloadManager.ACTION_VIEW_DOWNLOADS)
2299 // Launch as a new task so that the download manager and Privacy Browser show as separate windows in the recent tasks list.
2300 defaultDownloadManagerIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2303 startActivity(defaultDownloadManagerIntent)
2304 } catch (defaultDownloadManagerException: Exception) { // The system download manager is not available.
2305 // Try a generic file manager.
2307 // Create a generic file manager intent.
2308 val genericFileManagerIntent = Intent(Intent.ACTION_VIEW)
2310 // Open the download directory.
2311 genericFileManagerIntent.setDataAndType(Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()), DocumentsContract.Document.MIME_TYPE_DIR)
2313 // Launch as a new task so that the file manager and Privacy Browser show as separate windows in the recent tasks list.
2314 genericFileManagerIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2317 startActivity(genericFileManagerIntent)
2318 } catch (genericFileManagerException: Exception) { // A generic file manager is not available.
2319 // Try an alternate file manager.
2321 // Create an alternate file manager intent.
2322 val alternateFileManagerIntent = Intent(Intent.ACTION_VIEW)
2324 // Open the download directory.
2325 alternateFileManagerIntent.setDataAndType(Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()), "resource/folder")
2327 // Launch as a new task so that the file manager and Privacy Browser show as separate windows in the recent tasks list.
2328 alternateFileManagerIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2330 // Open the alternate file manager.
2331 startActivity(alternateFileManagerIntent)
2332 } catch (alternateFileManagerException: Exception) {
2333 // Display a snackbar.
2334 Snackbar.make(currentWebView!!, R.string.no_file_manager_detected, Snackbar.LENGTH_INDEFINITE).show()
2340 R.id.domains -> { // Domains.
2341 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2342 reapplyDomainSettingsOnRestart = true
2344 // Create a domains activity intent.
2345 val domainsIntent = Intent(this, DomainsActivity::class.java)
2347 // Add the extra information to the intent.
2348 domainsIntent.putExtra(CURRENT_URL, currentWebView!!.url)
2349 domainsIntent.putExtra(CURRENT_IP_ADDRESSES, currentWebView!!.currentIpAddresses)
2351 // Get the current certificate.
2352 val sslCertificate = currentWebView!!.certificate
2354 // Check to see if the SSL certificate is populated.
2355 if (sslCertificate != null) {
2356 // Extract the certificate to strings.
2357 val issuedToCName = sslCertificate.issuedTo.cName
2358 val issuedToOName = sslCertificate.issuedTo.oName
2359 val issuedToUName = sslCertificate.issuedTo.uName
2360 val issuedByCName = sslCertificate.issuedBy.cName
2361 val issuedByOName = sslCertificate.issuedBy.oName
2362 val issuedByUName = sslCertificate.issuedBy.uName
2363 val startDateLong = sslCertificate.validNotBeforeDate.time
2364 val endDateLong = sslCertificate.validNotAfterDate.time
2366 // Add the certificate to the intent.
2367 domainsIntent.putExtra(SSL_ISSUED_TO_CNAME, issuedToCName)
2368 domainsIntent.putExtra(SSL_ISSUED_TO_ONAME, issuedToOName)
2369 domainsIntent.putExtra(SSL_ISSUED_TO_UNAME, issuedToUName)
2370 domainsIntent.putExtra(SSL_ISSUED_BY_CNAME, issuedByCName)
2371 domainsIntent.putExtra(SSL_ISSUED_BY_ONAME, issuedByOName)
2372 domainsIntent.putExtra(SSL_ISSUED_BY_UNAME, issuedByUName)
2373 domainsIntent.putExtra(SSL_START_DATE, startDateLong)
2374 domainsIntent.putExtra(SSL_END_DATE, endDateLong)
2378 startActivity(domainsIntent)
2381 R.id.settings -> { // Settings.
2382 // Set the reapply on restart flags.
2383 reapplyAppSettingsOnRestart = true
2384 reapplyDomainSettingsOnRestart = true
2386 // Create a settings intent.
2387 val settingsIntent = Intent(this, SettingsActivity::class.java)
2390 startActivity(settingsIntent)
2393 R.id.import_export -> { // Import/Export.
2394 // Create an intent to launch the import/export activity.
2395 val importExportIntent = Intent(this, ImportExportActivity::class.java)
2398 startActivity(importExportIntent)
2401 R.id.logcat -> { // Logcat.
2402 // Create an intent to launch the logcat activity.
2403 val logcatIntent = Intent(this, LogcatActivity::class.java)
2406 startActivity(logcatIntent)
2409 R.id.webview_devtools -> { // WebView DevTools.
2410 // Create a WebView DevTools intent.
2411 val webViewDevToolsIntent = Intent("com.android.webview.SHOW_DEV_UI")
2413 // Launch as a new task so that the WebView DevTools and Privacy Browser show as a separate windows in the recent tasks list.
2414 webViewDevToolsIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2417 startActivity(webViewDevToolsIntent)
2420 R.id.guide -> { // Guide.
2421 // Create an intent to launch the guide activity.
2422 val guideIntent = Intent(this, GuideActivity::class.java)
2425 startActivity(guideIntent)
2428 R.id.about -> { // About
2429 // Create an intent to launch the about activity.
2430 val aboutIntent = Intent(this, AboutActivity::class.java)
2432 // Create a string array for the filter list versions.
2433 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])
2435 // Add the filter list versions to the intent.
2436 aboutIntent.putExtra(FILTERLIST_VERSIONS, filterListVersions)
2439 startActivity(aboutIntent)
2443 // Close the navigation drawer.
2444 drawerLayout.closeDrawer(GravityCompat.START)
2450 override fun onCreateContextMenu(contextMenu: ContextMenu, view: View, contextMenuInfo: ContextMenu.ContextMenuInfo?) {
2451 // Get the hit test result.
2452 val hitTestResult = currentWebView!!.hitTestResult
2454 // Define the URL strings.
2455 val imageUrl: String?
2456 val linkUrl: String?
2458 // Get a handle for the clipboard manager.
2459 val clipboardManager = (getSystemService(CLIPBOARD_SERVICE) as ClipboardManager)
2461 // Process the link according to the type.
2462 when (hitTestResult.type) {
2463 // `SRC_ANCHOR_TYPE` is a link.
2464 WebView.HitTestResult.SRC_ANCHOR_TYPE -> {
2465 // Get the target URL.
2466 linkUrl = hitTestResult.extra!!
2468 // Set the target URL as the context menu title.
2469 contextMenu.setHeaderTitle(linkUrl)
2471 // Add an open in new tab entry.
2472 contextMenu.add(R.string.open_in_new_tab).setOnMenuItemClickListener {
2473 // Load the link URL in a new tab and move to it.
2474 addNewTab(linkUrl, true)
2476 // Consume the event.
2480 // Add an open in background entry.
2481 contextMenu.add(R.string.open_in_background).setOnMenuItemClickListener {
2482 // Load the link URL in a new tab but do not move to it.
2483 addNewTab(linkUrl, false)
2485 // Consume the event.
2489 // Add an open with app entry.
2490 contextMenu.add(R.string.open_with_app).setOnMenuItemClickListener {
2491 // Open the URL with another app.
2492 openWithApp(linkUrl)
2494 // Consume the event.
2498 // Add an open with browser entry.
2499 contextMenu.add(R.string.open_with_browser).setOnMenuItemClickListener {
2500 // Open the URL with another browser.
2501 openWithBrowser(linkUrl)
2503 // Consume the event.
2507 // Add a copy URL entry.
2508 contextMenu.add(R.string.copy_url).setOnMenuItemClickListener {
2509 // Save the link URL in a clip data.
2510 val srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl)
2512 // Set the clip data as the clipboard's primary clip.
2513 clipboardManager.setPrimaryClip(srcAnchorTypeClipData)
2515 // Consume the event.
2519 // Add a Save URL entry.
2520 contextMenu.add(R.string.save_url).setOnMenuItemClickListener {
2521 // Check the download preference.
2522 if (downloadWithExternalApp) // Download with an external app.
2523 downloadUrlWithExternalApp(linkUrl)
2524 else // Handle the download inside of Privacy Browser. The dialog will be displayed once the file size and the content disposition have been acquired.
2525 PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, linkUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
2527 // Consume the event.
2531 // Add an empty cancel entry, which by default closes the context menu.
2532 contextMenu.add(R.string.cancel)
2535 // `IMAGE_TYPE` is an image.
2536 WebView.HitTestResult.IMAGE_TYPE -> {
2537 // Get the image URL.
2538 imageUrl = hitTestResult.extra!!
2540 // Set the context menu title.
2541 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.
2542 contextMenu.setHeaderTitle(imageUrl.substring(0, 100))
2543 else // The image URL does not contain the full image data. Set the image URL as the title of the context menu.
2544 contextMenu.setHeaderTitle(imageUrl)
2546 // Add an open in new tab entry.
2547 contextMenu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener {
2548 // Load the image in a new tab.
2549 addNewTab(imageUrl, true)
2551 // Consume the event.
2555 // Add an open with app entry.
2556 contextMenu.add(R.string.open_with_app).setOnMenuItemClickListener {
2557 // Open the image URL with an external app.
2558 openWithApp(imageUrl)
2560 // Consume the event.
2564 // Add an open with browser entry.
2565 contextMenu.add(R.string.open_with_browser).setOnMenuItemClickListener {
2566 // Open the image URL with an external browser.
2567 openWithBrowser(imageUrl)
2569 // Consume the event.
2573 // Add a view image entry.
2574 contextMenu.add(R.string.view_image).setOnMenuItemClickListener {
2575 // Load the image in the current tab.
2576 loadUrl(currentWebView!!, imageUrl)
2578 // Consume the event.
2582 // Add a save image entry.
2583 contextMenu.add(R.string.save_image).setOnMenuItemClickListener {
2584 // Check the download preference.
2585 if (downloadWithExternalApp) { // Download with an external app.
2586 downloadUrlWithExternalApp(imageUrl)
2587 } else { // Handle the download inside of Privacy Browser. The dialog will be displayed once the file size and the content disposition have been acquired.
2588 PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, imageUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
2591 // Consume the event.
2595 // Add a copy URL entry.
2596 contextMenu.add(R.string.copy_url).setOnMenuItemClickListener {
2597 // Save the image URL in a clip data.
2598 val imageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl)
2600 // Set the clip data as the clipboard's primary clip.
2601 clipboardManager.setPrimaryClip(imageTypeClipData)
2603 // Consume the event.
2607 // Add an empty cancel entry, which by default closes the context menu.
2608 contextMenu.add(R.string.cancel)
2611 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2612 WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE -> {
2613 // Get the image URL.
2614 imageUrl = hitTestResult.extra!!
2616 // Instantiate a handler.
2617 val handler = Handler(Looper.getMainLooper())
2619 // Get a handle for the handler message.
2620 val message = handler.obtainMessage()
2622 // Request the image details from the last touched node be returned in the message.
2623 currentWebView!!.requestFocusNodeHref(message)
2625 // Get the link URL from the message data.
2626 linkUrl = message.data.getString("url")!!
2628 // Set the link URL as the title of the context menu.
2629 contextMenu.setHeaderTitle(linkUrl)
2631 // Add an open in new tab entry.
2632 contextMenu.add(R.string.open_in_new_tab).setOnMenuItemClickListener {
2633 // Load the link URL in a new tab and move to it.
2634 addNewTab(linkUrl, true)
2636 // Consume the event.
2640 // Add an open in background entry.
2641 contextMenu.add(R.string.open_in_background).setOnMenuItemClickListener {
2642 // Lod the link URL in a new tab but do not move to it.
2643 addNewTab(linkUrl, false)
2645 // Consume the event.
2649 // Add an open image in new tab entry.
2650 contextMenu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener {
2651 // Load the image in a new tab and move to it.
2652 addNewTab(imageUrl, true)
2654 // Consume the event.
2658 // Add an open with app entry.
2659 contextMenu.add(R.string.open_with_app).setOnMenuItemClickListener {
2660 // Open the link URL with an external app.
2661 openWithApp(linkUrl)
2663 // Consume the event.
2667 // Add an open with browser entry.
2668 contextMenu.add(R.string.open_with_browser).setOnMenuItemClickListener {
2669 // Open the link URL with an external browser.
2670 openWithBrowser(linkUrl)
2672 // Consume the event.
2676 // Add a view image entry.
2677 contextMenu.add(R.string.view_image).setOnMenuItemClickListener {
2678 // View the image in the current tab.
2679 loadUrl(currentWebView!!, imageUrl)
2681 // Consume the event.
2685 // Add a Save Image entry.
2686 contextMenu.add(R.string.save_image).setOnMenuItemClickListener {
2687 // Check the download preference.
2688 if (downloadWithExternalApp) // Download with an external app.
2689 downloadUrlWithExternalApp(imageUrl)
2690 else // Handle the download inside of Privacy Browser. The dialog will be displayed once the file size and the content disposition have been acquired.
2691 PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, imageUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
2693 // Consume the event.
2697 // Add a copy URL entry.
2698 contextMenu.add(R.string.copy_url).setOnMenuItemClickListener {
2699 // Save the link URL in a clip data.
2700 val srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl)
2702 // Set the clip data as the clipboard's primary clip.
2703 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData)
2705 // Consume the event.
2709 // Add a save URL entry.
2710 contextMenu.add(R.string.save_url).setOnMenuItemClickListener {
2711 // Check the download preference.
2712 if (downloadWithExternalApp) // Download with an external app.
2713 downloadUrlWithExternalApp(linkUrl)
2714 else // Handle the download inside of Privacy Browser. The dialog will be displayed once the file size and the content disposition have been acquired.
2715 PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, linkUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
2717 // Consume the event.
2721 // Add an empty cancel entry, which by default closes the context menu.
2722 contextMenu.add(R.string.cancel)
2725 WebView.HitTestResult.EMAIL_TYPE -> {
2726 // Get the target URL.
2727 linkUrl = hitTestResult.extra
2729 // Set the target URL as the title of the context menu.
2730 contextMenu.setHeaderTitle(linkUrl)
2732 // Add a write email entry.
2733 contextMenu.add(R.string.write_email).setOnMenuItemClickListener {
2734 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2735 val emailIntent = Intent(Intent.ACTION_SENDTO)
2737 // Parse the url and set it as the data for the intent.
2738 emailIntent.data = Uri.parse("mailto:$linkUrl")
2740 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2741 emailIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2745 startActivity(emailIntent)
2746 } catch (exception: ActivityNotFoundException) {
2747 // Display a snackbar.
2748 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
2751 // Consume the event.
2755 // Add a copy email address entry.
2756 contextMenu.add(R.string.copy_email_address).setOnMenuItemClickListener {
2757 // Save the email address in a clip data.
2758 val srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl)
2760 // Set the clip data as the clipboard's primary clip.
2761 clipboardManager.setPrimaryClip(srcEmailTypeClipData)
2763 // Consume the event.
2767 // Add an empty cancel entry, which by default closes the context menu.
2768 contextMenu.add(R.string.cancel)
2773 // The view parameter cannot be removed because it is called from the layout onClick.
2774 fun addTab(@Suppress("UNUSED_PARAMETER")view: View?) {
2775 // Add a new tab with a blank URL.
2779 private fun addNewTab(urlString: String, moveToTab: Boolean) {
2780 // Clear the focus from the URL edit text, so that it will be populated with the information from the new tab.
2781 urlEditText.clearFocus()
2783 // Get the new page number. The page numbers are 0 indexed, so the new page number will match the current count.
2784 val newTabNumber = tabLayout.tabCount
2787 tabLayout.addTab(tabLayout.newTab())
2790 val newTab = tabLayout.getTabAt(newTabNumber)!!
2792 // Set a custom view on the new tab.
2793 newTab.setCustomView(R.layout.tab_custom_view)
2795 // Add the new WebView page.
2796 webViewStateAdapter!!.addPage(newTabNumber, webViewViewPager2, urlString, moveToTab)
2798 // Show the app bar if it is at the bottom of the screen and the new tab is taking focus.
2799 if (bottomAppBar && moveToTab && appBarLayout.translationY != 0f) {
2800 // Animate the bottom app bar onto the screen.
2801 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0f)
2804 objectAnimator.start()
2808 private fun applyAppSettings() {
2809 // 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.
2810 defaultJavaScript = sharedPreferences.getBoolean(getString(R.string.javascript_key), false)
2811 defaultCookies = sharedPreferences.getBoolean(getString(R.string.cookies_key), false)
2812 defaultDomStorage = sharedPreferences.getBoolean(getString(R.string.dom_storage_key), false)
2813 defaultFormData = sharedPreferences.getBoolean(getString(R.string.save_form_data_key), false) // Form data can be removed once the minimum API >= 26.
2814 defaultEasyList = sharedPreferences.getBoolean(getString(R.string.easylist_key), true)
2815 defaultEasyPrivacy = sharedPreferences.getBoolean(getString(R.string.easyprivacy_key), true)
2816 defaultFanboysAnnoyanceList = sharedPreferences.getBoolean(getString(R.string.fanboys_annoyance_list_key), true)
2817 defaultFanboysSocialBlockingList = sharedPreferences.getBoolean(getString(R.string.fanboys_social_blocking_list_key), true)
2818 defaultUltraList = sharedPreferences.getBoolean(getString(R.string.ultralist_key), true)
2819 defaultUltraPrivacy = sharedPreferences.getBoolean(getString(R.string.ultraprivacy_key), true)
2820 defaultBlockAllThirdPartyRequests = sharedPreferences.getBoolean(getString(R.string.block_all_third_party_requests_key), false)
2821 defaultFontSizeString = sharedPreferences.getString(getString(R.string.font_size_key), getString(R.string.font_size_default_value))!!
2822 defaultUserAgentName = sharedPreferences.getString(getString(R.string.user_agent_key), getString(R.string.user_agent_default_value))!!
2823 defaultSwipeToRefresh = sharedPreferences.getBoolean(getString(R.string.swipe_to_refresh_key), true)
2824 defaultWebViewTheme = sharedPreferences.getString(getString(R.string.webview_theme_key), getString(R.string.webview_theme_default_value))!!
2825 defaultWideViewport = sharedPreferences.getBoolean(getString(R.string.wide_viewport_key), true)
2826 defaultDisplayWebpageImages = sharedPreferences.getBoolean(getString(R.string.display_webpage_images_key), true)
2828 // 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.
2829 webViewThemeEntryValuesStringArray = resources.getStringArray(R.array.webview_theme_entry_values)
2831 // 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.
2832 userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item)
2833 userAgentDataArray = resources.getStringArray(R.array.user_agent_data)
2835 // Store the values from the shared preferences in variables.
2836 incognitoModeEnabled = sharedPreferences.getBoolean(getString(R.string.incognito_mode_key), false)
2837 sanitizeTrackingQueries = sharedPreferences.getBoolean(getString(R.string.tracking_queries_key), true)
2838 sanitizeAmpRedirects = sharedPreferences.getBoolean(getString(R.string.amp_redirects_key), true)
2839 proxyMode = sharedPreferences.getString(getString(R.string.proxy_key), getString(R.string.proxy_default_value))!!
2840 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean(getString(R.string.full_screen_browsing_mode_key), false)
2841 hideAppBar = sharedPreferences.getBoolean(getString(R.string.hide_app_bar_key), true)
2842 downloadWithExternalApp = sharedPreferences.getBoolean(getString(R.string.download_with_external_app_key), false)
2843 scrollAppBar = sharedPreferences.getBoolean(getString(R.string.scroll_app_bar_key), true)
2845 // Apply the saved proxy mode if the app has been restarted.
2846 if (savedProxyMode != null) {
2847 // Apply the saved proxy mode.
2848 proxyMode = savedProxyMode!!
2850 // Reset the saved proxy mode.
2851 savedProxyMode = null
2854 // Get the search string.
2855 val searchString = sharedPreferences.getString(getString(R.string.search_key), getString(R.string.search_default_value))!!
2857 // Set the search string, using the custom search URL if specified.
2858 searchURL = if (searchString == getString(R.string.custom_url_item))
2859 sharedPreferences.getString(getString(R.string.search_custom_url_key), getString(R.string.search_custom_url_default_value))!!
2866 // Adjust the layout and scrolling parameters according to the position of the app bar.
2867 if (bottomAppBar) { // The app bar is on the bottom.
2869 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) { // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
2870 // Reset the WebView padding to fill the available space.
2871 swipeRefreshLayout.setPadding(0, 0, 0, 0)
2872 } else { // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
2873 // Move the WebView above the app bar layout.
2874 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
2876 // Show the app bar if it is scrolled off the screen.
2877 if (appBarLayout.translationY != 0f) {
2878 // Animate the bottom app bar onto the screen.
2879 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0f)
2882 objectAnimator.start()
2885 } else { // The app bar is on the top.
2886 // Get the current layout parameters. Using coordinator layout parameters allows the `setBehavior()` command and using app bar layout parameters allows the `setScrollFlags()` command.
2887 val swipeRefreshLayoutParams = swipeRefreshLayout.layoutParams as CoordinatorLayout.LayoutParams
2888 val toolbarLayoutParams = toolbar.layoutParams as AppBarLayout.LayoutParams
2889 val findOnPageLayoutParams = findOnPageLinearLayout.layoutParams as AppBarLayout.LayoutParams
2890 val tabsLayoutParams = tabsLinearLayout.layoutParams as AppBarLayout.LayoutParams
2892 // Add the scrolling behavior to the layout parameters.
2894 // Enable scrolling of the app bar.
2895 swipeRefreshLayoutParams.behavior = AppBarLayout.ScrollingViewBehavior()
2896 toolbarLayoutParams.scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS or AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP
2897 findOnPageLayoutParams.scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS or AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP
2898 tabsLayoutParams.scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS or AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP
2900 // Disable scrolling of the app bar.
2901 swipeRefreshLayoutParams.behavior = null
2902 toolbarLayoutParams.scrollFlags = 0
2903 findOnPageLayoutParams.scrollFlags = 0
2904 tabsLayoutParams.scrollFlags = 0
2906 // Expand the app bar if it is currently collapsed.
2907 appBarLayout.setExpanded(true)
2910 // Set the app bar scrolling for each WebView.
2911 for (i in 0 until webViewStateAdapter!!.itemCount) {
2912 // Get the WebView tab fragment.
2913 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
2915 // Get the fragment view.
2916 val fragmentView = webViewTabFragment.view
2918 // Only modify the WebViews if they exist.
2919 if (fragmentView != null) {
2920 // Get the nested scroll WebView from the tab fragment.
2921 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
2923 // Set the app bar scrolling.
2924 nestedScrollWebView.isNestedScrollingEnabled = scrollAppBar
2929 // Update the full screen browsing mode settings.
2930 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
2931 // Update the visibility of the app bar, which might have changed in the settings.
2933 // Hide the tab linear layout.
2934 tabsLinearLayout.visibility = View.GONE
2936 // Hide the app bar.
2939 // Show the tab linear layout.
2940 tabsLinearLayout.visibility = View.VISIBLE
2942 // Show the app bar.
2946 /* Hide the system bars.
2947 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2948 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
2949 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2950 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
2953 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
2954 @Suppress("DEPRECATION")
2955 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
2956 } else { // Privacy Browser is not in full screen browsing mode.
2957 // 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.
2958 inFullScreenBrowsingMode = false
2960 // Show the tab linear layout.
2961 tabsLinearLayout.visibility = View.VISIBLE
2963 // Show the app bar.
2966 // Remove the `SYSTEM_UI` flags from the root frame layout. The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
2967 @Suppress("DEPRECATION")
2968 rootFrameLayout.systemUiVisibility = 0
2972 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
2973 @SuppressLint("SetJavaScriptEnabled")
2974 private fun applyDomainSettings(nestedScrollWebView: NestedScrollWebView, url: String?, resetTab: Boolean, reloadWebsite: Boolean, loadUrl: Boolean) {
2975 // Store the current URL.
2976 nestedScrollWebView.currentUrl = url!!
2978 // Parse the URL into a URI.
2979 val uri = Uri.parse(url)
2981 // Extract the domain from the URI.
2982 var newHostName = uri.host
2984 // Strings don't like to be null.
2985 if (newHostName == null)
2988 // 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.
2989 if ((nestedScrollWebView.currentDomainName != newHostName) || (newHostName == "")) { // A new domain is being loaded.
2990 // Set the new host name as the current domain name.
2991 nestedScrollWebView.currentDomainName = newHostName
2993 // Reset the ignoring of pinned domain information.
2994 nestedScrollWebView.ignorePinnedDomainInformation = false
2996 // Clear any pinned SSL certificate or IP addresses.
2997 nestedScrollWebView.clearPinnedSslCertificate()
2998 nestedScrollWebView.pinnedIpAddresses = ""
3000 // Reset the favorite icon if specified.
3002 // Initialize the favorite icon.
3003 nestedScrollWebView.initializeFavoriteIcon()
3005 // Get the current page position.
3006 val currentPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
3008 // Get the corresponding tab.
3009 val tab = tabLayout.getTabAt(currentPagePosition)
3011 // Update the tab if it isn't null, which sometimes happens when restarting from the background.
3013 // Get the tab custom view.
3014 val tabCustomView = tab.customView!!
3016 // Get the tab views.
3017 val tabFavoriteIconImageView = tabCustomView.findViewById<ImageView>(R.id.favorite_icon_imageview)
3018 val tabTitleTextView = tabCustomView.findViewById<TextView>(R.id.title_textview)
3020 // Set the default favorite icon as the favorite icon for this tab.
3021 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nestedScrollWebView.getFavoriteIcon(), 64, 64, true))
3023 // Set the loading title text.
3024 tabTitleTextView.setText(R.string.loading)
3028 // Initialize the domain name in database variable.
3029 var domainNameInDatabase: String? = null
3031 // Check the hostname against the domain settings set.
3032 if (domainsSettingsSet.contains(newHostName)) { // The hostname is contained in the domain settings set.
3033 // Record the domain name in the database.
3034 domainNameInDatabase = newHostName
3036 // Set the domain settings applied tracker to true.
3037 nestedScrollWebView.domainSettingsApplied = true
3038 } else { // The hostname is not contained in the domain settings set.
3039 // Set the domain settings applied tracker to false.
3040 nestedScrollWebView.domainSettingsApplied = false
3043 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3044 while (!nestedScrollWebView.domainSettingsApplied && newHostName!!.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the hostname.
3045 if (domainsSettingsSet.contains("*.$newHostName")) { // Check the host name prepended by `*.`.
3046 // Set the domain settings applied tracker to true.
3047 nestedScrollWebView.domainSettingsApplied = true
3049 // Store the applied domain names as it appears in the database.
3050 domainNameInDatabase = "*.$newHostName"
3053 // Strip out the lowest subdomain of of the host name.
3054 newHostName = newHostName.substring(newHostName.indexOf(".") + 1)
3057 // Apply either the domain settings or the default settings.
3058 if (nestedScrollWebView.domainSettingsApplied) { // The url has custom domain settings.
3059 // Get a cursor for the current host.
3060 val currentDomainSettingsCursor = domainsDatabaseHelper!!.getCursorForDomainName(domainNameInDatabase!!)
3062 // Move to the first position.
3063 currentDomainSettingsCursor.moveToFirst()
3065 // Get the settings from the cursor.
3066 nestedScrollWebView.domainSettingsDatabaseId = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ID))
3067 val javaScriptInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_JAVASCRIPT))
3068 val cookiesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(COOKIES))
3069 val domStorageInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_DOM_STORAGE))
3070 val formDataInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_FORM_DATA)) // Form data can be removed once the minimum API >= 26.
3071 val easyListInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_EASYLIST))
3072 val easyPrivacyInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_EASYPRIVACY))
3073 val fanboysAnnoyanceListInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_FANBOYS_ANNOYANCE_LIST))
3074 val fanboysSocialBlockingListInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST))
3075 val ultraListInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.ULTRALIST))
3076 val ultraPrivacyInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_ULTRAPRIVACY))
3077 val blockAllThirdPartyRequestsInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.BLOCK_ALL_THIRD_PARTY_REQUESTS))
3078 val userAgentName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.USER_AGENT))
3079 val fontSize = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(FONT_SIZE))
3080 val swipeToRefreshInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(SWIPE_TO_REFRESH))
3081 val webViewThemeInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(WEBVIEW_THEME))
3082 val wideViewportInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(WIDE_VIEWPORT))
3083 val displayWebpageImagesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DISPLAY_IMAGES))
3084 val pinnedSslCertificate = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(PINNED_SSL_CERTIFICATE)) == 1)
3085 val pinnedSslIssuedToCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_TO_COMMON_NAME))
3086 val pinnedSslIssuedToOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_TO_ORGANIZATION))
3087 val pinnedSslIssuedToUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_TO_ORGANIZATIONAL_UNIT))
3088 val pinnedSslIssuedByCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_BY_COMMON_NAME))
3089 val pinnedSslIssuedByOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_BY_ORGANIZATION))
3090 val pinnedSslIssuedByUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_BY_ORGANIZATIONAL_UNIT))
3091 val pinnedSslStartDate = Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.SSL_START_DATE)))
3092 val pinnedSslEndDate = Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.SSL_END_DATE)))
3093 val pinnedIpAddresses = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(PINNED_IP_ADDRESSES)) == 1)
3094 val pinnedHostIpAddresses = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(IP_ADDRESSES))
3096 // Close the current host domain settings cursor.
3097 currentDomainSettingsCursor.close()
3099 // Set the JavaScript status.
3100 when (javaScriptInt) {
3101 SYSTEM_DEFAULT -> nestedScrollWebView.settings.javaScriptEnabled = defaultJavaScript
3102 ENABLED -> nestedScrollWebView.settings.javaScriptEnabled = true
3103 DISABLED -> nestedScrollWebView.settings.javaScriptEnabled = false
3106 // Store the cookies status.
3108 SYSTEM_DEFAULT -> nestedScrollWebView.acceptCookies = defaultCookies
3109 ENABLED -> nestedScrollWebView.acceptCookies = true
3110 DISABLED -> nestedScrollWebView.acceptCookies = false
3113 // Apply the cookies status.
3114 cookieManager.setAcceptCookie(nestedScrollWebView.acceptCookies)
3116 // Set the DOM storage status.
3117 when (domStorageInt) {
3118 SYSTEM_DEFAULT -> nestedScrollWebView.settings.domStorageEnabled = defaultDomStorage
3119 ENABLED -> nestedScrollWebView.settings.domStorageEnabled = true
3120 DISABLED -> nestedScrollWebView.settings.domStorageEnabled = false
3123 // Apply the form data setting if the API < 26.
3124 @Suppress("DEPRECATION")
3125 if (Build.VERSION.SDK_INT < 26) {
3126 // Set the form data status.
3127 when (formDataInt) {
3128 SYSTEM_DEFAULT -> nestedScrollWebView.settings.saveFormData = defaultFormData
3129 ENABLED -> nestedScrollWebView.settings.saveFormData = true
3130 DISABLED -> nestedScrollWebView.settings.saveFormData = false
3134 // Set the EasyList status.
3135 when (easyListInt) {
3136 SYSTEM_DEFAULT -> nestedScrollWebView.easyListEnabled = defaultEasyList
3137 ENABLED -> nestedScrollWebView.easyListEnabled = true
3138 DISABLED -> nestedScrollWebView.easyListEnabled = false
3141 // Set the EasyPrivacy status.
3142 when (easyPrivacyInt) {
3143 SYSTEM_DEFAULT -> nestedScrollWebView.easyPrivacyEnabled = defaultEasyPrivacy
3144 ENABLED -> nestedScrollWebView.easyPrivacyEnabled = true
3145 DISABLED -> nestedScrollWebView.easyPrivacyEnabled = false
3148 // Set the Fanboy's Annoyance List status.
3149 when (fanboysAnnoyanceListInt) {
3150 SYSTEM_DEFAULT -> nestedScrollWebView.fanboysAnnoyanceListEnabled = defaultFanboysAnnoyanceList
3151 ENABLED -> nestedScrollWebView.fanboysAnnoyanceListEnabled = true
3152 DISABLED -> nestedScrollWebView.fanboysAnnoyanceListEnabled = false
3155 // Set the Fanboy's Social Blocking List status.
3156 when (fanboysSocialBlockingListInt) {
3157 SYSTEM_DEFAULT -> nestedScrollWebView.fanboysSocialBlockingListEnabled = defaultFanboysSocialBlockingList
3158 ENABLED -> nestedScrollWebView.fanboysSocialBlockingListEnabled = true
3159 DISABLED -> nestedScrollWebView.fanboysSocialBlockingListEnabled = false
3162 // Set the UltraList status.
3163 when (ultraListInt) {
3164 SYSTEM_DEFAULT -> nestedScrollWebView.ultraListEnabled = defaultUltraList
3165 ENABLED -> nestedScrollWebView.ultraListEnabled = true
3166 DISABLED -> nestedScrollWebView.ultraListEnabled = false
3169 // Set the UltraPrivacy status.
3170 when (ultraPrivacyInt) {
3171 SYSTEM_DEFAULT -> nestedScrollWebView.ultraPrivacyEnabled = defaultUltraPrivacy
3172 ENABLED -> nestedScrollWebView.ultraPrivacyEnabled = true
3173 DISABLED -> nestedScrollWebView.ultraPrivacyEnabled = false
3176 // Set the block all third-party requests status.
3177 when (blockAllThirdPartyRequestsInt) {
3178 SYSTEM_DEFAULT -> nestedScrollWebView.blockAllThirdPartyRequests = defaultBlockAllThirdPartyRequests
3179 ENABLED -> nestedScrollWebView.blockAllThirdPartyRequests = true
3180 DISABLED -> nestedScrollWebView.blockAllThirdPartyRequests = false
3183 // Set the user agent.
3184 if (userAgentName == getString(R.string.system_default_user_agent)) { // Use the system default user agent.
3185 // Set the user agent according to the system default.
3186 when (val defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName)) {
3187 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3188 UNRECOGNIZED_USER_AGENT -> nestedScrollWebView.settings.userAgentString = defaultUserAgentName
3190 // Set the user agent to `""`, which uses the default value.
3191 SETTINGS_WEBVIEW_DEFAULT_USER_AGENT -> nestedScrollWebView.settings.userAgentString = ""
3193 // Set the default custom user agent.
3194 SETTINGS_CUSTOM_USER_AGENT -> nestedScrollWebView.settings.userAgentString =
3195 sharedPreferences.getString(getString(R.string.custom_user_agent_key), getString(R.string.custom_user_agent_default_value))
3197 // Get the user agent string from the user agent data array
3198 else -> nestedScrollWebView.settings.userAgentString = userAgentDataArray[defaultUserAgentArrayPosition]
3200 } else { // Set the user agent according to the stored name.
3201 // Set the user agent.
3202 when (val userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName)) {
3203 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3204 UNRECOGNIZED_USER_AGENT ->
3205 nestedScrollWebView.settings.userAgentString = userAgentName
3207 // Set the user agent to `""`, which uses the default value.
3208 SETTINGS_WEBVIEW_DEFAULT_USER_AGENT ->
3209 nestedScrollWebView.settings.userAgentString = ""
3211 // Get the user agent string from the user agent data array.
3213 nestedScrollWebView.settings.userAgentString = userAgentDataArray[userAgentArrayPosition]
3217 // Apply the font size.
3218 try { // Try the specified font size to see if it is valid.
3219 if (fontSize == 0) { // Apply the default font size.
3220 // Set the font size from the value in the app settings.
3221 nestedScrollWebView.settings.textZoom = defaultFontSizeString.toInt()
3222 } else { // Apply the font size from domain settings.
3223 nestedScrollWebView.settings.textZoom = fontSize
3225 } catch (exception: Exception) { // The specified font size is invalid
3226 // Set the font size to be 100%
3227 nestedScrollWebView.settings.textZoom = 100
3230 // Set swipe to refresh.
3231 when (swipeToRefreshInt) {
3233 // Store the swipe to refresh status in the nested scroll WebView.
3234 nestedScrollWebView.swipeToRefresh = defaultSwipeToRefresh
3236 // Update the swipe refresh layout.
3237 if (defaultSwipeToRefresh) { // Swipe to refresh is enabled.
3238 // 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).
3239 if (currentWebView != null) {
3240 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
3241 swipeRefreshLayout.isEnabled = (currentWebView!!.scrollY == 0)
3243 } else { // Swipe to refresh is disabled.
3244 // Disable the swipe refresh layout.
3245 swipeRefreshLayout.isEnabled = false
3250 // Store the swipe to refresh status in the nested scroll WebView.
3251 nestedScrollWebView.swipeToRefresh = true
3253 // 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).
3254 if (currentWebView != null) {
3255 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
3256 swipeRefreshLayout.isEnabled = (currentWebView!!.scrollY == 0)
3261 // Store the swipe to refresh status in the nested scroll WebView.
3262 nestedScrollWebView.swipeToRefresh = false
3264 // Disable swipe to refresh.
3265 swipeRefreshLayout.isEnabled = false
3269 // Set the WebView theme if algorithmic darkening is supported.
3270 if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {
3271 // Set the WebView theme.
3272 when (webViewThemeInt) {
3273 // Set the WebView theme.
3275 when (defaultWebViewTheme) {
3276 // The light theme is selected. Turn off algorithmic darkening.
3277 webViewThemeEntryValuesStringArray[1] -> WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
3279 // The dark theme is selected. Turn on algorithmic darkening.
3280 webViewThemeEntryValuesStringArray[2] -> WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
3282 // The system default theme is selected.
3284 // Get the current system theme status.
3285 val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
3287 // Set the algorithmic darkening according to the current system theme status.
3288 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, currentThemeStatus == Configuration.UI_MODE_NIGHT_YES)
3292 // Turn off algorithmic darkening.
3293 LIGHT_THEME -> WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
3295 // Turn on algorithmic darkening.
3296 DARK_THEME -> WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
3300 // Set the wide viewport status.
3301 when (wideViewportInt) {
3302 SYSTEM_DEFAULT -> nestedScrollWebView.settings.useWideViewPort = defaultWideViewport
3303 ENABLED -> nestedScrollWebView.settings.useWideViewPort = true
3304 DISABLED -> nestedScrollWebView.settings.useWideViewPort = false
3307 // Set the display webpage images status.
3308 when (displayWebpageImagesInt) {
3309 SYSTEM_DEFAULT -> nestedScrollWebView.settings.loadsImagesAutomatically = defaultDisplayWebpageImages
3310 ENABLED -> nestedScrollWebView.settings.loadsImagesAutomatically = true
3311 DISABLED -> nestedScrollWebView.settings.loadsImagesAutomatically = false
3314 // If there is a pinned SSL certificate, store it in the WebView.
3315 if (pinnedSslCertificate)
3316 nestedScrollWebView.setPinnedSslCertificate(pinnedSslIssuedToCName, pinnedSslIssuedToOName, pinnedSslIssuedToUName, pinnedSslIssuedByCName, pinnedSslIssuedByOName, pinnedSslIssuedByUName,
3317 pinnedSslStartDate, pinnedSslEndDate)
3319 // If there is a pinned IP address, store it in the WebView.
3320 if (pinnedIpAddresses)
3321 nestedScrollWebView.pinnedIpAddresses = pinnedHostIpAddresses
3323 // Set a background on the URL relative layout to indicate that custom domain settings are being used.
3324 urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.drawable.domain_settings_url_background)
3325 } else { // The new URL does not have custom domain settings. Load the defaults.
3326 // Store the values from the shared preferences.
3327 nestedScrollWebView.settings.javaScriptEnabled = defaultJavaScript
3328 nestedScrollWebView.acceptCookies = defaultCookies
3329 nestedScrollWebView.settings.domStorageEnabled = defaultDomStorage
3330 nestedScrollWebView.easyListEnabled = defaultEasyList
3331 nestedScrollWebView.easyPrivacyEnabled = defaultEasyPrivacy
3332 nestedScrollWebView.fanboysAnnoyanceListEnabled = defaultFanboysAnnoyanceList
3333 nestedScrollWebView.fanboysSocialBlockingListEnabled = defaultFanboysSocialBlockingList
3334 nestedScrollWebView.ultraListEnabled = defaultUltraList
3335 nestedScrollWebView.ultraPrivacyEnabled = defaultUltraPrivacy
3336 nestedScrollWebView.blockAllThirdPartyRequests = defaultBlockAllThirdPartyRequests
3338 // Apply the default cookie setting.
3339 cookieManager.setAcceptCookie(nestedScrollWebView.acceptCookies)
3341 // Apply the form data setting if the API < 26.
3342 if (Build.VERSION.SDK_INT < 26)
3343 @Suppress("DEPRECATION")
3344 nestedScrollWebView.settings.saveFormData = defaultFormData
3346 // Apply the default font size setting.
3348 // Try to set the font size from the value in the app settings.
3349 nestedScrollWebView.settings.textZoom = defaultFontSizeString.toInt()
3350 } catch (exception: Exception) {
3351 // If the app settings value is invalid, set the font size to 100%.
3352 nestedScrollWebView.settings.textZoom = 100
3355 // Store the swipe to refresh status in the nested scroll WebView.
3356 nestedScrollWebView.swipeToRefresh = defaultSwipeToRefresh
3358 // Update the swipe refresh layout.
3359 if (defaultSwipeToRefresh) { // Swipe to refresh is enabled.
3360 // 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).
3361 if (currentWebView != null) {
3362 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
3363 swipeRefreshLayout.isEnabled = currentWebView!!.scrollY == 0
3365 } else { // Swipe to refresh is disabled.
3366 // Disable the swipe refresh layout.
3367 swipeRefreshLayout.isEnabled = false
3370 // Reset the domain settings database ID.
3371 nestedScrollWebView.domainSettingsDatabaseId = -1
3373 // Set the user agent.
3374 when (val userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName)) {
3375 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3376 UNRECOGNIZED_USER_AGENT -> nestedScrollWebView.settings.userAgentString = defaultUserAgentName
3378 // Set the user agent to `""`, which uses the default value.
3379 SETTINGS_WEBVIEW_DEFAULT_USER_AGENT -> nestedScrollWebView.settings.userAgentString = ""
3381 // Set the default custom user agent.
3382 SETTINGS_CUSTOM_USER_AGENT -> nestedScrollWebView.settings.userAgentString =
3383 sharedPreferences.getString(getString(R.string.custom_user_agent_key), getString(R.string.custom_user_agent_default_value))
3385 // Get the user agent string from the user agent data array
3386 else -> nestedScrollWebView.settings.userAgentString = userAgentDataArray[userAgentArrayPosition]
3389 // Set the WebView theme if algorithmic darkening is supported.
3390 if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {
3391 // Set the WebView theme.
3392 when (defaultWebViewTheme) {
3393 // The light theme is selected. Turn off algorithmic darkening.
3394 webViewThemeEntryValuesStringArray[1] -> WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
3396 // The dark theme is selected. Turn on algorithmic darkening.
3397 webViewThemeEntryValuesStringArray[2] -> WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
3399 // The system default theme is selected. Get the current system theme status.
3401 // Get the current theme status.
3402 val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
3404 // Set the algorithmic darkening according to the current system theme status.
3405 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, currentThemeStatus == Configuration.UI_MODE_NIGHT_YES)
3410 // Set the viewport.
3411 nestedScrollWebView.settings.useWideViewPort = defaultWideViewport
3413 // Set the loading of webpage images.
3414 nestedScrollWebView.settings.loadsImagesAutomatically = defaultDisplayWebpageImages
3416 // Set a transparent background on the URL relative layout.
3417 urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.color.transparent)
3420 // Update the privacy icons.
3421 updatePrivacyIcons(true)
3424 // Reload the website if returning from the Domains activity.
3426 nestedScrollWebView.reload()
3428 // Disable the wide viewport if the source is being viewed.
3429 if (url.startsWith("view-source:"))
3430 nestedScrollWebView.settings.useWideViewPort = false
3432 // 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.
3434 nestedScrollWebView.loadUrl(url)
3437 private fun applyProxy(reloadWebViews: Boolean) {
3438 // Set the proxy according to the mode.
3439 proxyHelper.setProxy(applicationContext, appBarLayout, proxyMode)
3441 // Reset the waiting for proxy tracker.
3442 waitingForProxy = false
3446 ProxyHelper.NONE -> {
3447 // Initialize a color background typed value.
3448 val colorBackgroundTypedValue = TypedValue()
3450 // Get the color background from the theme.
3451 theme.resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true)
3453 // Get the color background int from the typed value.
3454 val colorBackgroundInt = colorBackgroundTypedValue.data
3456 // Set the default app bar layout background.
3457 appBarLayout.setBackgroundColor(colorBackgroundInt)
3460 ProxyHelper.TOR -> {
3461 // Set the app bar background to indicate proxying is enabled.
3462 appBarLayout.setBackgroundResource(R.color.blue_background)
3464 // Check to see if Orbot is installed.
3466 // Get the package manager.
3467 val packageManager = packageManager
3469 // Check to see if Orbot is in the list. This will throw an error and drop to the catch section if it isn't installed. The deprecated method must be used until the minimum API >= 33.
3470 @Suppress("DEPRECATION")
3471 packageManager.getPackageInfo("org.torproject.android", 0)
3473 // Check to see if the proxy is ready.
3474 if (orbotStatus != ProxyHelper.ORBOT_STATUS_ON) { // Orbot is not ready.
3475 // Set the waiting for proxy status.
3476 waitingForProxy = true
3478 // Show the waiting for proxy dialog if it isn't already displayed.
3479 if (supportFragmentManager.findFragmentByTag(getString(R.string.waiting_for_proxy_dialog)) == null) {
3480 // Get a handle for the waiting for proxy alert dialog.
3481 val waitingForProxyDialogFragment = WaitingForProxyDialog()
3483 // Try to show the dialog. Sometimes the window is not yet active if returning from Settings.
3485 // Show the waiting for proxy alert dialog.
3486 waitingForProxyDialogFragment.show(supportFragmentManager, getString(R.string.waiting_for_proxy_dialog))
3487 } catch (waitingForTorException: Exception) {
3488 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
3489 pendingDialogsArrayList.add(PendingDialogDataClass(waitingForProxyDialogFragment, getString(R.string.waiting_for_proxy_dialog)))
3493 } catch (exception: PackageManager.NameNotFoundException) { // Orbot is not installed.
3494 // Show the Orbot not installed dialog if it is not already displayed.
3495 if (supportFragmentManager.findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
3496 // Get a handle for the Orbot not installed alert dialog.
3497 val orbotNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode)
3499 // Try to show the dialog. Sometimes the window is not yet active if returning from Settings.
3501 // Display the Orbot not installed alert dialog.
3502 orbotNotInstalledDialogFragment.show(supportFragmentManager, getString(R.string.proxy_not_installed_dialog))
3503 } catch (orbotNotInstalledException: Exception) {
3504 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
3505 pendingDialogsArrayList.add(PendingDialogDataClass(orbotNotInstalledDialogFragment, getString(R.string.proxy_not_installed_dialog)))
3511 ProxyHelper.I2P -> {
3512 // Set the app bar background to indicate proxying is enabled.
3513 appBarLayout.setBackgroundResource(R.color.blue_background)
3515 // Check to see if I2P is installed.
3517 // 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.
3518 // The deprecated method must be used until the minimum API >= 33.
3519 @Suppress("DEPRECATION")
3520 packageManager.getPackageInfo("net.i2p.android.router", 0)
3521 } catch (fdroidException: PackageManager.NameNotFoundException) { // The F-Droid flavor is not installed.
3523 // 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.
3524 // The deprecated method must be used until the minimum API >= 33.
3525 @Suppress("DEPRECATION")
3526 packageManager.getPackageInfo("net.i2p.android", 0)
3527 } catch (googlePlayException: PackageManager.NameNotFoundException) { // The Google Play flavor is not installed.
3528 // Sow the I2P not installed dialog if it is not already displayed.
3529 if (supportFragmentManager.findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
3530 // Get a handle for the waiting for proxy alert dialog.
3531 val i2pNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode)
3533 // Try to show the dialog. Sometimes the window is not yet active if returning from Settings.
3535 // Display the I2P not installed alert dialog.
3536 i2pNotInstalledDialogFragment.show(supportFragmentManager, getString(R.string.proxy_not_installed_dialog))
3537 } catch (i2pNotInstalledException: Exception) {
3538 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
3539 pendingDialogsArrayList.add(PendingDialogDataClass(i2pNotInstalledDialogFragment, getString(R.string.proxy_not_installed_dialog)))
3546 ProxyHelper.CUSTOM ->
3547 // Set the app bar background to indicate proxying is enabled.
3548 appBarLayout.setBackgroundResource(R.color.blue_background)
3551 // Reload the WebViews if requested and not waiting for the proxy.
3552 if (reloadWebViews && !waitingForProxy) {
3553 // Reload the WebViews.
3554 for (i in 0 until webViewStateAdapter!!.itemCount) {
3555 // Get the WebView tab fragment.
3556 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
3558 // Get the fragment view.
3559 val fragmentView = webViewTabFragment.view
3561 // Only reload the WebViews if they exist.
3562 if (fragmentView != null) {
3563 // Get the nested scroll WebView from the tab fragment.
3564 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
3566 // Reload the WebView.
3567 nestedScrollWebView.reload()
3573 // The view parameter cannot be removed because it is called from the layout onClick.
3574 fun bookmarksBack(@Suppress("UNUSED_PARAMETER")view: View?) {
3575 if (currentBookmarksFolderId == HOME_FOLDER_ID) { // The home folder is displayed.
3576 // close the bookmarks drawer.
3577 drawerLayout.closeDrawer(GravityCompat.END)
3578 } else { // A subfolder is displayed.
3579 // Set the former parent folder as the current folder.
3580 currentBookmarksFolderId = bookmarksDatabaseHelper!!.getParentFolderId(currentBookmarksFolderId)
3582 // Load the new folder.
3583 loadBookmarksFolder()
3587 private fun clearAndExit() {
3588 // Close the bookmarks cursor if it exists.
3589 bookmarksCursor?.close()
3591 // Close the databases helpers if they exist.
3592 bookmarksDatabaseHelper?.close()
3593 domainsDatabaseHelper?.close()
3595 // Get the status of the clear everything preference.
3596 val clearEverything = sharedPreferences.getBoolean(getString(R.string.clear_everything_key), true)
3598 // Get a handle for the runtime.
3599 val runtime = Runtime.getRuntime()
3601 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
3602 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
3603 val privateDataDirectoryString = applicationInfo.dataDir
3606 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_cookies_key), true)) {
3607 // Ass the cookie manager to delete all the cookies.
3608 cookieManager.removeAllCookies(null)
3610 // Ask the cookie manager to flush the cookie database.
3611 cookieManager.flush()
3613 // Manually delete the cookies database, as the cookie manager sometimes will not flush its changes to disk before system exit is run.
3615 // Two commands must be used because `Runtime.exec()` does not like `*`.
3616 val deleteCookiesProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/Cookies")
3617 val deleteCookiesJournalProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/Cookies-journal")
3619 // Wait until the processes have finished.
3620 deleteCookiesProcess.waitFor()
3621 deleteCookiesJournalProcess.waitFor()
3622 } catch (exception: Exception) {
3623 // Do nothing if an error is thrown.
3627 // Clear DOM storage.
3628 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_dom_storage_key), true)) {
3629 // Ask web storage to clear the DOM storage.
3630 WebStorage.getInstance().deleteAllData()
3632 // Manually delete the DOM storage files and directories, as web storage sometimes will not flush its changes to disk before system exit is run.
3634 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
3635 val deleteLocalStorageProcess = runtime.exec(arrayOf("rm", "-rf", "$privateDataDirectoryString/app_webview/Local Storage/"))
3637 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
3638 val deleteIndexProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview/IndexedDB")
3639 val deleteQuotaManagerProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/QuotaManager")
3640 val deleteQuotaManagerJournalProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/QuotaManager-journal")
3641 val deleteDatabaseProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview/databases")
3643 // Wait until the processes have finished.
3644 deleteLocalStorageProcess.waitFor()
3645 deleteIndexProcess.waitFor()
3646 deleteQuotaManagerProcess.waitFor()
3647 deleteQuotaManagerJournalProcess.waitFor()
3648 deleteDatabaseProcess.waitFor()
3649 } catch (exception: Exception) {
3650 // Do nothing if an error is thrown.
3654 // Clear form data if the API < 26.
3655 if (Build.VERSION.SDK_INT < 26 && (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_form_data_key), true))) {
3656 // Ask the WebView database to clear the form data.
3657 @Suppress("DEPRECATION")
3658 WebViewDatabase.getInstance(this).clearFormData()
3660 // Manually delete the form data database, as the WebView database sometimes will not flush its changes to disk before system exit is run.
3662 // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
3663 val deleteWebDataProcess = runtime.exec(arrayOf("rm", "-f", "$privateDataDirectoryString/app_webview/Web Data"))
3664 val deleteWebDataJournalProcess = runtime.exec(arrayOf("rm", "-f", "$privateDataDirectoryString/app_webview/Web Data-journal"))
3666 // Wait until the processes have finished.
3667 deleteWebDataProcess.waitFor()
3668 deleteWebDataJournalProcess.waitFor()
3669 } catch (exception: Exception) {
3670 // Do nothing if an error is thrown.
3674 // Clear the logcat.
3675 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_logcat_key), true)) {
3677 // Clear the logcat. `-c` clears the logcat. `-b all` clears all the buffers (instead of just crash, main, and system).
3678 val process = Runtime.getRuntime().exec("logcat -b all -c")
3680 // Wait for the process to finish.
3682 } catch (exception: IOException) {
3684 } catch (exception: InterruptedException) {
3690 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_cache_key), true)) {
3691 // Clear the cache from each WebView.
3692 for (i in 0 until webViewStateAdapter!!.itemCount) {
3693 // Get the WebView tab fragment.
3694 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
3696 // Get the WebView fragment view.
3697 val webViewFragmentView = webViewTabFragment.view
3699 // Only clear the cache if the WebView exists.
3700 if (webViewFragmentView != null) {
3701 // Get the nested scroll WebView from the tab fragment.
3702 val nestedScrollWebView = webViewFragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
3704 // Clear the cache for this WebView.
3705 nestedScrollWebView.clearCache(true)
3709 // Manually delete the cache directories.
3711 // Delete the main cache directory.
3712 val deleteCacheProcess = runtime.exec("rm -rf $privateDataDirectoryString/cache")
3714 // Delete the secondary `Service Worker` cache directory.
3715 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
3716 val deleteServiceWorkerProcess = runtime.exec(arrayOf("rm", "-rf", "$privateDataDirectoryString/app_webview/Default/Service Worker/"))
3718 // Wait until the processes have finished.
3719 deleteCacheProcess.waitFor()
3720 deleteServiceWorkerProcess.waitFor()
3721 } catch (exception: Exception) {
3722 // Do nothing if an error is thrown.
3726 // Wipe out each WebView.
3727 for (i in 0 until webViewStateAdapter!!.itemCount) {
3728 // Get the WebView tab fragment.
3729 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
3731 // Get the WebView frame layout.
3732 val webViewFrameLayout = webViewTabFragment.view as FrameLayout?
3734 // Only wipe out the WebView if it exists.
3735 if (webViewFrameLayout != null) {
3736 // Get the nested scroll WebView from the tab fragment.
3737 val nestedScrollWebView = webViewFrameLayout.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
3739 // Clear SSL certificate preferences for this WebView.
3740 nestedScrollWebView.clearSslPreferences()
3742 // Clear the back/forward history for this WebView.
3743 nestedScrollWebView.clearHistory()
3745 // Remove all the views from the frame layout.
3746 webViewFrameLayout.removeAllViews()
3748 // Destroy the internal state of the WebView.
3749 nestedScrollWebView.destroy()
3753 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
3754 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
3755 if (clearEverything) {
3757 // Delete the folder.
3758 val deleteAppWebviewProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview")
3760 // Wait until the process has finished.
3761 deleteAppWebviewProcess.waitFor()
3762 } catch (exception: Exception) {
3763 // Do nothing if an error is thrown.
3767 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
3768 finishAndRemoveTask()
3770 // Remove the terminated program from RAM. The status code is `0`.
3774 // The view parameter cannot be removed because it is called from the layout onClick.
3775 fun closeFindOnPage(@Suppress("UNUSED_PARAMETER")view: View?) {
3776 // Delete the contents of the find on page edit text.
3777 findOnPageEditText.text = null
3779 // Clear the highlighted phrases if the WebView is not null.
3780 currentWebView?.clearMatches()
3782 // Hide the find on page linear layout.
3783 findOnPageLinearLayout.visibility = View.GONE
3785 // Show the toolbar.
3786 toolbar.visibility = View.VISIBLE
3788 // Get a handle for the input method manager.
3789 val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
3791 // Hide the keyboard.
3792 inputMethodManager.hideSoftInputFromWindow(toolbar.windowToken, 0)
3795 // The view parameter cannot be removed because it is called from the layout onClick.
3796 fun closeTab(@Suppress("UNUSED_PARAMETER")view: View?) {
3797 // Run the command according to the number of tabs.
3798 if (tabLayout.tabCount > 1) { // There is more than one tab open.
3799 // Get the current tab number.
3800 val currentTabNumber = tabLayout.selectedTabPosition
3802 // Delete the current tab.
3803 tabLayout.removeTabAt(currentTabNumber)
3805 // 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,
3806 // meaning that the current WebView must be reset. Otherwise it will happen automatically as the selected tab number changes.
3807 if (webViewStateAdapter!!.deletePage(currentTabNumber, webViewViewPager2))
3808 setCurrentWebView(currentTabNumber)
3809 } else { // There is only one tab open.
3814 override fun createBookmark(dialogFragment: DialogFragment, favoriteIconBitmap: Bitmap) {
3816 val dialog = dialogFragment.dialog!!
3818 // Get the views from the dialog fragment.
3819 val createBookmarkNameEditText = dialog.findViewById<EditText>(R.id.create_bookmark_name_edittext)
3820 val createBookmarkUrlEditText = dialog.findViewById<EditText>(R.id.create_bookmark_url_edittext)
3822 // Extract the strings from the edit texts.
3823 val bookmarkNameString = createBookmarkNameEditText.text.toString()
3824 val bookmarkUrlString = createBookmarkUrlEditText.text.toString()
3826 // Create a favorite icon byte array output stream.
3827 val favoriteIconByteArrayOutputStream = ByteArrayOutputStream()
3829 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
3830 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream)
3832 // Convert the favorite icon byte array stream to a byte array.
3833 val favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray()
3835 // Display the new bookmark below the current items in the (0 indexed) list.
3836 val newBookmarkDisplayOrder = bookmarksListView.count
3838 // Create the bookmark.
3839 bookmarksDatabaseHelper!!.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolderId, newBookmarkDisplayOrder, favoriteIconByteArray)
3841 // Update the bookmarks cursor with the current contents of this folder.
3842 bookmarksCursor = bookmarksDatabaseHelper!!.getBookmarksByDisplayOrder(currentBookmarksFolderId)
3844 // Update the list view.
3845 bookmarksCursorAdapter.changeCursor(bookmarksCursor)
3847 // Scroll to the new bookmark.
3848 bookmarksListView.setSelection(newBookmarkDisplayOrder)
3851 override fun createBookmarkFolder(dialogFragment: DialogFragment, favoriteIconBitmap: Bitmap) {
3853 val dialog = dialogFragment.dialog!!
3855 // Get handles for the views in the dialog fragment.
3856 val folderNameEditText = dialog.findViewById<EditText>(R.id.folder_name_edittext)
3857 val defaultIconRadioButton = dialog.findViewById<RadioButton>(R.id.default_icon_radiobutton)
3858 val defaultIconImageView = dialog.findViewById<ImageView>(R.id.default_icon_imageview)
3860 // Get new folder name string.
3861 val folderNameString = folderNameEditText.text.toString()
3863 // Set the folder icon bitmap according to the dialog.
3864 val folderIconBitmap: Bitmap = if (defaultIconRadioButton.isChecked) { // Use the default folder icon.
3865 // Get the default folder icon drawable.
3866 val folderIconDrawable = defaultIconImageView.drawable
3868 // Convert the folder icon drawable to a bitmap drawable.
3869 val folderIconBitmapDrawable = folderIconDrawable as BitmapDrawable
3871 // Convert the folder icon bitmap drawable to a bitmap.
3872 folderIconBitmapDrawable.bitmap
3873 } else { // Use the WebView favorite icon.
3874 // Copy the favorite icon bitmap to the folder icon bitmap.
3878 // Create a folder icon byte array output stream.
3879 val folderIconByteArrayOutputStream = ByteArrayOutputStream()
3881 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
3882 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream)
3884 // Convert the folder icon byte array stream to a byte array.
3885 val folderIconByteArray = folderIconByteArrayOutputStream.toByteArray()
3887 // Move all the bookmarks down one in the display order.
3888 for (i in 0 until bookmarksListView.count) {
3889 // Get the bookmark database id.
3890 val databaseId = bookmarksListView.getItemIdAtPosition(i).toInt()
3892 // Move the bookmark down one slot.
3893 bookmarksDatabaseHelper!!.updateDisplayOrder(databaseId, i + 1)
3896 // Create the folder, which will be placed at the top of the list view.
3897 bookmarksDatabaseHelper!!.createFolder(folderNameString, currentBookmarksFolderId, folderIconByteArray)
3899 // Update the bookmarks cursor with the current contents of this folder.
3900 bookmarksCursor = bookmarksDatabaseHelper!!.getBookmarksByDisplayOrder(currentBookmarksFolderId)
3902 // Update the list view.
3903 bookmarksCursorAdapter.changeCursor(bookmarksCursor)
3905 // Scroll to the new folder.
3906 bookmarksListView.setSelection(0)
3909 private fun downloadUrlWithExternalApp(url: String) {
3910 // Create a download intent. Not specifying the action type will display the maximum number of options.
3911 val downloadIntent = Intent()
3913 // Set the URI and the mime type.
3914 downloadIntent.setDataAndType(Uri.parse(url), "text/html")
3916 // Flag the intent to open in a new task.
3917 downloadIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
3919 // Show the chooser.
3920 startActivity(Intent.createChooser(downloadIntent, getString(R.string.download_with_external_app)))
3923 private fun exitFullScreenVideo() {
3924 // Re-enable the screen timeout.
3925 fullScreenVideoFrameLayout.keepScreenOn = false
3927 // Unset the full screen video flag.
3928 displayingFullScreenVideo = false
3930 // Remove all the views from the full screen video frame layout.
3931 fullScreenVideoFrameLayout.removeAllViews()
3933 // Hide the full screen video frame layout.
3934 fullScreenVideoFrameLayout.visibility = View.GONE
3936 // Enable the sliding drawers.
3937 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED)
3939 // Show the coordinator layout.
3940 coordinatorLayout.visibility = View.VISIBLE
3942 // Apply the appropriate full screen mode flags.
3943 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
3944 // Hide the app bar if specified.
3946 // Hide the tab linear layout.
3947 tabsLinearLayout.visibility = View.GONE
3949 // Hide the app bar.
3953 /* Hide the system bars.
3954 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3955 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
3956 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3957 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3960 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
3961 @Suppress("DEPRECATION")
3962 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
3963 } else { // Switch to normal viewing mode.
3964 // Remove the `SYSTEM_UI` flags from the root frame layout. The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
3965 @Suppress("DEPRECATION")
3966 rootFrameLayout.systemUiVisibility = 0
3970 // The view parameter cannot be removed because it is called from the layout onClick.
3971 fun findNextOnPage(@Suppress("UNUSED_PARAMETER")view: View?) {
3972 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
3973 currentWebView!!.findNext(true)
3976 // The view parameter cannot be removed because it is called from the layout onClick.
3977 fun findPreviousOnPage(@Suppress("UNUSED_PARAMETER")view: View?) {
3978 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
3979 currentWebView!!.findNext(false)
3982 override fun finishedPopulatingFilterLists(combinedFilterLists: ArrayList<ArrayList<List<Array<String>>>>) {
3983 // Store the filter lists.
3984 easyList = combinedFilterLists[0]
3985 easyPrivacy = combinedFilterLists[1]
3986 fanboysAnnoyanceList = combinedFilterLists[2]
3987 fanboysSocialList = combinedFilterLists[3]
3988 ultraList = combinedFilterLists[4]
3989 ultraPrivacy = combinedFilterLists[5]
3991 // Check to see if the activity has been restarted with a saved state.
3992 if ((savedStateArrayList == null) || (savedStateArrayList!!.size == 0)) { // The activity has not been restarted or it was restarted on start to change the theme.
3993 // Add the first tab.
3994 addNewTab("", false)
3995 } else { // The activity has been restarted.
3996 // Restore each tab.
3997 for (i in savedStateArrayList!!.indices) {
3999 tabLayout.addTab(tabLayout.newTab())
4002 val newTab = tabLayout.getTabAt(i)!!
4004 // Set a custom view on the new tab.
4005 newTab.setCustomView(R.layout.tab_custom_view)
4007 // Add the new page.
4008 webViewStateAdapter!!.restorePage(savedStateArrayList!![i], savedNestedScrollWebViewStateArrayList!![i])
4011 // Reset the saved state variables.
4012 savedStateArrayList = null
4013 savedNestedScrollWebViewStateArrayList = null
4015 // Restore the selected tab position.
4016 if (savedTabPosition == 0) { // The first tab is selected.
4017 // Set the first page as the current WebView.
4018 setCurrentWebView(0)
4019 } else { // The first tab is not selected.
4020 // Switch to the page before the saved tab position.
4021 webViewViewPager2.post { webViewViewPager2.currentItem = (savedTabPosition - 1) }
4023 // Switch to the saved tab position.
4024 // This has to be done twice because, for some reason, if the above step is skipped there is some race condition where nothing happens and the first page is displayed.
4025 webViewViewPager2.post { webViewViewPager2.currentItem = savedTabPosition }
4028 // Get the intent that started the app.
4031 // Reset the intent. This prevents a duplicate tab from being created on restart.
4034 // Get the information from the intent.
4035 val intentAction = intent.action
4036 val intentUriData = intent.data
4037 val intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT)
4039 // Determine if this is a web search.
4040 val isWebSearch = (intentAction != null) && (intentAction == Intent.ACTION_WEB_SEARCH)
4042 // 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.
4043 if ((intentUriData != null) || (intentStringExtra != null) || isWebSearch) {
4044 // Get the URL string.
4045 val urlString = if (isWebSearch) { // The intent is a web search.
4046 // Sanitize the search input.
4047 val encodedSearchString: String = try {
4048 URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8")
4049 } catch (exception: UnsupportedEncodingException) {
4053 // Add the base search URL.
4054 searchURL + encodedSearchString
4055 } else { // The intent contains a URL formatted as a URI or a URL in the string extra.
4056 // Get the URL string.
4057 intentUriData?.toString() ?: intentStringExtra!!
4060 // Add a new tab if specified in the preferences.
4061 if (sharedPreferences.getBoolean(getString(R.string.open_intents_in_new_tab_key), true)) { // Load the URL in a new tab.
4062 // Set the loading new intent flag.
4063 loadingNewIntent = true
4066 addNewTab(urlString, true)
4067 } else { // Load the URL in the current tab.
4069 loadUrl(currentWebView!!, urlString)
4075 // Remove the warning that `OnTouchListener()` needs to override `performClick()`, as the only purpose of setting the `OnTouchListener()` is to make it do nothing.
4076 @SuppressLint("ClickableViewAccessibility")
4077 private fun initializeApp() {
4078 // Get a handle for the input method.
4079 val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
4081 // Initialize the color spans for highlighting the URLs.
4082 initialGrayColorSpan = ForegroundColorSpan(getColor(R.color.gray_500))
4083 finalGrayColorSpan = ForegroundColorSpan(getColor(R.color.gray_500))
4084 redColorSpan = ForegroundColorSpan(getColor(R.color.red_text))
4086 // Remove the formatting from the URL edit text when the user is editing the text.
4087 urlEditText.onFocusChangeListener = View.OnFocusChangeListener { _: View?, hasFocus: Boolean ->
4088 if (hasFocus) { // The user is editing the URL text box.
4089 // Remove the syntax highlighting.
4090 urlEditText.text.removeSpan(redColorSpan)
4091 urlEditText.text.removeSpan(initialGrayColorSpan)
4092 urlEditText.text.removeSpan(finalGrayColorSpan)
4093 } else { // The user has stopped editing the URL text box.
4094 // Move to the beginning of the string.
4095 urlEditText.setSelection(0)
4097 // Reapply the syntax highlighting.
4098 UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
4102 // Set the go button on the keyboard to load the URL in url text box.
4103 urlEditText.setOnKeyListener { _: View?, keyCode: Int, keyEvent: KeyEvent ->
4104 // If the event is a key-down event on the `enter` button, load the URL.
4105 if ((keyEvent.action == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The enter key was pressed.
4107 loadUrlFromTextBox()
4109 // Consume the event.
4110 return@setOnKeyListener true
4111 } else { // Some other key was pressed.
4112 // Do not consume the event.
4113 return@setOnKeyListener false
4117 // Create an Orbot status broadcast receiver.
4118 orbotStatusBroadcastReceiver = object : BroadcastReceiver() {
4119 override fun onReceive(context: Context, intent: Intent) {
4120 // Get the content of the status message.
4121 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS")!!
4123 // If Privacy Browser is waiting on the proxy, load the website now that Orbot is connected.
4124 if ((orbotStatus == ProxyHelper.ORBOT_STATUS_ON) && waitingForProxy) {
4125 // Reset the waiting for proxy status.
4126 waitingForProxy = false
4128 // Get a list of the current fragments.
4129 val fragmentList = supportFragmentManager.fragments
4131 // Check each fragment to see if it is a waiting for proxy dialog. Sometimes more than one is displayed.
4132 for (i in fragmentList.indices) {
4133 // Get the fragment tag.
4134 val fragmentTag = fragmentList[i].tag
4136 // Check to see if it is the waiting for proxy dialog.
4137 if (fragmentTag != null && fragmentTag == getString(R.string.waiting_for_proxy_dialog)) {
4138 // Dismiss the waiting for proxy dialog.
4139 (fragmentList[i] as DialogFragment).dismiss()
4143 // Reload existing URLs and load any URLs that are waiting for the proxy.
4144 for (i in 0 until webViewStateAdapter!!.itemCount) {
4145 // Get the WebView tab fragment.
4146 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
4148 // Get the fragment view.
4149 val fragmentView = webViewTabFragment.view
4151 // Only process the WebViews if they exist.
4152 if (fragmentView != null) {
4153 // Get the nested scroll WebView from the tab fragment.
4154 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
4156 // Get the waiting for proxy URL string.
4157 val waitingForProxyUrlString = nestedScrollWebView.waitingForProxyUrlString
4159 // Load the pending URL if it exists.
4160 if (waitingForProxyUrlString.isNotEmpty()) { // A URL is waiting to be loaded.
4162 loadUrl(nestedScrollWebView, waitingForProxyUrlString)
4164 // Reset the waiting for proxy URL string.
4165 nestedScrollWebView.waitingForProxyUrlString = ""
4166 } else { // No URL is waiting to be loaded.
4167 // Reload the existing URL.
4168 nestedScrollWebView.reload()
4176 // Register the Orbot status broadcast receiver.
4177 registerReceiver(orbotStatusBroadcastReceiver, IntentFilter("org.torproject.android.intent.action.STATUS"))
4179 // Get handles for views that need to be modified.
4180 val bookmarksHeaderLinearLayout = findViewById<LinearLayout>(R.id.bookmarks_header_linearlayout)
4181 val launchBookmarksActivityFab = findViewById<FloatingActionButton>(R.id.launch_bookmarks_activity_fab)
4182 val createBookmarkFolderFab = findViewById<FloatingActionButton>(R.id.create_bookmark_folder_fab)
4183 val createBookmarkFab = findViewById<FloatingActionButton>(R.id.create_bookmark_fab)
4185 // Update the WebView pager every time a tab is modified.
4186 webViewViewPager2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
4187 override fun onPageSelected(position: Int) {
4188 // Close the find on page bar if it is open.
4189 closeFindOnPage(null)
4191 // Set the current WebView.
4192 setCurrentWebView(position)
4194 // Select the corresponding tab if it does not match the currently selected page. This will happen if the page was scrolled by creating a new tab.
4195 if (tabLayout.selectedTabPosition != position) {
4196 // Wait until the new tab has been created.
4198 // Get a handle for the tab.
4199 val tab = tabLayout.getTabAt(position)!!
4208 // Handle tab selections.
4209 tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
4210 override fun onTabSelected(tab: TabLayout.Tab) {
4211 // Select the same page in the view pager.
4212 webViewViewPager2.currentItem = tab.position
4215 override fun onTabUnselected(tab: TabLayout.Tab) {}
4217 override fun onTabReselected(tab: TabLayout.Tab) {
4218 // Instantiate the View SSL Certificate dialog.
4219 val viewSslCertificateDialogFragment: DialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView!!.webViewFragmentId, currentWebView!!.getFavoriteIcon())
4221 // Display the View SSL Certificate dialog.
4222 viewSslCertificateDialogFragment.show(supportFragmentManager, getString(R.string.view_ssl_certificate))
4226 // Set a touch listener on the bookmarks header linear layout so that touches don't pass through to the button underneath.
4227 bookmarksHeaderLinearLayout.setOnTouchListener { _: View?, _: MotionEvent? -> true }
4229 // Set the launch bookmarks activity floating action button to launch the bookmarks activity.
4230 launchBookmarksActivityFab.setOnClickListener {
4231 // Get a copy of the favorite icon bitmap.
4232 val currentFavoriteIconBitmap = currentWebView!!.getFavoriteIcon()
4234 // Create a favorite icon byte array output stream.
4235 val currentFavoriteIconByteArrayOutputStream = ByteArrayOutputStream()
4237 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
4238 currentFavoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, currentFavoriteIconByteArrayOutputStream)
4240 // Convert the favorite icon byte array stream to a byte array.
4241 val currentFavoriteIconByteArray = currentFavoriteIconByteArrayOutputStream.toByteArray()
4243 // Create an intent to launch the bookmarks activity.
4244 val bookmarksIntent = Intent(applicationContext, BookmarksActivity::class.java)
4246 // Add the extra information to the intent.
4247 bookmarksIntent.putExtra(CURRENT_FOLDER_ID, currentBookmarksFolderId)
4248 bookmarksIntent.putExtra(CURRENT_TITLE, currentWebView!!.title)
4249 bookmarksIntent.putExtra(CURRENT_URL, currentWebView!!.url)
4250 bookmarksIntent.putExtra(CURRENT_FAVORITE_ICON_BYTE_ARRAY, currentFavoriteIconByteArray)
4253 startActivity(bookmarksIntent)
4256 // Set the create new bookmark folder floating action button to display an alert dialog.
4257 createBookmarkFolderFab.setOnClickListener {
4258 // Create a create bookmark folder dialog.
4259 val createBookmarkFolderDialog: DialogFragment = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView!!.getFavoriteIcon())
4261 // Show the create bookmark folder dialog.
4262 createBookmarkFolderDialog.show(supportFragmentManager, getString(R.string.create_folder))
4265 // Set the create new bookmark floating action button to display an alert dialog.
4266 createBookmarkFab.setOnClickListener {
4267 // Instantiate the create bookmark dialog.
4268 val createBookmarkDialog: DialogFragment = CreateBookmarkDialog.createBookmark(currentWebView!!.url!!, currentWebView!!.title!!, currentWebView!!.getFavoriteIcon())
4270 // Display the create bookmark dialog.
4271 createBookmarkDialog.show(supportFragmentManager, getString(R.string.create_bookmark))
4274 // Search for the string on the page whenever a character changes in the find on page edit text.
4275 findOnPageEditText.addTextChangedListener(object : TextWatcher {
4276 override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
4278 override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
4280 override fun afterTextChanged(s: Editable) {
4281 // 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.
4282 currentWebView?.findAllAsync(findOnPageEditText.text.toString())
4286 // Set the `check mark` button for the find on page edit text keyboard to close the soft keyboard.
4287 findOnPageEditText.setOnKeyListener { _: View?, keyCode: Int, keyEvent: KeyEvent ->
4288 if ((keyEvent.action == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
4289 // Hide the soft keyboard.
4290 inputMethodManager.hideSoftInputFromWindow(currentWebView!!.windowToken, 0)
4292 // Consume the event.
4293 return@setOnKeyListener true
4294 } else { // A different key was pressed.
4295 // Do not consume the event.
4296 return@setOnKeyListener false
4300 // Implement swipe to refresh.
4301 swipeRefreshLayout.setOnRefreshListener {
4302 // Reload the website.
4303 currentWebView!!.reload()
4306 // Store the default progress view offsets.
4307 defaultProgressViewStartOffset = swipeRefreshLayout.progressViewStartOffset
4308 defaultProgressViewEndOffset = swipeRefreshLayout.progressViewEndOffset
4310 // Set the refresh color scheme according to the theme.
4311 swipeRefreshLayout.setColorSchemeResources(R.color.blue_text)
4313 // Initialize a color background typed value.
4314 val colorBackgroundTypedValue = TypedValue()
4316 // Get the color background from the theme.
4317 theme.resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true)
4319 // Get the color background int from the typed value.
4320 val colorBackgroundInt = colorBackgroundTypedValue.data
4322 // Set the swipe refresh background color.
4323 swipeRefreshLayout.setProgressBackgroundColorSchemeColor(colorBackgroundInt)
4325 // Set the drawer titles, which identify the drawer layouts in accessibility mode.
4326 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer))
4327 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks))
4329 // Load the bookmarks folder.
4330 loadBookmarksFolder()
4332 // Handle clicks on bookmarks.
4333 bookmarksListView.onItemClickListener = AdapterView.OnItemClickListener { _: AdapterView<*>?, _: View?, _: Int, id: Long ->
4334 // Convert the id from long to int to match the format of the bookmarks database.
4335 val databaseId = id.toInt()
4337 // Get the bookmark cursor for this ID.
4338 val bookmarkCursor = bookmarksDatabaseHelper!!.getBookmark(databaseId)
4340 // Move the bookmark cursor to the first row.
4341 bookmarkCursor.moveToFirst()
4343 // Act upon the bookmark according to the type.
4344 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndexOrThrow(IS_FOLDER)) == 1) { // The selected bookmark is a folder.
4345 // Store the folder ID.
4346 currentBookmarksFolderId = bookmarkCursor.getLong(bookmarkCursor.getColumnIndexOrThrow(FOLDER_ID))
4348 // Load the new folder.
4349 loadBookmarksFolder()
4350 } else { // The selected bookmark is not a folder.
4351 // Load the bookmark URL.
4352 loadUrl(currentWebView!!, bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BOOKMARK_URL)))
4354 // Close the bookmarks drawer if it is not pinned.
4355 if (!bookmarksDrawerPinned)
4356 drawerLayout.closeDrawer(GravityCompat.END)
4359 // Close the cursor.
4360 bookmarkCursor.close()
4363 // Handle long-presses on bookmarks.
4364 bookmarksListView.onItemLongClickListener = AdapterView.OnItemLongClickListener { _: AdapterView<*>?, _: View?, _: Int, id: Long ->
4365 // Convert the database ID from `long` to `int`.
4366 val databaseId = id.toInt()
4368 // Run the commands associated with the type.
4369 if (bookmarksDatabaseHelper!!.isFolder(databaseId)) { // The bookmark is a folder.
4370 // Get the folder ID.
4371 val folderId = bookmarksDatabaseHelper!!.getFolderId(databaseId)
4373 // Get a cursor of all the bookmarks in the folder.
4374 val bookmarksCursor = bookmarksDatabaseHelper!!.getFolderBookmarks(folderId)
4376 // Move to the first entry in the cursor.
4377 bookmarksCursor.moveToFirst()
4379 // Open each bookmark
4380 for (i in 0 until bookmarksCursor.count) {
4381 // Load the bookmark in a new tab, moving to the tab for the first bookmark if the drawer is not pinned.
4382 addNewTab(bookmarksCursor.getString(bookmarksCursor.getColumnIndexOrThrow(BOOKMARK_URL)), !bookmarksDrawerPinned && (i == 0))
4384 // Move to the next bookmark.
4385 bookmarksCursor.moveToNext()
4388 // Close the cursor.
4389 bookmarksCursor.close()
4390 } else { // The bookmark is not a folder.
4391 // Get the bookmark cursor for this ID.
4392 val bookmarkCursor = bookmarksDatabaseHelper!!.getBookmark(databaseId)
4394 // Move the bookmark cursor to the first row.
4395 bookmarkCursor.moveToFirst()
4397 // Load the bookmark in a new tab and move to the tab if the drawer is not pinned.
4398 addNewTab(bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BOOKMARK_URL)), !bookmarksDrawerPinned)
4400 // Close the cursor.
4401 bookmarkCursor.close()
4404 // Close the bookmarks drawer if it is not pinned.
4405 if (!bookmarksDrawerPinned)
4406 drawerLayout.closeDrawer(GravityCompat.END)
4408 // Consume the event.
4412 // The drawer listener is used to update the navigation menu.
4413 drawerLayout.addDrawerListener(object : DrawerLayout.DrawerListener {
4414 override fun onDrawerSlide(drawerView: View, slideOffset: Float) {}
4416 override fun onDrawerOpened(drawerView: View) {}
4418 override fun onDrawerClosed(drawerView: View) {
4419 // Reset the drawer icon when the drawer is closed. Otherwise, it remains an arrow if the drawer is open when the app is restarted.
4420 actionBarDrawerToggle!!.syncState()
4423 override fun onDrawerStateChanged(newState: Int) {
4424 if (newState == DrawerLayout.STATE_SETTLING || newState == DrawerLayout.STATE_DRAGGING) { // A drawer is opening or closing.
4425 // Update the navigation menu items if the WebView is not null.
4426 if (currentWebView != null) {
4427 navigationBackMenuItem.isEnabled = currentWebView!!.canGoBack()
4428 navigationForwardMenuItem.isEnabled = currentWebView!!.canGoForward()
4429 navigationHistoryMenuItem.isEnabled = currentWebView!!.canGoBack() || currentWebView!!.canGoForward()
4430 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + currentWebView!!.getRequestsCount(BLOCKED_REQUESTS)
4432 // Hide the keyboard (if displayed).
4433 inputMethodManager.hideSoftInputFromWindow(currentWebView!!.windowToken, 0)
4436 // 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.
4437 urlEditText.clearFocus()
4439 // 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.
4440 // Clearing the focus from the WebView removes any text selection markers and context menus, which otherwise draw above the open drawers.
4441 currentWebView?.clearFocus()
4446 // Inflate a bare WebView to get the default user agent. It is not used to render content on the screen.
4447 @SuppressLint("InflateParams") val webViewLayout = layoutInflater.inflate(R.layout.bare_webview, null, false)
4449 // Get a handle for the WebView.
4450 val bareWebView = webViewLayout.findViewById<WebView>(R.id.bare_webview)
4452 // Store the default user agent.
4453 webViewDefaultUserAgent = bareWebView.settings.userAgentString
4455 // Destroy the bare WebView.
4456 bareWebView.destroy()
4458 // Update the domains settings set.
4459 updateDomainsSettingsSet()
4461 // Instantiate the check filter list helper.
4462 checkFilterListHelper = CheckFilterListHelper()
4465 @SuppressLint("ClickableViewAccessibility")
4466 override fun initializeWebView(nestedScrollWebView: NestedScrollWebView, pageNumber: Int, progressBar: ProgressBar, urlString: String, restoringState: Boolean) {
4467 // Get the WebView theme.
4468 val webViewTheme = sharedPreferences.getString(getString(R.string.webview_theme_key), getString(R.string.webview_theme_default_value))
4470 // Get the WebView theme entry values string array.
4471 val webViewThemeEntryValuesStringArray = resources.getStringArray(R.array.webview_theme_entry_values)
4473 // Set the WebView theme if algorithmic darkening is supported.
4474 if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {
4475 // Set the WebView them. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
4476 if (webViewTheme == webViewThemeEntryValuesStringArray[1]) { // The light theme is selected.
4477 // Turn off algorithmic darkening.
4478 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
4480 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
4481 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
4482 nestedScrollWebView.visibility = View.VISIBLE
4483 } else if (webViewTheme == webViewThemeEntryValuesStringArray[2]) { // The dark theme is selected.
4484 // Turn on algorithmic darkening.
4485 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
4486 } else { // The system default theme is selected.
4487 // Get the current theme status.
4488 val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
4490 // Set the algorithmic darkening according to the current system theme status.
4491 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) { // The system is in day mode.
4492 // Turn off algorithmic darkening.
4493 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
4495 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
4496 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
4497 nestedScrollWebView.visibility = View.VISIBLE
4498 } else { // The system is in night mode.
4499 // Turn on algorithmic darkening.
4500 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
4505 // Get a handle for the input method manager.
4506 val inputMethodManager = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
4508 // Set the app bar scrolling.
4509 nestedScrollWebView.isNestedScrollingEnabled = scrollAppBar
4511 // Allow pinch to zoom.
4512 nestedScrollWebView.settings.builtInZoomControls = true
4514 // Hide zoom controls.
4515 nestedScrollWebView.settings.displayZoomControls = false
4517 // Don't allow mixed content (HTTP and HTTPS) on the same website.
4518 nestedScrollWebView.settings.mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW
4520 // Set the WebView to load in overview mode (zoomed out to the maximum width).
4521 nestedScrollWebView.settings.loadWithOverviewMode = true
4523 // Explicitly disable geolocation.
4524 nestedScrollWebView.settings.setGeolocationEnabled(false)
4526 // Allow loading of file:// URLs. This is necessary for opening MHT web archives, which are copied into a temporary cache location.
4527 nestedScrollWebView.settings.allowFileAccess = true
4529 // Create a double-tap gesture detector to toggle full-screen mode.
4530 val doubleTapGestureDetector = GestureDetector(this, object : GestureDetector.SimpleOnGestureListener() {
4531 // Override `onDoubleTap()`. All other events are handled using the default settings.
4532 override fun onDoubleTap(motionEvent: MotionEvent): Boolean {
4533 return if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
4534 // Toggle the full screen browsing mode tracker.
4535 inFullScreenBrowsingMode = !inFullScreenBrowsingMode
4537 // Toggle the full screen browsing mode.
4538 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
4539 // Hide the app bar if specified.
4540 if (hideAppBar) { // App bar hiding is enabled.
4541 // Close the find on page bar if it is visible.
4542 closeFindOnPage(null)
4544 // Hide the tab linear layout.
4545 tabsLinearLayout.visibility = View.GONE
4547 // Hide the app bar.
4550 // Set layout and scrolling parameters according to the position of the app bar.
4551 if (bottomAppBar) { // The app bar is at the bottom.
4552 // Reset the WebView padding to fill the available space.
4553 swipeRefreshLayout.setPadding(0, 0, 0, 0)
4554 } else { // The app bar is at the top.
4555 // Check to see if the app bar is normally scrolled.
4556 if (scrollAppBar) { // The app bar is scrolled when it is displayed.
4557 // Get the swipe refresh layout parameters.
4558 val swipeRefreshLayoutParams = swipeRefreshLayout.layoutParams as CoordinatorLayout.LayoutParams
4560 // Remove the off-screen scrolling layout.
4561 swipeRefreshLayoutParams.behavior = null
4562 } else { // The app bar is not scrolled when it is displayed.
4563 // Remove the padding from the top of the swipe refresh layout.
4564 swipeRefreshLayout.setPadding(0, 0, 0, 0)
4566 // The swipe refresh circle must be moved above the now removed status bar location.
4567 swipeRefreshLayout.setProgressViewOffset(false, -200, defaultProgressViewEndOffset)
4570 } else { // App bar hiding is not enabled.
4571 // Adjust the UI for the bottom app bar.
4573 // Adjust the UI according to the scrolling of the app bar.
4575 // Reset the WebView padding to fill the available space.
4576 swipeRefreshLayout.setPadding(0, 0, 0, 0)
4578 // Move the WebView above the app bar layout.
4579 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
4584 /* Hide the system bars.
4585 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4586 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4587 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4588 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4591 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4592 @Suppress("DEPRECATION")
4593 rootFrameLayout.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
4594 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
4595 } else { // Switch to normal viewing mode.
4596 // Show the app bar if it was hidden.
4598 // Show the tab linear layout.
4599 tabsLinearLayout.visibility = View.VISIBLE
4601 // Show the app bar.
4605 // Set layout and scrolling parameters according to the position of the app bar.
4606 if (bottomAppBar) { // The app bar is at the bottom.
4609 // Reset the WebView padding to fill the available space.
4610 swipeRefreshLayout.setPadding(0, 0, 0, 0)
4612 // Move the WebView above the app bar layout.
4613 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
4615 } else { // The app bar is at the top.
4616 // Check to see if the app bar is normally scrolled.
4617 if (scrollAppBar) { // The app bar is scrolled when it is displayed.
4618 // Get the swipe refresh layout parameters.
4619 val swipeRefreshLayoutParams = swipeRefreshLayout.layoutParams as CoordinatorLayout.LayoutParams
4621 // Add the off-screen scrolling layout.
4622 swipeRefreshLayoutParams.behavior = AppBarLayout.ScrollingViewBehavior()
4623 } else { // The app bar is not scrolled when it is displayed.
4624 // The swipe refresh layout must be manually moved below the app bar layout.
4625 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0)
4627 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
4628 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight)
4632 // Remove the `SYSTEM_UI` flags from the root frame layout. The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4633 @Suppress("DEPRECATION")
4634 rootFrameLayout.systemUiVisibility = 0
4637 // Consume the double-tap.
4639 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
4645 override fun onFling(motionEvent1: MotionEvent, motionEvent2: MotionEvent, velocityX: Float, velocityY: Float): Boolean {
4646 // Scroll the bottom app bar if enabled.
4647 if (bottomAppBar && scrollAppBar && !objectAnimator.isRunning) {
4648 // Calculate the Y change.
4649 val motionY = motionEvent2.y - motionEvent1.y
4651 // Scroll the app bar if the change is greater than 50 pixels.
4653 // Animate the bottom app bar onto the screen.
4654 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0f)
4655 } else if (motionY < -50) {
4656 // Animate the bottom app bar off the screen.
4657 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", appBarLayout.height.toFloat())
4661 objectAnimator.start()
4664 // Do not consume the event.
4669 // Pass all touch events on the WebView through the double-tap gesture detector.
4670 nestedScrollWebView.setOnTouchListener { view: View, motionEvent: MotionEvent? ->
4671 // Call `performClick()` on the view, which is required for accessibility.
4674 // Check for double-taps.
4675 doubleTapGestureDetector.onTouchEvent(motionEvent!!)
4678 // Register the WebView for a context menu. This is used to see link targets and download images.
4679 registerForContextMenu(nestedScrollWebView)
4681 // Allow the downloading of files.
4682 nestedScrollWebView.setDownloadListener { downloadUrlString: String?, userAgent: String?, contentDisposition: String?, mimetype: String?, contentLength: Long ->
4683 // Check the download preference.
4684 if (downloadWithExternalApp) { // Download with an external app.
4685 downloadUrlWithExternalApp(downloadUrlString!!)
4686 } else { // Handle the download inside of Privacy Browser.
4687 // Define a formatted file size string.
4689 // Process the content length if it contains data.
4690 val formattedFileSizeString = if (contentLength > 0) { // The content length is greater than 0.
4691 // Format the content length as a string.
4692 NumberFormat.getInstance().format(contentLength) + " " + getString(R.string.bytes)
4693 } else { // The content length is not greater than 0.
4694 // Set the formatted file size string to be `unknown size`.
4695 getString(R.string.unknown_size)
4698 // Get the file name from the content disposition.
4699 val fileNameString = UrlHelper.getFileName(this, contentDisposition, mimetype, downloadUrlString!!)
4701 // Instantiate the save dialog.
4702 val saveDialogFragment = SaveDialog.saveUrl(downloadUrlString, fileNameString, formattedFileSizeString, userAgent!!, nestedScrollWebView.acceptCookies)
4704 // 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.
4706 // Show the save dialog.
4707 saveDialogFragment.show(supportFragmentManager, getString(R.string.save_dialog))
4708 } catch (exception: Exception) { // The dialog could not be shown.
4709 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
4710 pendingDialogsArrayList.add(PendingDialogDataClass(saveDialogFragment, getString(R.string.save_dialog)))
4715 // Update the find on page count.
4716 nestedScrollWebView.setFindListener { activeMatchOrdinal, numberOfMatches, isDoneCounting ->
4717 if (isDoneCounting && (numberOfMatches == 0)) { // There are no matches.
4718 // Set the find on page count text view to be `0/0`.
4719 findOnPageCountTextView.setText(R.string.zero_of_zero)
4720 } else if (isDoneCounting) { // There are matches.
4721 // The active match ordinal is zero-based.
4722 val activeMatch = activeMatchOrdinal + 1
4724 // Build the match string.
4725 val matchString = "$activeMatch/$numberOfMatches"
4727 // Update the find on page count text view.
4728 findOnPageCountTextView.text = matchString
4732 // Process scroll changes.
4733 nestedScrollWebView.setOnScrollChangeListener { _: View?, _: Int, _: Int, _: Int, _: Int ->
4734 // Set the swipe to refresh status.
4735 if (nestedScrollWebView.swipeToRefresh) // Only enable swipe to refresh if the WebView is scrolled to the top.
4736 swipeRefreshLayout.isEnabled = nestedScrollWebView.scrollY == 0
4737 else // Disable swipe to refresh.
4738 swipeRefreshLayout.isEnabled = false
4740 // Reinforce the system UI visibility flags if in full screen browsing mode.
4741 // This hides the status and navigation bars, which are displayed if other elements are shown, like dialog boxes, the options menu, or the keyboard.
4742 if (inFullScreenBrowsingMode) {
4743 /* Hide the system bars.
4744 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4745 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4746 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4747 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4750 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4751 @Suppress("DEPRECATION")
4752 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
4756 // Set the web chrome client.
4757 nestedScrollWebView.webChromeClient = object : WebChromeClient() {
4758 // Update the progress bar when a page is loading.
4759 override fun onProgressChanged(view: WebView, progress: Int) {
4760 // Update the progress bar.
4761 progressBar.progress = progress
4763 // Set the visibility of the progress bar.
4764 if (progress < 100) {
4765 // Show the progress bar.
4766 progressBar.visibility = View.VISIBLE
4768 // Hide the progress bar.
4769 progressBar.visibility = View.GONE
4771 //Stop the swipe to refresh indicator if it is running
4772 swipeRefreshLayout.isRefreshing = false
4774 // 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.
4775 nestedScrollWebView.visibility = View.VISIBLE
4779 // Set the favorite icon when it changes.
4780 override fun onReceivedIcon(view: WebView, icon: Bitmap) {
4781 // 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.
4782 // This prevents low resolution icons from replacing high resolution one.
4783 // The check for the visibility of the progress bar can possibly be removed once https://redmine.stoutner.com/issues/747 is fixed.
4784 if ((progressBar.visibility == View.GONE) && (icon.height > nestedScrollWebView.getFavoriteIconHeight())) {
4785 // Store the new favorite icon.
4786 nestedScrollWebView.setFavoriteIcon(icon)
4788 // Get the current page position.
4789 val currentPosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
4791 // Get the current tab.
4792 val tab = tabLayout.getTabAt(currentPosition)
4794 // Check to see if the tab has been populated.
4796 // Get the custom view from the tab.
4797 val tabView = tab.customView
4799 // Check to see if the custom tab view has been populated.
4800 if (tabView != null) {
4801 // Get the favorite icon image view from the tab.
4802 val tabFavoriteIconImageView = tabView.findViewById<ImageView>(R.id.favorite_icon_imageview)
4804 // Display the favorite icon in the tab.
4805 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true))
4811 // Save a copy of the title when it changes.
4812 override fun onReceivedTitle(view: WebView, title: String) {
4813 // Get the current page position.
4814 val currentPosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
4816 // Get the current tab.
4817 val tab = tabLayout.getTabAt(currentPosition)
4819 // Only populate the title text view if the tab has been fully created.
4821 // Get the custom view from the tab.
4822 val tabView = tab.customView
4824 // Only populate the title text view if the tab view has been fully populated.
4825 if (tabView != null) {
4826 // Get the title text view from the tab.
4827 val tabTitleTextView = tabView.findViewById<TextView>(R.id.title_textview)
4829 // Set the title according to the URL.
4830 if (title == "about:blank") {
4831 // Set the title to indicate a new tab.
4832 tabTitleTextView.setText(R.string.new_tab)
4834 // Set the title as the tab text.
4835 tabTitleTextView.text = title
4841 // Enter full screen video.
4842 override fun onShowCustomView(video: View, callback: CustomViewCallback) {
4843 // Set the full screen video flag.
4844 displayingFullScreenVideo = true
4846 // Hide the keyboard.
4847 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.windowToken, 0)
4849 // Hide the coordinator layout.
4850 coordinatorLayout.visibility = View.GONE
4852 /* Hide the system bars.
4853 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4854 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4855 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4856 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4859 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4860 @Suppress("DEPRECATION")
4861 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
4863 // Disable the sliding drawers.
4864 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
4866 // Add the video view to the full screen video frame layout.
4867 fullScreenVideoFrameLayout.addView(video)
4869 // Show the full screen video frame layout.
4870 fullScreenVideoFrameLayout.visibility = View.VISIBLE
4872 // Disable the screen timeout while the video is playing. YouTube does this automatically, but not all other videos do.
4873 fullScreenVideoFrameLayout.keepScreenOn = true
4876 // Exit full screen video.
4877 override fun onHideCustomView() {
4878 // Exit the full screen video.
4879 exitFullScreenVideo()
4883 override fun onShowFileChooser(webView: WebView, filePathCallback: ValueCallback<Array<Uri>>, fileChooserParams: FileChooserParams): Boolean {
4884 // Store the file path callback.
4885 fileChooserCallback = filePathCallback
4887 // Create an intent to open a chooser based on the file chooser parameters.
4888 val fileChooserIntent = fileChooserParams.createIntent()
4890 // Check to see if the file chooser intent resolves to an installed package.
4891 if (fileChooserIntent.resolveActivity(packageManager) != null) { // The file chooser intent is fine.
4892 // Launch the file chooser intent.
4893 browseFileUploadActivityResultLauncher.launch(fileChooserIntent)
4894 } else { // The file chooser intent will cause a crash.
4895 // Create a generic intent to open a chooser.
4896 val genericFileChooserIntent = Intent(Intent.ACTION_GET_CONTENT)
4898 // Request an openable file.
4899 genericFileChooserIntent.addCategory(Intent.CATEGORY_OPENABLE)
4901 // Set the file type to everything.
4902 genericFileChooserIntent.type = "*/*"
4904 // Launch the generic file chooser intent.
4905 browseFileUploadActivityResultLauncher.launch(genericFileChooserIntent)
4908 // Handle the event.
4912 nestedScrollWebView.webViewClient = object : WebViewClient() {
4913 // `shouldOverrideUrlLoading` makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
4914 override fun shouldOverrideUrlLoading(view: WebView, webResourceRequest: WebResourceRequest): Boolean {
4915 // Get the URL from the web resource request.
4916 var requestUrlString = webResourceRequest.url.toString()
4918 // Sanitize the url.
4919 requestUrlString = sanitizeUrl(requestUrlString)
4921 // Handle the URL according to the type.
4922 return if (requestUrlString.startsWith("http")) { // Load the URL in Privacy Browser.
4923 // Load the URL. By using `loadUrl()`, instead of `loadUrlFromBase()`, the Referer header will never be sent.
4924 loadUrl(nestedScrollWebView, requestUrlString)
4926 // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
4927 // Custom headers cannot be added if false is returned and the WebView handles the loading of the URL.
4929 } else if (requestUrlString.startsWith("mailto:")) { // Load the email address in an external email program.
4930 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
4931 val emailIntent = Intent(Intent.ACTION_SENDTO)
4933 // Parse the url and set it as the data for the intent.
4934 emailIntent.data = Uri.parse(requestUrlString)
4936 // Open the email program in a new task instead of as part of Privacy Browser.
4937 emailIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
4941 startActivity(emailIntent)
4942 } catch (exception: ActivityNotFoundException) {
4943 // Display a snackbar.
4944 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
4947 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
4949 } else if (requestUrlString.startsWith("tel:")) { // Load the phone number in the dialer.
4950 // Create a dial intent.
4951 val dialIntent = Intent(Intent.ACTION_DIAL)
4953 // Add the phone number to the intent.
4954 dialIntent.data = Uri.parse(requestUrlString)
4956 // Open the dialer in a new task instead of as part of Privacy Browser.
4957 dialIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
4961 startActivity(dialIntent)
4962 } catch (exception: ActivityNotFoundException) {
4963 // Display a snackbar.
4964 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
4967 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
4969 } else { // Load a system chooser to select an app that can handle the URL.
4970 // Create a generic intent to open an app.
4971 val genericIntent = Intent(Intent.ACTION_VIEW)
4973 // Add the URL to the intent.
4974 genericIntent.data = Uri.parse(requestUrlString)
4976 // List all apps that can handle the URL instead of just opening the first one.
4977 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE)
4979 // Open the app in a new task instead of as part of Privacy Browser.
4980 genericIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
4984 startActivity(genericIntent)
4985 } catch (exception: ActivityNotFoundException) {
4986 // Display a snackbar.
4987 Snackbar.make(nestedScrollWebView, getString(R.string.unrecognized_url, requestUrlString), Snackbar.LENGTH_SHORT).show()
4990 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
4995 // Check requests against the block lists.
4996 override fun shouldInterceptRequest(view: WebView, webResourceRequest: WebResourceRequest): WebResourceResponse? {
4998 val requestUrlString = webResourceRequest.url.toString()
5000 // Check to see if the resource request is for the main URL.
5001 if (requestUrlString == nestedScrollWebView.currentUrl) {
5002 // `return null` loads the resource request, which should never be blocked if it is the main URL.
5006 // 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.
5007 while (ultraPrivacy == null) {
5009 // Check to see if the filter lists have been populated after 100 ms.
5011 } catch (exception: InterruptedException) {
5016 // Create an empty web resource response to be used if the resource request is blocked.
5017 val emptyWebResourceResponse = WebResourceResponse("text/plain", "utf8", ByteArrayInputStream("".toByteArray()))
5019 // Initialize the variables.
5020 var allowListResultStringArray: Array<String>? = null
5021 var isThirdPartyRequest = false
5023 // Get the current URL. `.getUrl()` throws an error because operations on the WebView cannot be made from this thread.
5024 var currentBaseDomain = nestedScrollWebView.currentDomainName
5026 // Store a copy of the current domain for use in later requests.
5027 val currentDomain = currentBaseDomain
5029 // Get the request host name.
5030 var requestBaseDomain = webResourceRequest.url.host
5032 // Only check for third-party requests if the current base domain is not empty and the request domain is not null.
5033 if (currentBaseDomain.isNotEmpty() && (requestBaseDomain != null)) {
5034 // Determine the current base domain.
5035 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5036 // Remove the first subdomain.
5037 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1)
5040 // Determine the request base domain.
5041 while (requestBaseDomain!!.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5042 // Remove the first subdomain.
5043 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1)
5046 // Update the third party request tracker.
5047 isThirdPartyRequest = currentBaseDomain != requestBaseDomain
5050 // Get the current WebView page position.
5051 val webViewPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
5053 // Determine if the WebView is currently displayed.
5054 val webViewDisplayed = (webViewPagePosition == tabLayout.selectedTabPosition)
5056 // Block third-party requests if enabled.
5057 if (isThirdPartyRequest && nestedScrollWebView.blockAllThirdPartyRequests) {
5058 // Add the result to the resource requests.
5059 nestedScrollWebView.addResourceRequest(arrayOf(REQUEST_THIRD_PARTY, requestUrlString))
5061 // Increment the blocked requests counters.
5062 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5063 nestedScrollWebView.incrementRequestsCount(THIRD_PARTY_REQUESTS)
5065 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5066 if (webViewDisplayed) {
5067 // Updating the UI must be run from the UI thread.
5069 // Update the menu item titles.
5070 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5072 // Update the options menu if it has been populated.
5073 if (optionsMenu != null) {
5074 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5075 optionsBlockAllThirdPartyRequestsMenuItem.title =
5076 nestedScrollWebView.getRequestsCount(THIRD_PARTY_REQUESTS).toString() + " - " + getString(R.string.block_all_third_party_requests)
5081 // The resource request was blocked. Return an empty web resource response.
5082 return emptyWebResourceResponse
5085 // Check UltraList if it is enabled.
5086 if (nestedScrollWebView.ultraListEnabled) {
5087 // Check the URL against UltraList.
5088 val ultraListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, ultraList)
5090 // Process the UltraList results.
5091 if (ultraListResults[0] == REQUEST_BLOCKED) { // The resource request matched UltraList's block list.
5092 // Add the result to the resource requests.
5093 nestedScrollWebView.addResourceRequest(arrayOf(ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]))
5095 // Increment the blocked requests counters.
5096 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5097 nestedScrollWebView.incrementRequestsCount(com.stoutner.privacybrowser.views.ULTRALIST)
5099 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5100 if (webViewDisplayed) {
5101 // Updating the UI must be run from the UI thread.
5103 // Update the menu item titles.
5104 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5106 // Update the options menu if it has been populated.
5107 if (optionsMenu != null) {
5108 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5109 optionsUltraListMenuItem.title = nestedScrollWebView.getRequestsCount(com.stoutner.privacybrowser.views.ULTRALIST).toString() + " - " + getString(R.string.ultralist)
5114 // The resource request was blocked. Return an empty web resource response.
5115 return emptyWebResourceResponse
5116 } else if (ultraListResults[0] == REQUEST_ALLOWED) { // The resource request matched UltraList's allow list.
5117 // Add an allow list entry to the resource requests array.
5118 nestedScrollWebView.addResourceRequest(arrayOf(ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]))
5120 // The resource request has been allowed by UltraList. `return null` loads the requested resource.
5125 // Check UltraPrivacy if it is enabled.
5126 if (nestedScrollWebView.ultraPrivacyEnabled) {
5127 // Check the URL against UltraPrivacy.
5128 val ultraPrivacyResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, ultraPrivacy!!)
5130 // Process the UltraPrivacy results.
5131 if (ultraPrivacyResults[0] == REQUEST_BLOCKED) { // The resource request matched UltraPrivacy's block list.
5132 // Add the result to the resource requests.
5133 nestedScrollWebView.addResourceRequest(arrayOf(ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5134 ultraPrivacyResults[5]))
5136 // Increment the blocked requests counters.
5137 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5138 nestedScrollWebView.incrementRequestsCount(ULTRAPRIVACY)
5140 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5141 if (webViewDisplayed) {
5142 // Updating the UI must be run from the UI thread.
5144 // Update the menu item titles.
5145 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5147 // Update the options menu if it has been populated.
5148 if (optionsMenu != null) {
5149 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5150 optionsUltraPrivacyMenuItem.title = nestedScrollWebView.getRequestsCount(ULTRAPRIVACY).toString() + " - " + getString(R.string.ultraprivacy)
5155 // The resource request was blocked. Return an empty web resource response.
5156 return emptyWebResourceResponse
5157 } else if (ultraPrivacyResults[0] == REQUEST_ALLOWED) { // The resource request matched UltraPrivacy's allow list.
5158 // Add an allow list entry to the resource requests array.
5159 nestedScrollWebView.addResourceRequest(arrayOf(ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5160 ultraPrivacyResults[5]))
5162 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
5167 // Check EasyList if it is enabled.
5168 if (nestedScrollWebView.easyListEnabled) {
5169 // Check the URL against EasyList.
5170 val easyListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, easyList)
5172 // Process the EasyList results.
5173 if (easyListResults[0] == REQUEST_BLOCKED) { // The resource request matched EasyList's block list.
5174 // Add the result to the resource requests.
5175 nestedScrollWebView.addResourceRequest(arrayOf(easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]))
5177 // Increment the blocked requests counters.
5178 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5179 nestedScrollWebView.incrementRequestsCount(EASYLIST)
5181 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5182 if (webViewDisplayed) {
5183 // Updating the UI must be run from the UI thread.
5185 // Update the menu item titles.
5186 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5188 // Update the options menu if it has been populated.
5189 if (optionsMenu != null) {
5190 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5191 optionsEasyListMenuItem.title = nestedScrollWebView.getRequestsCount(EASYLIST).toString() + " - " + getString(R.string.easylist)
5196 // The resource request was blocked. Return an empty web resource response.
5197 return emptyWebResourceResponse
5198 } else if (easyListResults[0] == REQUEST_ALLOWED) { // The resource request matched EasyList's allow list.
5199 // Update the allow list result string array tracker.
5200 allowListResultStringArray = arrayOf(easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5])
5204 // Check EasyPrivacy if it is enabled.
5205 if (nestedScrollWebView.easyPrivacyEnabled) {
5206 // Check the URL against EasyPrivacy.
5207 val easyPrivacyResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, easyPrivacy)
5209 // Process the EasyPrivacy results.
5210 if (easyPrivacyResults[0] == REQUEST_BLOCKED) { // The resource request matched EasyPrivacy's block list.
5211 // Add the result to the resource requests.
5212 nestedScrollWebView.addResourceRequest(arrayOf(easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5]))
5214 // Increment the blocked requests counters.
5215 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5216 nestedScrollWebView.incrementRequestsCount(EASYPRIVACY)
5218 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5219 if (webViewDisplayed) {
5220 // Updating the UI must be run from the UI thread.
5222 // Update the menu item titles.
5223 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5225 // Update the options menu if it has been populated.
5226 if (optionsMenu != null) {
5227 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5228 optionsEasyPrivacyMenuItem.title = nestedScrollWebView.getRequestsCount(EASYPRIVACY).toString() + " - " + getString(R.string.easyprivacy)
5233 // The resource request was blocked. Return an empty web resource response.
5234 return emptyWebResourceResponse
5235 } else if (easyPrivacyResults[0] == REQUEST_ALLOWED) { // The resource request matched EasyPrivacy's allow list.
5236 // Update the allow list result string array tracker.
5237 allowListResultStringArray = arrayOf(easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5])
5241 // Check Fanboy’s Annoyance List if it is enabled.
5242 if (nestedScrollWebView.fanboysAnnoyanceListEnabled) {
5243 // Check the URL against Fanboy's Annoyance List.
5244 val fanboysAnnoyanceListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, fanboysAnnoyanceList)
5246 // Process the Fanboy's Annoyance List results.
5247 if (fanboysAnnoyanceListResults[0] == REQUEST_BLOCKED) { // The resource request matched Fanboy's Annoyance List's block list.
5248 // Add the result to the resource requests.
5249 nestedScrollWebView.addResourceRequest(arrayOf(fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5250 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]))
5252 // Increment the blocked requests counters.
5253 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5254 nestedScrollWebView.incrementRequestsCount(FANBOYS_ANNOYANCE_LIST)
5256 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5257 if (webViewDisplayed) {
5258 // Updating the UI must be run from the UI thread.
5260 // Update the menu item titles.
5261 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5263 // Update the options menu if it has been populated.
5264 if (optionsMenu != null) {
5265 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5266 optionsFanboysAnnoyanceListMenuItem.title = nestedScrollWebView.getRequestsCount(FANBOYS_ANNOYANCE_LIST).toString() + " - " + getString(R.string.fanboys_annoyance_list)
5271 // The resource request was blocked. Return an empty web resource response.
5272 return emptyWebResourceResponse
5273 } else if (fanboysAnnoyanceListResults[0] == REQUEST_ALLOWED) { // The resource request matched Fanboy's Annoyance List's allow list.
5274 // Update the allow list result string array tracker.
5275 allowListResultStringArray = arrayOf(fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5276 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5])
5278 } else if (nestedScrollWebView.fanboysSocialBlockingListEnabled) { // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
5279 // Check the URL against Fanboy's Annoyance List.
5280 val fanboysSocialListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, fanboysSocialList)
5282 // Process the Fanboy's Social Blocking List results.
5283 if (fanboysSocialListResults[0] == REQUEST_BLOCKED) { // The resource request matched Fanboy's Social Blocking List's block list.
5284 // Add the result to the resource requests.
5285 nestedScrollWebView.addResourceRequest(arrayOf(fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5286 fanboysSocialListResults[4], fanboysSocialListResults[5]))
5288 // Increment the blocked requests counters.
5289 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5290 nestedScrollWebView.incrementRequestsCount(FANBOYS_SOCIAL_BLOCKING_LIST)
5292 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5293 if (webViewDisplayed) {
5294 // Updating the UI must be run from the UI thread.
5296 // Update the menu item titles.
5297 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5299 // Update the options menu if it has been populated.
5300 if (optionsMenu != null) {
5301 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5302 optionsFanboysSocialBlockingListMenuItem.title =
5303 nestedScrollWebView.getRequestsCount(FANBOYS_SOCIAL_BLOCKING_LIST).toString() + " - " + getString(R.string.fanboys_social_blocking_list)
5308 // The resource request was blocked. Return an empty web resource response.
5309 return emptyWebResourceResponse
5310 } else if (fanboysSocialListResults[0] == REQUEST_ALLOWED) { // The resource request matched Fanboy's Social Blocking List's allow list.
5311 // Update the allow list result string array tracker.
5312 allowListResultStringArray = arrayOf(fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3], fanboysSocialListResults[4],
5313 fanboysSocialListResults[5])
5317 // Add the request to the log because it hasn't been processed by any of the previous checks.
5318 if (allowListResultStringArray != null) { // The request was processed by an allow list.
5319 nestedScrollWebView.addResourceRequest(allowListResultStringArray)
5320 } else { // The request didn't match any filter list entry. Log it as a default request.
5321 nestedScrollWebView.addResourceRequest(arrayOf(REQUEST_DEFAULT, requestUrlString))
5324 // The resource request has not been blocked. `return null` loads the requested resource.
5328 // Handle HTTP authentication requests.
5329 override fun onReceivedHttpAuthRequest(view: WebView, handler: HttpAuthHandler, host: String, realm: String) {
5330 // Store the handler.
5331 nestedScrollWebView.httpAuthHandler = handler
5333 // Instantiate an HTTP authentication dialog.
5334 val httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm, nestedScrollWebView.webViewFragmentId)
5336 // Show the HTTP authentication dialog.
5337 httpAuthenticationDialogFragment.show(supportFragmentManager, getString(R.string.http_authentication))
5340 override fun onPageStarted(webView: WebView, url: String, favicon: Bitmap?) {
5341 // Get the app bar layout height. This can't be done in `applyAppSettings()` because the app bar is not yet populated there.
5342 // 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.
5343 if (appBarLayout.height > 0)
5344 appBarHeight = appBarLayout.height
5346 // Set the padding and layout settings according to the position of the app bar.
5347 if (bottomAppBar) { // The app bar is on the bottom.
5349 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) { // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
5350 // Reset the WebView padding to fill the available space.
5351 swipeRefreshLayout.setPadding(0, 0, 0, 0)
5352 } else { // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
5353 // Move the WebView above the app bar layout.
5354 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
5356 } else { // The app bar is on the top.
5357 // 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.
5358 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) { // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
5359 // No padding is needed because it will automatically be placed below the app bar layout due to the scrolling layout behavior.
5360 swipeRefreshLayout.setPadding(0, 0, 0, 0)
5362 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5363 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10, defaultProgressViewEndOffset)
5364 } else { // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
5365 // The swipe refresh layout must be manually moved below the app bar layout.
5366 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0)
5368 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5369 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight)
5373 // Reset the list of resource requests.
5374 nestedScrollWebView.clearResourceRequests()
5376 // Reset the requests counters.
5377 nestedScrollWebView.resetRequestsCounters()
5379 // Get the current page position.
5380 val currentPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
5382 // Update the URL text bar if the page is currently selected and the URL edit text is not currently being edited.
5383 if ((tabLayout.selectedTabPosition == currentPagePosition) && !urlEditText.hasFocus()) {
5384 // Display the formatted URL text. The nested scroll WebView current URL preserves any initial `view-source:`, and opposed to the method URL variable.
5385 urlEditText.setText(nestedScrollWebView.currentUrl)
5387 // Highlight the URL syntax.
5388 UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
5390 // Hide the keyboard.
5391 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.windowToken, 0)
5394 // Reset the list of host IP addresses.
5395 nestedScrollWebView.currentIpAddresses = ""
5397 // Get a URI for the current URL.
5398 val currentUri = Uri.parse(url)
5400 // Get the current domain name.
5401 val currentDomainName = currentUri.host
5403 // Get the IP addresses for the current domain.
5404 if (!currentDomainName.isNullOrEmpty())
5405 GetHostIpAddressesCoroutine.checkPinnedMismatch(currentDomainName, nestedScrollWebView, supportFragmentManager, getString(R.string.pinned_mismatch))
5407 // 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.)
5408 if ((optionsMenu != null) && (webView == currentWebView)) {
5410 optionsRefreshMenuItem.setTitle(R.string.stop)
5412 // Set the icon if it is displayed in the AppBar.
5413 if (displayAdditionalAppBarIcons)
5414 optionsRefreshMenuItem.setIcon(R.drawable.close_blue)
5418 override fun onPageFinished(webView: WebView, url: String) {
5419 // Flush any cookies to persistent storage. The cookie manager has become very lazy about flushing cookies in recent versions.
5420 if (nestedScrollWebView.acceptCookies)
5421 cookieManager.flush()
5423 // Update the Refresh menu item if the options menu has been created and the WebView is currently displayed.
5424 if (optionsMenu != null && (webView == currentWebView)) {
5425 // Reset the Refresh title.
5426 optionsRefreshMenuItem.setTitle(R.string.refresh)
5428 // Reset the icon if it is displayed in the app bar.
5429 if (displayAdditionalAppBarIcons)
5430 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled)
5433 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
5434 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
5435 val privateDataDirectoryString = applicationInfo.dataDir
5437 // Clear the cache, history, and logcat if Incognito Mode is enabled.
5438 if (incognitoModeEnabled) {
5439 // Clear the cache. `true` includes disk files.
5440 nestedScrollWebView.clearCache(true)
5442 // Clear the back/forward history.
5443 nestedScrollWebView.clearHistory()
5445 // Manually delete cache folders.
5447 // Delete the main cache directory.
5448 Runtime.getRuntime().exec("rm -rf $privateDataDirectoryString/cache")
5449 } catch (exception: IOException) {
5450 // Do nothing if an error is thrown.
5453 // Clear the logcat.
5455 // Clear the logcat. `-c` clears the logcat. `-b all` clears all the buffers (instead of just crash, main, and system).
5456 Runtime.getRuntime().exec("logcat -b all -c")
5457 } catch (exception: IOException) {
5462 // Clear the `Service Worker` directory.
5464 // A string array must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
5465 Runtime.getRuntime().exec(arrayOf("rm", "-rf", "$privateDataDirectoryString/app_webview/Default/Service Worker/"))
5466 } catch (exception: IOException) {
5470 // Get the current page position.
5471 val currentPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
5473 // 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.
5474 val currentUrl = nestedScrollWebView.url
5476 // Get the current tab.
5477 val tab = tabLayout.getTabAt(currentPagePosition)
5479 // Update the URL text bar if the page is currently selected and the user is not currently typing in the URL edit text.
5480 // Crash records show that, in some crazy way, it is possible for the current URL to be blank at this point.
5481 // Probably some sort of race condition when Privacy Browser is being resumed.
5482 if ((tabLayout.selectedTabPosition == currentPagePosition) && !urlEditText.hasFocus() && (currentUrl != null)) {
5483 // Check to see if the URL is `about:blank`.
5484 if (currentUrl == "about:blank") { // The WebView is blank.
5485 // Display the hint in the URL edit text.
5486 urlEditText.setText("")
5488 // Request focus for the URL text box.
5489 urlEditText.requestFocus()
5491 // Display the keyboard.
5492 inputMethodManager.showSoftInput(urlEditText, 0)
5494 // Apply the domain settings. This clears any settings from the previous domain.
5495 applyDomainSettings(nestedScrollWebView, "", resetTab = true, reloadWebsite = false, loadUrl = false)
5497 // Only populate the title text view if the tab has been fully created.
5499 // Get the custom view from the tab.
5500 val tabView = tab.customView!!
5502 // Get the title text view from the tab.
5503 val tabTitleTextView = tabView.findViewById<TextView>(R.id.title_textview)
5505 // Set the title as the tab text.
5506 tabTitleTextView.setText(R.string.new_tab)
5508 } else { // The WebView has loaded a webpage.
5509 // Update the URL edit text if it is not currently being edited.
5510 if (!urlEditText.hasFocus()) {
5511 // 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.
5512 val sanitizedUrl = sanitizeUrl(currentUrl)
5514 // Display the final URL. Getting the URL from the WebView instead of using the one provided by `onPageFinished()` makes websites like YouTube function correctly.
5515 urlEditText.setText(sanitizedUrl)
5517 // Highlight the URL syntax.
5518 UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
5521 // Only populate the title text view if the tab has been fully created.
5523 // Get the custom view from the tab.
5524 val tabView = tab.customView!!
5526 // Get the title text view from the tab.
5527 val tabTitleTextView = tabView.findViewById<TextView>(R.id.title_textview)
5529 // Set the title as the tab text. Sometimes `onReceivedTitle()` is not called, especially when navigating history.
5530 tabTitleTextView.text = nestedScrollWebView.title
5536 // Handle SSL Certificate errors. Suppress the lint warning that ignoring the error might be dangerous.
5537 @SuppressLint("WebViewClientOnReceivedSslError")
5538 override fun onReceivedSslError(view: WebView, handler: SslErrorHandler, error: SslError) {
5539 // Get the current website SSL certificate.
5540 val currentWebsiteSslCertificate = error.certificate
5542 // Extract the individual pieces of information from the current website SSL certificate.
5543 val currentWebsiteIssuedToCName = currentWebsiteSslCertificate.issuedTo.cName
5544 val currentWebsiteIssuedToOName = currentWebsiteSslCertificate.issuedTo.oName
5545 val currentWebsiteIssuedToUName = currentWebsiteSslCertificate.issuedTo.uName
5546 val currentWebsiteIssuedByCName = currentWebsiteSslCertificate.issuedBy.cName
5547 val currentWebsiteIssuedByOName = currentWebsiteSslCertificate.issuedBy.oName
5548 val currentWebsiteIssuedByUName = currentWebsiteSslCertificate.issuedBy.uName
5549 val currentWebsiteSslStartDate = currentWebsiteSslCertificate.validNotBeforeDate
5550 val currentWebsiteSslEndDate = currentWebsiteSslCertificate.validNotAfterDate
5552 // Get the pinned SSL certificate.
5553 val (pinnedSslCertificateStringArray, pinnedSslCertificateDateArray) = nestedScrollWebView.getPinnedSslCertificate()
5555 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
5556 if (nestedScrollWebView.hasPinnedSslCertificate() &&
5557 (currentWebsiteIssuedToCName == pinnedSslCertificateStringArray[0]) &&
5558 (currentWebsiteIssuedToOName == pinnedSslCertificateStringArray[1]) &&
5559 (currentWebsiteIssuedToUName == pinnedSslCertificateStringArray[2]) &&
5560 (currentWebsiteIssuedByCName == pinnedSslCertificateStringArray[3]) &&
5561 (currentWebsiteIssuedByOName == pinnedSslCertificateStringArray[4]) &&
5562 (currentWebsiteIssuedByUName == pinnedSslCertificateStringArray[5]) &&
5563 (currentWebsiteSslStartDate == pinnedSslCertificateDateArray[0]) &&
5564 (currentWebsiteSslEndDate == pinnedSslCertificateDateArray[1])) {
5566 // An SSL certificate is pinned and matches the current domain certificate. Proceed to the website without displaying an error.
5568 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
5569 // Store the SSL error handler.
5570 nestedScrollWebView.sslErrorHandler = handler
5572 // Instantiate an SSL certificate error alert dialog.
5573 val sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error, nestedScrollWebView.webViewFragmentId)
5575 // 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.
5577 // Show the SSL certificate error dialog.
5578 sslCertificateErrorDialogFragment.show(supportFragmentManager, getString(R.string.ssl_certificate_error))
5579 } catch (exception: Exception) {
5580 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
5581 pendingDialogsArrayList.add(PendingDialogDataClass(sslCertificateErrorDialogFragment, getString(R.string.ssl_certificate_error)))
5587 // Check to see if the state is being restored.
5588 if (restoringState) { // The state is being restored.
5589 // Resume the nested scroll WebView JavaScript timers.
5590 nestedScrollWebView.resumeTimers()
5591 } else if (pageNumber == 0) { // The first page is being loaded.
5592 // Set this nested scroll WebView as the current WebView.
5593 currentWebView = nestedScrollWebView
5595 // Get the intent that started the app.
5596 val launchingIntent = intent
5598 // Reset the intent. This prevents a duplicate tab from being created on restart.
5601 // Get the information from the intent.
5602 val launchingIntentAction = launchingIntent.action
5603 val launchingIntentUriData = launchingIntent.data
5604 val launchingIntentStringExtra = launchingIntent.getStringExtra(Intent.EXTRA_TEXT)
5606 // Parse the launching intent URL. Suppress the suggestions of using elvis expressions as they make the logic very difficult to follow.
5607 @Suppress("IfThenToElvis") val urlToLoadString = if ((launchingIntentAction != null) && (launchingIntentAction == Intent.ACTION_WEB_SEARCH)) { // The intent contains a search string.
5608 // Sanitize the search input and convert it to a search.
5609 val encodedSearchString = try {
5610 URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8")
5611 } catch (exception: UnsupportedEncodingException) {
5615 // Add the search URL to the encodedSearchString
5616 searchURL + encodedSearchString
5617 } else if (launchingIntentUriData != null) { // The launching intent contains a URL formatted as a URI.
5618 // Get the URL from the URI.
5619 launchingIntentUriData.toString()
5620 } else if (launchingIntentStringExtra != null) { // The launching intent contains text that might be a URL.
5621 // Get the URL from the string extra.
5622 launchingIntentStringExtra
5623 } else if (urlString != "") { // The activity has been restarted.
5624 // Load the saved URL.
5626 } else { // The is no saved URL and there is no URL in the intent.
5627 // Load the homepage.
5628 sharedPreferences.getString("homepage", getString(R.string.homepage_default_value))
5631 // Load the website if not waiting for the proxy.
5632 if (waitingForProxy) { // Store the URL to be loaded in the Nested Scroll WebView.
5633 nestedScrollWebView.waitingForProxyUrlString = urlToLoadString!!
5634 } else { // Load the URL.
5635 loadUrl(nestedScrollWebView, urlToLoadString!!)
5638 // 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.
5639 // 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.
5641 } else { // This is not the first tab.
5643 loadUrl(nestedScrollWebView, urlString)
5645 // Set the focus and display the keyboard if the URL is blank.
5646 if (urlString == "") {
5647 // Request focus for the URL text box.
5648 urlEditText.requestFocus()
5650 // Create a display keyboard handler.
5651 val displayKeyboardHandler = Handler(Looper.getMainLooper())
5653 // Create a display keyboard runnable.
5654 val displayKeyboardRunnable = Runnable {
5655 // Display the keyboard.
5656 inputMethodManager.showSoftInput(urlEditText, 0)
5659 // Display the keyboard after 100 milliseconds, which leaves enough time for the tab to transition.
5660 displayKeyboardHandler.postDelayed(displayKeyboardRunnable, 100)
5665 private fun loadBookmarksFolder() {
5666 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
5667 bookmarksCursor = bookmarksDatabaseHelper!!.getBookmarksByDisplayOrder(currentBookmarksFolderId)
5669 // Populate the bookmarks cursor adapter.
5670 bookmarksCursorAdapter = object : CursorAdapter(this, bookmarksCursor, false) {
5671 override fun newView(context: Context, cursor: Cursor, parent: ViewGroup): View {
5672 // Inflate the individual item layout.
5673 return layoutInflater.inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false)
5676 override fun bindView(view: View, context: Context, cursor: Cursor) {
5677 // Get handles for the views.
5678 val bookmarkFavoriteIcon = view.findViewById<ImageView>(R.id.bookmark_favorite_icon)
5679 val bookmarkNameTextView = view.findViewById<TextView>(R.id.bookmark_name)
5681 // Get the favorite icon byte array from the cursor.
5682 val favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndexOrThrow(FAVORITE_ICON))
5684 // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
5685 val favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.size)
5687 // Display the bitmap in the bookmark favorite icon.
5688 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap)
5690 // Display the bookmark name from the cursor in the bookmark name text view.
5691 bookmarkNameTextView.text = cursor.getString(cursor.getColumnIndexOrThrow(BOOKMARK_NAME))
5693 // Make the font bold for folders.
5694 if (cursor.getInt(cursor.getColumnIndexOrThrow(IS_FOLDER)) == 1)
5695 bookmarkNameTextView.typeface = Typeface.DEFAULT_BOLD
5696 else // Reset the font to default for normal bookmarks.
5697 bookmarkNameTextView.typeface = Typeface.DEFAULT
5701 // Populate the list view with the adapter.
5702 bookmarksListView.adapter = bookmarksCursorAdapter
5704 // Set the bookmarks drawer title.
5705 if (currentBookmarksFolderId == HOME_FOLDER_ID) // The current bookmarks folder is the home folder.
5706 bookmarksTitleTextView.setText(R.string.bookmarks)
5708 bookmarksTitleTextView.text = bookmarksDatabaseHelper!!.getFolderName(currentBookmarksFolderId)
5711 private fun loadUrl(nestedScrollWebView: NestedScrollWebView, url: String) {
5712 // Sanitize the URL.
5713 val urlString = sanitizeUrl(url)
5715 // Apply the domain settings and load the URL.
5716 applyDomainSettings(nestedScrollWebView, urlString, resetTab = true, reloadWebsite = false, loadUrl = true)
5719 private fun loadUrlFromTextBox() {
5720 // 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.
5721 var unformattedUrlString = urlEditText.text.toString().trim { it <= ' ' }
5723 // Create the formatted URL string.
5726 // Check to see if the unformatted URL string is a valid URL. Otherwise, convert it into a search.
5727 if (unformattedUrlString.startsWith("content://") || unformattedUrlString.startsWith("view-source:")) { // This is a content or source URL.
5728 // Load the entire content URL.
5729 urlString = unformattedUrlString
5730 } else if (Patterns.WEB_URL.matcher(unformattedUrlString).matches() || unformattedUrlString.startsWith("http://") || unformattedUrlString.startsWith("https://") ||
5731 unformattedUrlString.startsWith("file://")) { // This is a standard URL.
5733 // Add `https://` at the beginning if there is no protocol. Otherwise the app will segfault.
5734 if (!unformattedUrlString.startsWith("http") && !unformattedUrlString.startsWith("file://"))
5735 unformattedUrlString = "https://$unformattedUrlString"
5737 // Initialize the unformatted URL.
5738 var unformattedUrl: URL? = null
5740 // Convert the unformatted URL string to a URL.
5742 unformattedUrl = URL(unformattedUrlString)
5743 } catch (exception: MalformedURLException) {
5744 exception.printStackTrace()
5747 // Get the components of the URL.
5748 val scheme = unformattedUrl?.protocol
5749 val authority = unformattedUrl?.authority
5750 val path = unformattedUrl?.path
5751 val query = unformattedUrl?.query
5752 val fragment = unformattedUrl?.ref
5755 val uri = Uri.Builder()
5757 // Build the URI from the components of the URL.
5758 uri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment)
5760 // Decode the URI as a UTF-8 string in.
5762 urlString = URLDecoder.decode(uri.build().toString(), "UTF-8")
5763 } catch (exception: UnsupportedEncodingException) {
5764 // Do nothing. The formatted URL string will remain blank.
5766 } else if (unformattedUrlString.isNotEmpty()) { // This is not a URL, but rather a search string.
5767 // Sanitize the search input.
5768 val encodedSearchString = try {
5769 URLEncoder.encode(unformattedUrlString, "UTF-8")
5770 } catch (exception: UnsupportedEncodingException) {
5774 // Add the base search URL.
5775 urlString = searchURL + encodedSearchString
5778 // 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.
5779 urlEditText.clearFocus()
5782 loadUrl(currentWebView!!, urlString)
5785 override fun navigateHistory(url: String, steps: Int) {
5786 // Apply the domain settings.
5787 applyDomainSettings(currentWebView!!, url, resetTab = false, reloadWebsite = false, loadUrl = false)
5789 // Load the history entry.
5790 currentWebView!!.goBackOrForward(steps)
5792 // Update the URL edit text after a delay.
5793 updateUrlEditTextAfterDelay()
5796 override fun openFile(dialogFragment: DialogFragment) {
5798 val dialog = dialogFragment.dialog!!
5800 // Get handles for the views.
5801 val fileNameEditText = dialog.findViewById<EditText>(R.id.file_name_edittext)
5802 val mhtCheckBox = dialog.findViewById<CheckBox>(R.id.mht_checkbox)
5804 // Get the file path string.
5805 val openFilePath = fileNameEditText.text.toString()
5807 // Apply the domain settings. This resets the favorite icon and removes any domain settings.
5808 applyDomainSettings(currentWebView!!, openFilePath, resetTab = true, reloadWebsite = false, loadUrl = false)
5810 // Open the file according to the type.
5811 if (mhtCheckBox.isChecked) { // Force opening of an MHT file.
5813 // Get the MHT file input stream.
5814 val mhtFileInputStream = contentResolver.openInputStream(Uri.parse(openFilePath))
5816 // Create a temporary MHT file.
5817 val temporaryMhtFile = File.createTempFile(TEMPORARY_MHT_FILE, ".mht", cacheDir)
5819 // Get a file output stream for the temporary MHT file.
5820 val temporaryMhtFileOutputStream = FileOutputStream(temporaryMhtFile)
5822 // Create a transfer byte array.
5823 val transferByteArray = ByteArray(1024)
5825 // Create an integer to track the number of bytes read.
5828 // Copy the temporary MHT file input stream to the MHT output stream.
5829 while (mhtFileInputStream!!.read(transferByteArray).also { bytesRead = it } > 0)
5830 temporaryMhtFileOutputStream.write(transferByteArray, 0, bytesRead)
5832 // Flush the temporary MHT file output stream.
5833 temporaryMhtFileOutputStream.flush()
5835 // Close the streams.
5836 temporaryMhtFileOutputStream.close()
5837 mhtFileInputStream.close()
5839 // Load the temporary MHT file.
5840 currentWebView!!.loadUrl(temporaryMhtFile.toString())
5841 } catch (exception: Exception) {
5842 // Display a snackbar.
5843 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
5845 } else { // Let the WebView handle opening of the file.
5847 currentWebView!!.loadUrl(openFilePath)
5851 private fun openWithApp(url: String) {
5852 // Create an open with app intent with `ACTION_VIEW`.
5853 val openWithAppIntent = Intent(Intent.ACTION_VIEW)
5855 // Set the URI but not the MIME type. This should open all available apps.
5856 openWithAppIntent.data = Uri.parse(url)
5858 // Flag the intent to open in a new task.
5859 openWithAppIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
5863 // Show the chooser.
5864 startActivity(openWithAppIntent)
5865 } catch (exception: ActivityNotFoundException) { // There are no apps available to open the URL.
5866 // Show a snackbar with the error.
5867 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
5871 private fun openWithBrowser(url: String) {
5873 // Create an open with browser intent with `ACTION_VIEW`.
5874 val openWithBrowserIntent = Intent(Intent.ACTION_VIEW)
5876 // Set the URI and the MIME type. `"text/html"` should load browser options.
5877 openWithBrowserIntent.setDataAndType(Uri.parse(url), "text/html")
5879 // Flag the intent to open in a new task.
5880 openWithBrowserIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
5884 // Show the chooser.
5885 startActivity(openWithBrowserIntent)
5886 } catch (exception: ActivityNotFoundException) { // There are no browsers available to open the URL.
5887 // Show a snackbar with the error.
5888 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
5892 override fun pinnedErrorGoBack() {
5893 // Get the current web back forward list.
5894 val webBackForwardList = currentWebView!!.copyBackForwardList()
5896 // Get the previous entry URL.
5897 val previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex - 1).url
5899 // Apply the domain settings.
5900 applyDomainSettings(currentWebView!!, previousUrl, resetTab = false, reloadWebsite = false, loadUrl = false)
5903 currentWebView!!.goBack()
5905 // Update the URL edit text after a delay.
5906 updateUrlEditTextAfterDelay()
5909 private fun sanitizeUrl(urlString: String): String {
5910 // Initialize a sanitized URL string.
5911 var sanitizedUrlString = urlString
5913 // Sanitize tracking queries.
5914 if (sanitizeTrackingQueries)
5915 sanitizedUrlString = SanitizeUrlHelper.sanitizeTrackingQueries(sanitizedUrlString)
5917 // Sanitize AMP redirects.
5918 if (sanitizeAmpRedirects)
5919 sanitizedUrlString = SanitizeUrlHelper.sanitizeAmpRedirects(sanitizedUrlString)
5921 // Return the sanitized URL string.
5922 return sanitizedUrlString
5925 override fun saveUrl(originalUrlString: String, fileNameString: String, dialogFragment: DialogFragment) {
5926 // Store the URL. This will be used in the save URL activity result launcher.
5927 saveUrlString = if (originalUrlString.startsWith("data:")) {
5928 // Save the original URL.
5932 val dialog = dialogFragment.dialog!!
5934 // Get a handle for the dialog URL edit text.
5935 val dialogUrlEditText = dialog.findViewById<EditText>(R.id.url_edittext)
5937 // Get the URL from the edit text, which may have been modified.
5938 dialogUrlEditText.text.toString()
5941 // Open the file picker.
5942 saveUrlActivityResultLauncher.launch(fileNameString)
5945 private fun setCurrentWebView(pageNumber: Int) {
5946 // Stop the swipe to refresh indicator if it is running
5947 swipeRefreshLayout.isRefreshing = false
5949 // Get the WebView tab fragment.
5950 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(pageNumber)
5952 // Get the fragment view.
5953 val webViewFragmentView = webViewTabFragment.view
5955 // Set the current WebView if the fragment view is not null.
5956 if (webViewFragmentView != null) { // The fragment has been populated.
5957 // Store the current WebView.
5958 currentWebView = webViewFragmentView.findViewById(R.id.nestedscroll_webview)
5960 // Update the status of swipe to refresh.
5961 if (currentWebView!!.swipeToRefresh) { // Swipe to refresh is enabled.
5962 // Enable the swipe refresh layout if the WebView is scrolled all the way to the top. It is updated every time the scroll changes.
5963 swipeRefreshLayout.isEnabled = (currentWebView!!.scrollY == 0)
5964 } else { // Swipe to refresh is disabled.
5965 // Disable the swipe refresh layout.
5966 swipeRefreshLayout.isEnabled = false
5969 // Set the cookie status.
5970 cookieManager.setAcceptCookie(currentWebView!!.acceptCookies)
5972 // Update the privacy icons. `true` redraws the icons in the app bar.
5973 updatePrivacyIcons(true)
5975 // Get a handle for the input method manager.
5976 val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
5978 // Get the current URL.
5979 val urlString = currentWebView!!.url
5981 // Update the URL edit text if not loading a new intent. Otherwise, this will be handled by `onPageStarted()` (if called) and `onPageFinished()`.
5982 if (!loadingNewIntent) { // A new intent is not being loaded.
5983 if ((urlString == null) || (urlString == "about:blank")) { // The WebView is blank.
5984 // Display the hint in the URL edit text.
5985 urlEditText.setText("")
5987 // Request focus for the URL text box.
5988 urlEditText.requestFocus()
5990 // Display the keyboard.
5991 inputMethodManager.showSoftInput(urlEditText, 0)
5992 } else { // The WebView has a loaded URL.
5993 // Clear the focus from the URL text box.
5994 urlEditText.clearFocus()
5996 // Hide the soft keyboard.
5997 inputMethodManager.hideSoftInputFromWindow(currentWebView!!.windowToken, 0)
5999 // Display the current URL in the URL text box.
6000 urlEditText.setText(urlString)
6002 // Highlight the URL syntax.
6003 UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
6005 } else { // A new intent is being loaded.
6006 // Reset the loading new intent flag.
6007 loadingNewIntent = false
6010 // Set the background to indicate the domain settings status.
6011 if (currentWebView!!.domainSettingsApplied) {
6012 // Set a background on the URL relative layout to indicate that custom domain settings are being used.
6013 urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.drawable.domain_settings_url_background)
6015 // Remove any background on the URL relative layout.
6016 urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.color.transparent)
6018 } else if ((pageNumber == savedTabPosition) || (pageNumber >= (webViewStateAdapter!!.itemCount - 1))) { // The tab has not been populated yet.
6019 // Try again in 100 milliseconds if the app is being restored or the a new tab has been added (the last tab).
6020 // Create a handler to set the current WebView.
6021 val setCurrentWebViewHandler = Handler(Looper.getMainLooper())
6023 // Create a runnable to set the current WebView.
6024 val setCurrentWebWebRunnable = Runnable {
6025 // Set the current WebView.
6026 setCurrentWebView(pageNumber)
6029 // Try setting the current WebView again after 100 milliseconds.
6030 setCurrentWebViewHandler.postDelayed(setCurrentWebWebRunnable, 100)
6034 // The view parameter cannot be removed because it is called from the layout onClick.
6035 fun toggleBookmarksDrawerPinned(@Suppress("UNUSED_PARAMETER")view: View?) {
6036 // Toggle the bookmarks drawer pinned tracker.
6037 bookmarksDrawerPinned = !bookmarksDrawerPinned
6039 // Update the bookmarks drawer pinned image view.
6040 updateBookmarksDrawerPinnedImageView()
6043 private fun updateBookmarksDrawerPinnedImageView() {
6044 // Set the current icon.
6045 if (bookmarksDrawerPinned)
6046 bookmarksDrawerPinnedImageView.setImageResource(R.drawable.pin_selected)
6048 bookmarksDrawerPinnedImageView.setImageResource(R.drawable.pin)
6051 private fun updateDomainsSettingsSet() {
6052 // Reset the domains settings set.
6053 domainsSettingsSet = HashSet()
6055 // Get a domains cursor.
6056 val domainsCursor = domainsDatabaseHelper!!.domainNameCursorOrderedByDomain
6058 // Get the current count of domains.
6059 val domainsCount = domainsCursor.count
6061 // Get the domain name column index.
6062 val domainNameColumnIndex = domainsCursor.getColumnIndexOrThrow(DOMAIN_NAME)
6064 // Populate the domain settings set.
6065 for (i in 0 until domainsCount) {
6066 // Move the domains cursor to the current row.
6067 domainsCursor.moveToPosition(i)
6069 // Store the domain name in the domain settings set.
6070 domainsSettingsSet.add(domainsCursor.getString(domainNameColumnIndex))
6073 // Close the domains cursor.
6074 domainsCursor.close()
6077 override fun updateFontSize(dialogFragment: DialogFragment) {
6079 val dialog = dialogFragment.dialog!!
6081 // Get a handle for the font size edit text.
6082 val fontSizeEditText = dialog.findViewById<EditText>(R.id.font_size_edittext)
6084 // Initialize the new font size variable with the current font size.
6085 var newFontSize = currentWebView!!.settings.textZoom
6087 // Get the font size from the edit text.
6089 newFontSize = fontSizeEditText.text.toString().toInt()
6090 } catch (exception: Exception) {
6091 // If the edit text does not contain a valid font size do nothing.
6094 // Apply the new font size.
6095 currentWebView!!.settings.textZoom = newFontSize
6098 private fun updatePrivacyIcons(runInvalidateOptionsMenu: Boolean) {
6099 // Only update the privacy icons if the options menu and the current WebView have already been populated.
6100 if ((optionsMenu != null) && (currentWebView != null)) {
6101 // Update the privacy icon.
6102 if (currentWebView!!.settings.javaScriptEnabled) // JavaScript is enabled.
6103 optionsPrivacyMenuItem.setIcon(R.drawable.javascript_enabled)
6104 else if (currentWebView!!.acceptCookies) // JavaScript is disabled but cookies are enabled.
6105 optionsPrivacyMenuItem.setIcon(R.drawable.warning)
6106 else // All the dangerous features are disabled.
6107 optionsPrivacyMenuItem.setIcon(R.drawable.privacy_mode)
6109 // Update the cookies icon.
6110 if (currentWebView!!.acceptCookies)
6111 optionsCookiesMenuItem.setIcon(R.drawable.cookies_enabled)
6113 optionsCookiesMenuItem.setIcon(R.drawable.cookies_disabled)
6115 // Update the refresh icon.
6116 if (optionsRefreshMenuItem.title == getString(R.string.refresh)) // The refresh icon is displayed.
6117 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled)
6118 else // The stop icon is displayed.
6119 optionsRefreshMenuItem.setIcon(R.drawable.close_blue)
6121 // `invalidateOptionsMenu()` calls `onPrepareOptionsMenu()` and redraws the icons in the app bar.
6122 if (runInvalidateOptionsMenu)
6123 invalidateOptionsMenu()
6127 fun updateUrlEditTextAfterDelay() {
6128 // Create a handler to update the URL edit box.
6129 val urlEditTextUpdateHandler = Handler(Looper.getMainLooper())
6131 // Create a runnable to update the URL edit box.
6132 val urlEditTextUpdateRunnable = Runnable {
6133 // Update the URL edit text.
6134 urlEditText.setText(currentWebView!!.url)
6136 // Disable the wide viewport if the source is being viewed.
6137 if (currentWebView!!.url!!.startsWith("view-source:"))
6138 currentWebView!!.settings.useWideViewPort = false
6141 // Update the URL edit text after 50 milliseconds, so that the WebView has enough time to navigate to the new URL.
6142 urlEditTextUpdateHandler.postDelayed(urlEditTextUpdateRunnable, 50)