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 optionsWideViewportMenuItem: MenuItem
325 private lateinit var proxyHelper: ProxyHelper
326 private lateinit var redColorSpan: ForegroundColorSpan
327 private lateinit var rootFrameLayout: FrameLayout
328 private lateinit var saveUrlString: String
329 private lateinit var searchURL: String
330 private lateinit var sharedPreferences: SharedPreferences
331 private lateinit var swipeRefreshLayout: SwipeRefreshLayout
332 private lateinit var tabLayout: TabLayout
333 private lateinit var tabsLinearLayout: LinearLayout
334 private lateinit var toolbar: Toolbar
335 private lateinit var webViewDefaultUserAgent: String
336 private lateinit var webViewThemeEntryValuesStringArray: Array<String>
337 private lateinit var webViewViewPager2: ViewPager2
338 private lateinit var ultraList: ArrayList<List<Array<String>>>
339 private lateinit var urlEditText: EditText
340 private lateinit var urlRelativeLayout: RelativeLayout
341 private lateinit var userAgentDataArray: Array<String>
342 private lateinit var userAgentNamesArray: ArrayAdapter<CharSequence>
344 // Define the class variables.
345 private var actionBarDrawerToggle: ActionBarDrawerToggle? = null
346 private var appBarHeight = 0
347 private var bookmarksCursor: Cursor? = null
348 private var bookmarksDatabaseHelper: BookmarksDatabaseHelper? = null
349 private var bookmarksDrawerPinned = false
350 private var bottomAppBar = false
351 private var currentWebView: NestedScrollWebView? = null
352 private var defaultBlockAllThirdPartyRequests = false
353 private var defaultCookies = false
354 private var defaultDisplayWebpageImages = true
355 private var defaultDomStorage = false
356 private var defaultEasyList = true
357 private var defaultEasyPrivacy = true
358 private var defaultFanboysAnnoyanceList = true
359 private var defaultFanboysSocialBlockingList = true
360 private var defaultFormData = false // Form data can be removed once the minimum API >= 26.
361 private var defaultProgressViewEndOffset = 0
362 private var defaultProgressViewStartOffset = 0
363 private var defaultJavaScript = false
364 private var defaultSwipeToRefresh = true
365 private var defaultUltraList = true
366 private var defaultUltraPrivacy = true
367 private var defaultWideViewport = true
368 private var displayAdditionalAppBarIcons = false
369 private var displayingFullScreenVideo = false
370 private var domainsDatabaseHelper: DomainsDatabaseHelper? = null
371 private var downloadWithExternalApp = false
372 private var fullScreenBrowsingModeEnabled = false
373 private var hideAppBar = false
374 private var inFullScreenBrowsingMode = false
375 private var incognitoModeEnabled = false
376 private var loadingNewIntent = false
377 private var objectAnimator = ObjectAnimator()
378 private var optionsMenu: Menu? = null
379 private var orbotStatusBroadcastReceiver: BroadcastReceiver? = null
380 private var reapplyAppSettingsOnRestart = false
381 private var reapplyDomainSettingsOnRestart = false
382 private var sanitizeAmpRedirects = false
383 private var sanitizeTrackingQueries = false
384 private var savedProxyMode: String? = null
385 private var savedNestedScrollWebViewStateArrayList: ArrayList<Bundle>? = null
386 private var savedStateArrayList: ArrayList<Bundle>? = null
387 private var savedTabPosition = 0
388 private var scrollAppBar = false
389 private var ultraPrivacy: ArrayList<List<Array<String>>>? = null
390 private var waitingForProxy = false
392 // Define the save webpage image activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
393 private val browseFileUploadActivityResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { activityResult ->
394 // Pass the file to the WebView.
395 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(activityResult.resultCode, activityResult.data))
398 // Define the save URL activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
399 private val saveUrlActivityResultLauncher = registerForActivityResult<String, Uri>(ActivityResultContracts.CreateDocument("*/*")) { fileUri ->
400 // Only save the URL if the file URI is not null, which happens if the user exited the file picker by pressing back.
401 if (fileUri != null) {
402 // Instantiate the save URL coroutine.
403 val saveUrlCoroutine = SaveUrlCoroutine()
406 saveUrlCoroutine.save(this, this, saveUrlString, fileUri, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
409 // Reset the save URL string.
413 // Define the save webpage archive activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
414 private val saveWebpageArchiveActivityResultLauncher = registerForActivityResult<String, Uri>(ActivityResultContracts.CreateDocument("multipart/related")) { fileUri ->
415 // Only save the webpage archive if the file URI is not null, which happens if the user exited the file picker by pressing back.
416 if (fileUri != null) {
417 // Initialize the file name string from the file URI last path segment.
418 var fileNameString = fileUri.lastPathSegment
420 // Query the exact file name if the API >= 26.
421 if (Build.VERSION.SDK_INT >= 26) {
422 // Get a cursor from the content resolver.
423 val contentResolverCursor = contentResolver.query(fileUri, null, null, null)!!
425 // Move to the fist row.
426 contentResolverCursor.moveToFirst()
428 // Get the file name from the cursor.
429 fileNameString = contentResolverCursor.getString(contentResolverCursor.getColumnIndexOrThrow(OpenableColumns.DISPLAY_NAME))
432 contentResolverCursor.close()
435 // Use a coroutine to save the file.
436 CoroutineScope(Dispatchers.Main).launch {
438 // Create the file on the IO thread.
439 withContext(Dispatchers.IO) {
440 // Create a temporary MHT file.
441 val temporaryMhtFile = File.createTempFile(TEMPORARY_MHT_FILE, ".mht", cacheDir)
443 // The WebView must be accessed from the main thread.
444 withContext(Dispatchers.Main) {
445 currentWebView!!.saveWebArchive(temporaryMhtFile.toString(), false) { callbackValue ->
446 if (callbackValue != null) { // The temporary MHT file was saved successfully.
448 // Create a temporary MHT file input stream.
449 val temporaryMhtFileInputStream = FileInputStream(temporaryMhtFile)
451 // Get an output stream for the save webpage file path.
452 val mhtOutputStream = contentResolver.openOutputStream(fileUri)!!
454 // Create a transfer byte array.
455 val transferByteArray = ByteArray(1024)
457 // Create an integer to track the number of bytes read.
460 // Copy the temporary MHT file input stream to the MHT output stream.
461 while (temporaryMhtFileInputStream.read(transferByteArray).also { bytesRead = it } > 0)
462 mhtOutputStream.write(transferByteArray, 0, bytesRead)
464 // Close the streams.
465 mhtOutputStream.close()
466 temporaryMhtFileInputStream.close()
468 // Display a snackbar.
469 Snackbar.make(currentWebView!!, getString(R.string.saved, fileNameString), Snackbar.LENGTH_SHORT).show()
470 } catch (exception: Exception) {
471 // Display snackbar with the exception.
472 Snackbar.make(currentWebView!!, getString(R.string.error_saving_file, fileNameString, exception), Snackbar.LENGTH_INDEFINITE).show()
474 // Delete the temporary MHT file.
475 temporaryMhtFile.delete()
477 } else { // There was an unspecified error while saving the temporary MHT file.
478 // Display a snackbar.
479 Snackbar.make(currentWebView!!, getString(R.string.error_saving_file, fileNameString, getString(R.string.unknown_error)), Snackbar.LENGTH_INDEFINITE).show()
484 } catch (ioException: IOException) {
485 // Display a snackbar with the IO exception.
486 Snackbar.make(currentWebView!!, getString(R.string.error_saving_file, fileNameString, ioException), Snackbar.LENGTH_INDEFINITE).show()
492 // Define the save webpage image activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
493 private val saveWebpageImageActivityResultLauncher = registerForActivityResult<String, Uri>(ActivityResultContracts.CreateDocument("image/png")) { fileUri ->
494 // Only save the webpage image if the file URI is not null, which happens if the user exited the file picker by pressing back.
495 if (fileUri != null) {
496 // Instantiate the save webpage image coroutine.
497 val saveWebpageImageCoroutine = SaveWebpageImageCoroutine()
499 // Save the webpage image.
500 saveWebpageImageCoroutine.save(this, fileUri, currentWebView!!)
504 override fun onCreate(savedInstanceState: Bundle?) {
505 // Run the default commands.
506 super.onCreate(savedInstanceState)
508 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
509 PreferenceManager.setDefaultValues(this, R.xml.preferences, false)
511 // Get a handle for the shared preferences.
512 sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
514 // Get the preferences.
515 val appTheme = sharedPreferences.getString(getString(R.string.app_theme_key), getString(R.string.app_theme_default_value))
516 val allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false)
517 bottomAppBar = sharedPreferences.getBoolean(getString(R.string.bottom_app_bar_key), false)
518 displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false)
520 // Get the theme entry values string array.
521 val appThemeEntryValuesStringArray = resources.getStringArray(R.array.app_theme_entry_values)
523 // Get the current theme status.
524 val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
526 // 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.
527 if (appTheme == appThemeEntryValuesStringArray[1]) { // The light theme is selected.
528 // Apply the light theme.
529 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
530 } else if (appTheme == appThemeEntryValuesStringArray[2]) { // The dark theme is selected.
531 // Apply the dark theme.
532 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
533 } else { // The system default theme is selected.
534 if (Build.VERSION.SDK_INT >= 28) { // The system default theme is supported.
535 // Follow the system default theme.
536 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
537 } else { // The system default theme is not supported.
538 // Follow the battery saver mode.
539 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY)
543 // Do not continue if the app theme is different than the OS theme. The app always initially starts in the OS theme.
544 // 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.
545 // 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.
546 // See https://redmine.stoutner.com/issues/952.
547 if ((appTheme == appThemeEntryValuesStringArray[0]) || // The system default theme is used.
548 ((appTheme == appThemeEntryValuesStringArray[1]) && (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO)) || // The app is running in day theme as desired.
549 ((appTheme == appThemeEntryValuesStringArray[2]) && (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES))) { // The app is running in night theme as desired.
551 // Disable screenshots if not allowed.
552 if (!allowScreenshots) {
553 window.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
556 // Check to see if the activity has been restarted.
557 if (savedInstanceState != null) {
558 // Store the saved instance state variables. The deprecated `getParcelableArrayList` can be upgraded once the minimum API >= 33.
559 bookmarksDrawerPinned = savedInstanceState.getBoolean(BOOKMARKS_DRAWER_PINNED)
560 @Suppress("DEPRECATION")
561 savedStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_STATE_ARRAY_LIST)
562 @Suppress("DEPRECATION")
563 savedNestedScrollWebViewStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST)
564 savedTabPosition = savedInstanceState.getInt(SAVED_TAB_POSITION)
565 savedProxyMode = savedInstanceState.getString(PROXY_MODE)
568 // 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.
569 WebView.enableSlowWholeDocumentDraw()
571 // Set the content view according to the position of the app bar.
573 setContentView(R.layout.main_framelayout_bottom_appbar)
575 setContentView(R.layout.main_framelayout_top_appbar)
577 // Get handles for the views.
578 rootFrameLayout = findViewById(R.id.root_framelayout)
579 drawerLayout = findViewById(R.id.drawerlayout)
580 coordinatorLayout = findViewById(R.id.coordinatorlayout)
581 appBarLayout = findViewById(R.id.appbar_layout)
582 toolbar = findViewById(R.id.toolbar)
583 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout)
584 findOnPageEditText = findViewById(R.id.find_on_page_edittext)
585 findOnPageCountTextView = findViewById(R.id.find_on_page_count_textview)
586 tabsLinearLayout = findViewById(R.id.tabs_linearlayout)
587 tabLayout = findViewById(R.id.tablayout)
588 swipeRefreshLayout = findViewById(R.id.swiperefreshlayout)
589 webViewViewPager2 = findViewById(R.id.webview_viewpager2)
590 val navigationView = findViewById<NavigationView>(R.id.navigationview)
591 bookmarksListView = findViewById(R.id.bookmarks_drawer_listview)
592 bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview)
593 bookmarksDrawerPinnedImageView = findViewById(R.id.bookmarks_drawer_pinned_imageview)
594 fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout)
596 // Get a handle for the navigation menu.
597 val navigationMenu = navigationView.menu
599 // Get handles for the navigation menu items.
600 navigationBackMenuItem = navigationMenu.findItem(R.id.back)
601 navigationForwardMenuItem = navigationMenu.findItem(R.id.forward)
602 navigationHistoryMenuItem = navigationMenu.findItem(R.id.history)
603 navigationRequestsMenuItem = navigationMenu.findItem(R.id.requests)
605 // Listen for touches on the navigation menu.
606 navigationView.setNavigationItemSelectedListener(this)
608 // Set the support action bar.
609 setSupportActionBar(toolbar)
611 // Get a handle for the app bar.
612 appBar = supportActionBar!!
614 // Set the custom app bar layout, which shows the URL text bar.
615 appBar.setCustomView(R.layout.url_app_bar)
617 // Display the custom app bar layout.
618 appBar.displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM
620 // Get handles for the views in the URL app bar.
621 urlRelativeLayout = findViewById(R.id.url_relativelayout)
622 urlEditText = findViewById(R.id.url_edittext)
624 // Create the hamburger icon at the start of the AppBar.
625 actionBarDrawerToggle = ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer)
627 // Initially disable the sliding drawers. They will be enabled once the filter lists are loaded.
628 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
630 // Initially hide the user interface so that only the filter list loading screen is shown (if reloading).
631 drawerLayout.visibility = View.GONE
633 // Initialize the WebView state adapter.
634 webViewStateAdapter = WebViewStateAdapter(this)
636 // Set the pager adapter on the web view pager.
637 webViewViewPager2.adapter = webViewStateAdapter
639 // Store up to 100 tabs in memory.
640 webViewViewPager2.offscreenPageLimit = 100
642 // Disable swiping between pages in the view pager.
643 webViewViewPager2.isUserInputEnabled = false
645 // Get a handle for the cookie manager.
646 cookieManager = CookieManager.getInstance()
648 // Instantiate the helpers.
649 bookmarksDatabaseHelper = BookmarksDatabaseHelper(this)
650 domainsDatabaseHelper = DomainsDatabaseHelper(this)
651 proxyHelper = ProxyHelper()
653 // Update the bookmarks drawer pinned image view.
654 updateBookmarksDrawerPinnedImageView()
656 // Initialize the app.
659 // Apply the app settings from the shared preferences.
662 // Control what the system back command does.
663 val onBackPressedCallback: OnBackPressedCallback = object : OnBackPressedCallback(true) {
664 override fun handleOnBackPressed() {
665 // Process the different back options.
666 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
667 // Close the navigation drawer.
668 drawerLayout.closeDrawer(GravityCompat.START)
669 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)) { // The bookmarks drawer is open.
670 // close the bookmarks drawer.
671 drawerLayout.closeDrawer(GravityCompat.END)
672 } else if (displayingFullScreenVideo) { // A full screen video is shown.
673 // Exit the full screen video.
674 exitFullScreenVideo()
675 // It shouldn't be possible for the currentWebView to be null, but crash logs indicate it sometimes happens.
676 } else if (currentWebView != null && currentWebView!!.canGoBack()) { // There is at least one item in the current WebView history.
677 // Get the current web back forward list.
678 val webBackForwardList = currentWebView!!.copyBackForwardList()
680 // Get the previous entry URL.
681 val previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex - 1).url
683 // Apply the domain settings.
684 applyDomainSettings(currentWebView!!, previousUrl, resetTab = false, reloadWebsite = false, loadUrl = false)
687 currentWebView!!.goBack()
688 } else { // Close the current tab.
689 // A view is required because the method is also called by an XML `onClick`.
695 // Register the on back pressed callback.
696 onBackPressedDispatcher.addCallback(this, onBackPressedCallback)
698 // Instantiate the populate filter lists coroutine.
699 val populateFilterListsCoroutine = PopulateFilterListsCoroutine(this)
701 // Populate the filter lists.
702 populateFilterListsCoroutine.populateFilterLists(this)
706 public override fun onPostCreate(savedInstanceState: Bundle?) {
707 // Run the default commands.
708 super.onPostCreate(savedInstanceState)
710 // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished. This creates the navigation drawer icon.
711 // If the app is restarting to change the app theme the action bar drawer toggle will not yet be populated.
712 actionBarDrawerToggle?.syncState()
715 override fun onNewIntent(intent: Intent) {
716 // Run the default commands.
717 super.onNewIntent(intent)
719 // Get the information from the intent.
720 val intentAction = intent.action
721 val intentUriData = intent.data
722 val intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT)
724 // Determine if this is a web search.
725 val isWebSearch = (intentAction != null) && (intentAction == Intent.ACTION_WEB_SEARCH)
727 // Check to see if the app is being restarted from a saved state.
728 if (ultraPrivacy != null) { // The activity is not being restarted from a saved state.
729 // 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.
730 if ((intentUriData != null) || (intentStringExtra != null) || isWebSearch) {
731 // Exit the full screen video if it is displayed.
732 if (displayingFullScreenVideo) {
733 // Exit full screen video mode.
734 exitFullScreenVideo()
736 // Reload the current WebView. Otherwise, it can display entirely black.
737 currentWebView!!.reload()
741 val url = if (isWebSearch) { // The intent is a web search.
742 // Sanitize the search input and convert it to a search.
743 val encodedSearchString = try {
744 URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8")
745 } catch (exception: UnsupportedEncodingException) {
749 // Add the base search URL.
750 searchURL + encodedSearchString
751 } else { // The intent contains a URL in either the data or an extra.
752 intentUriData?.toString() ?: intentStringExtra
755 // Add a new tab if specified in the preferences.
756 if (sharedPreferences.getBoolean(getString(R.string.open_intents_in_new_tab_key), true)) { // Load the URL in a new tab.
757 // Set the loading new intent flag.
758 loadingNewIntent = true
761 addNewTab(url!!, true)
762 } else { // Load the URL in the current tab.
764 loadUrl(currentWebView!!, url!!)
767 // Close the navigation drawer if it is open.
768 if (drawerLayout.isDrawerVisible(GravityCompat.START))
769 drawerLayout.closeDrawer(GravityCompat.START)
771 // Close the bookmarks drawer if it is open.
772 if (drawerLayout.isDrawerVisible(GravityCompat.END))
773 drawerLayout.closeDrawer(GravityCompat.END)
775 } else { // The app has been restarted.
776 // If the new intent will open a new tab, set the saved tab position to be the size of the saved state array list.
777 // The tab position is 0 based, meaning the at the new tab will be the tab position that is restored.
778 if ((intentUriData != null) || (intentStringExtra != null) || isWebSearch)
779 savedTabPosition = savedStateArrayList!!.size
781 // Replace the intent that started the app with this one. This will load the tab after the others have been restored.
786 public override fun onRestart() {
787 // Run the default commands.
790 // Apply the app settings if returning from the Settings activity.
791 if (reapplyAppSettingsOnRestart) {
792 // Reset the reapply app settings on restart flag.
793 reapplyAppSettingsOnRestart = false
795 // Apply the app settings.
799 // Apply the domain settings if returning from the settings or domains activity.
800 if (reapplyDomainSettingsOnRestart) {
801 // Reset the reapply domain settings on restart flag.
802 reapplyDomainSettingsOnRestart = false
804 // Update the domains settings set.
805 updateDomainsSettingsSet()
807 // Reapply the domain settings for each tab.
808 for (i in 0 until webViewStateAdapter!!.itemCount) {
809 // Get the WebView tab fragment.
810 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
812 // Get the fragment view.
813 val fragmentView = webViewTabFragment.view
815 // Only reload the WebViews if they exist.
816 if (fragmentView != null) {
817 // Get the nested scroll WebView from the tab fragment.
818 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
820 // Reset the current domain name so the domain settings will be reapplied.
821 nestedScrollWebView.currentDomainName = ""
823 // Reapply the domain settings if the URL is not null, which happens for empty tabs when returning from settings.
824 if (nestedScrollWebView.url != null)
825 applyDomainSettings(nestedScrollWebView, nestedScrollWebView.url, resetTab = false, reloadWebsite = true, loadUrl = false)
830 // Update the bookmarks drawer if returning from the Bookmarks activity.
831 if (restartFromBookmarksActivity) {
832 // Reset the restart from bookmarks activity flag.
833 restartFromBookmarksActivity = false
835 // Close the bookmarks drawer.
836 drawerLayout.closeDrawer(GravityCompat.END)
838 // Reload the bookmarks drawer.
839 loadBookmarksFolder()
842 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
843 updatePrivacyIcons(true)
846 // `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.
847 public override fun onStart() {
848 // Run the default commands.
851 // 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.
852 if (webViewStateAdapter != null) {
853 for (i in 0 until webViewStateAdapter!!.itemCount) {
854 // Get the WebView tab fragment.
855 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
857 // Get the fragment view.
858 val fragmentView = webViewTabFragment.view
860 // Only resume the WebViews if they exist (they won't when the app is first created).
861 if (fragmentView != null) {
862 // Get the nested scroll WebView from the tab fragment.
863 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
865 // Resume the nested scroll WebView.
866 nestedScrollWebView.onResume()
871 // Resume the nested scroll WebView JavaScript timers. This is a global command that resumes JavaScript timers on all WebViews.
872 if (currentWebView != null)
873 currentWebView!!.resumeTimers()
875 // Reapply the proxy settings if the system is using a proxy. This redisplays the appropriate alert dialog.
876 if (proxyMode != ProxyHelper.NONE)
879 // Reapply any system UI flags.
880 if (displayingFullScreenVideo || inFullScreenBrowsingMode) { // The system is displaying a website or a video in full screen mode.
881 /* Hide the system bars.
882 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
883 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
884 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
885 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
888 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
889 @Suppress("DEPRECATION")
890 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
893 // Show any pending dialogs.
894 for (i in pendingDialogsArrayList.indices) {
895 // Get the pending dialog from the array list.
896 val (dialogFragment, tag) = pendingDialogsArrayList[i]
898 // Show the pending dialog.
899 dialogFragment.show(supportFragmentManager, tag)
902 // Clear the pending dialogs array list.
903 pendingDialogsArrayList.clear()
906 public override fun onSaveInstanceState(savedInstanceState: Bundle) {
907 // Run the default commands.
908 super.onSaveInstanceState(savedInstanceState)
910 // 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.
911 if (webViewStateAdapter != null) {
912 // Initialize the saved state array lists.
913 savedStateArrayList = ArrayList<Bundle>()
914 savedNestedScrollWebViewStateArrayList = ArrayList<Bundle>()
916 // Get the URLs from each tab.
917 for (i in 0 until webViewStateAdapter!!.itemCount) {
918 // Get the WebView tab fragment.
919 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
921 // Get the fragment view.
922 val fragmentView = webViewTabFragment.view
924 // Save the fragment state if it is not null.
925 if (fragmentView != null) {
926 // Get the nested scroll WebView from the tab fragment.
927 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
929 // Create the saved state bundle.
930 val savedStateBundle = Bundle()
932 // Get the current states.
933 nestedScrollWebView.saveState(savedStateBundle)
934 val savedNestedScrollWebViewStateBundle = nestedScrollWebView.saveNestedScrollWebViewState()
936 // Store the saved states in the array lists.
937 savedStateArrayList!!.add(savedStateBundle)
938 savedNestedScrollWebViewStateArrayList!!.add(savedNestedScrollWebViewStateBundle)
942 // Get the current tab position.
943 val currentTabPosition = tabLayout.selectedTabPosition
945 // Store the saved states in the bundle.
946 savedInstanceState.putBoolean(BOOKMARKS_DRAWER_PINNED, bookmarksDrawerPinned)
947 savedInstanceState.putString(PROXY_MODE, proxyMode)
948 savedInstanceState.putParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST, savedNestedScrollWebViewStateArrayList)
949 savedInstanceState.putParcelableArrayList(SAVED_STATE_ARRAY_LIST, savedStateArrayList)
950 savedInstanceState.putInt(SAVED_TAB_POSITION, currentTabPosition)
954 // `onStop()` runs after `onPause()`. It is used instead of `onPause()` so the commands are not called every time the screen is partially hidden.
955 public override fun onStop() {
956 // Run the default commands.
959 // 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.
960 if (webViewStateAdapter != null) {
961 // Pause each web view.
962 for (i in 0 until webViewStateAdapter!!.itemCount) {
963 // Get the WebView tab fragment.
964 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
966 // Get the fragment view.
967 val fragmentView = webViewTabFragment.view
969 // Only pause the WebViews if they exist (they won't when the app is first created).
970 if (fragmentView != null) {
971 // Get the nested scroll WebView from the tab fragment.
972 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
974 // Pause the nested scroll WebView.
975 nestedScrollWebView.onPause()
980 // Pause the WebView JavaScript timers. This is a global command that pauses JavaScript on all WebViews.
981 if (currentWebView != null)
982 currentWebView!!.pauseTimers()
985 public override fun onDestroy() {
986 // Unregister the orbot status broadcast receiver if it exists.
987 if (orbotStatusBroadcastReceiver != null) {
988 unregisterReceiver(orbotStatusBroadcastReceiver)
991 // Close the bookmarks cursor if it exists.
992 bookmarksCursor?.close()
994 // Close the databases if they exist.
995 bookmarksDatabaseHelper?.close()
996 domainsDatabaseHelper?.close()
998 // Run the default commands.
1002 override fun onConfigurationChanged(newConfig: Configuration) {
1003 // Run the default commands.
1004 super.onConfigurationChanged(newConfig)
1006 // Get the current page.
1007 val currentPage = webViewViewPager2.currentItem
1009 // Toggle the pages if there is more than one so that the view pager will recalculate their size.
1010 if (currentPage > 0) {
1011 // Switch to the previous page.
1012 webViewViewPager2.currentItem = (currentPage - 1)
1014 // Switch back to the current page after the view pager has quiesced.
1015 webViewViewPager2.post { webViewViewPager2.currentItem = currentPage }
1019 override fun onCreateOptionsMenu(menu: Menu): Boolean {
1020 // Inflate the menu. This adds items to the app bar if it is present.
1021 menuInflater.inflate(R.menu.webview_options_menu, menu)
1023 // Get handles for the menu items.
1024 optionsPrivacyMenuItem = menu.findItem(R.id.javascript)
1025 optionsRefreshMenuItem = menu.findItem(R.id.refresh)
1026 val optionsBookmarksMenuItem = menu.findItem(R.id.bookmarks)
1027 optionsCookiesMenuItem = menu.findItem(R.id.cookies)
1028 optionsDomStorageMenuItem = menu.findItem(R.id.dom_storage)
1029 optionsSaveFormDataMenuItem = menu.findItem(R.id.save_form_data) // Form data can be removed once the minimum API >= 26.
1030 optionsClearDataMenuItem = menu.findItem(R.id.clear_data)
1031 optionsClearCookiesMenuItem = menu.findItem(R.id.clear_cookies)
1032 optionsClearDomStorageMenuItem = menu.findItem(R.id.clear_dom_storage)
1033 optionsClearFormDataMenuItem = menu.findItem(R.id.clear_form_data) // Form data can be removed once the minimum API >= 26.
1034 optionsEasyListMenuItem = menu.findItem(R.id.easylist)
1035 optionsEasyPrivacyMenuItem = menu.findItem(R.id.easyprivacy)
1036 optionsFanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list)
1037 optionsFanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list)
1038 optionsFilterListsMenuItem = menu.findItem(R.id.filterlists)
1039 optionsUltraListMenuItem = menu.findItem(R.id.ultralist)
1040 optionsUltraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy)
1041 optionsBlockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests)
1042 optionsProxyMenuItem = menu.findItem(R.id.proxy)
1043 optionsProxyNoneMenuItem = menu.findItem(R.id.proxy_none)
1044 optionsProxyTorMenuItem = menu.findItem(R.id.proxy_tor)
1045 optionsProxyI2pMenuItem = menu.findItem(R.id.proxy_i2p)
1046 optionsProxyCustomMenuItem = menu.findItem(R.id.proxy_custom)
1047 optionsUserAgentMenuItem = menu.findItem(R.id.user_agent)
1048 optionsUserAgentPrivacyBrowserMenuItem = menu.findItem(R.id.user_agent_privacy_browser)
1049 optionsUserAgentWebViewDefaultMenuItem = menu.findItem(R.id.user_agent_webview_default)
1050 optionsUserAgentFirefoxOnAndroidMenuItem = menu.findItem(R.id.user_agent_firefox_on_android)
1051 optionsUserAgentChromeOnAndroidMenuItem = menu.findItem(R.id.user_agent_chrome_on_android)
1052 optionsUserAgentSafariOnIosMenuItem = menu.findItem(R.id.user_agent_safari_on_ios)
1053 optionsUserAgentFirefoxOnLinuxMenuItem = menu.findItem(R.id.user_agent_firefox_on_linux)
1054 optionsUserAgentChromiumOnLinuxMenuItem = menu.findItem(R.id.user_agent_chromium_on_linux)
1055 optionsUserAgentFirefoxOnWindowsMenuItem = menu.findItem(R.id.user_agent_firefox_on_windows)
1056 optionsUserAgentChromeOnWindowsMenuItem = menu.findItem(R.id.user_agent_chrome_on_windows)
1057 optionsUserAgentEdgeOnWindowsMenuItem = menu.findItem(R.id.user_agent_edge_on_windows)
1058 optionsUserAgentInternetExplorerOnWindowsMenuItem = menu.findItem(R.id.user_agent_internet_explorer_on_windows)
1059 optionsUserAgentSafariOnMacosMenuItem = menu.findItem(R.id.user_agent_safari_on_macos)
1060 optionsUserAgentCustomMenuItem = menu.findItem(R.id.user_agent_custom)
1061 optionsSwipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh)
1062 optionsWideViewportMenuItem = menu.findItem(R.id.wide_viewport)
1063 optionsDisplayImagesMenuItem = menu.findItem(R.id.display_images)
1064 optionsDarkWebViewMenuItem = menu.findItem(R.id.dark_webview)
1065 optionsFontSizeMenuItem = menu.findItem(R.id.font_size)
1066 optionsAddOrEditDomainMenuItem = menu.findItem(R.id.add_or_edit_domain)
1068 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1069 updatePrivacyIcons(false)
1071 // Only display the form data menu items if the API < 26.
1072 optionsSaveFormDataMenuItem.isVisible = Build.VERSION.SDK_INT < 26
1073 optionsClearFormDataMenuItem.isVisible = Build.VERSION.SDK_INT < 26
1075 // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
1076 optionsClearFormDataMenuItem.isEnabled = Build.VERSION.SDK_INT < 26
1078 // 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.
1079 if (displayAdditionalAppBarIcons) { // Display the additional icons.
1080 optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
1081 optionsBookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM)
1082 optionsCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM)
1083 } else { //Do not display the additional icons.
1084 optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER)
1085 optionsBookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER)
1086 optionsCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER)
1089 // Replace `Refresh` with `Stop` if a URL is already loading.
1090 if ((currentWebView != null) && (currentWebView!!.progress != 100)) {
1092 optionsRefreshMenuItem.setTitle(R.string.stop)
1094 // 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.
1095 if (displayAdditionalAppBarIcons)
1096 optionsRefreshMenuItem.setIcon(R.drawable.close_blue)
1099 // Store a handle for the options menu.
1106 override fun onPrepareOptionsMenu(menu: Menu): Boolean {
1107 // Initialize the current user agent string and the font size.
1108 var currentUserAgent = getString(R.string.user_agent_privacy_browser)
1111 // 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.
1112 if (currentWebView != null) {
1113 // Set the add or edit domain text.
1114 if (currentWebView!!.domainSettingsApplied)
1115 optionsAddOrEditDomainMenuItem.setTitle(R.string.edit_domain_settings)
1117 optionsAddOrEditDomainMenuItem.setTitle(R.string.add_domain_settings)
1119 // Get the current user agent from the WebView.
1120 currentUserAgent = currentWebView!!.settings.userAgentString
1122 // Get the current font size from the the WebView.
1123 fontSize = currentWebView!!.settings.textZoom
1125 // Set the status of the menu item checkboxes.
1126 optionsDomStorageMenuItem.isChecked = currentWebView!!.settings.domStorageEnabled
1127 @Suppress("DEPRECATION")
1128 optionsSaveFormDataMenuItem.isChecked = currentWebView!!.settings.saveFormData // Form data can be removed once the minimum API >= 26.
1129 optionsEasyListMenuItem.isChecked = currentWebView!!.easyListEnabled
1130 optionsEasyPrivacyMenuItem.isChecked = currentWebView!!.easyPrivacyEnabled
1131 optionsFanboysAnnoyanceListMenuItem.isChecked = currentWebView!!.fanboysAnnoyanceListEnabled
1132 optionsFanboysSocialBlockingListMenuItem.isChecked = currentWebView!!.fanboysSocialBlockingListEnabled
1133 optionsUltraListMenuItem.isChecked = currentWebView!!.ultraListEnabled
1134 optionsUltraPrivacyMenuItem.isChecked = currentWebView!!.ultraPrivacyEnabled
1135 optionsBlockAllThirdPartyRequestsMenuItem.isChecked = currentWebView!!.blockAllThirdPartyRequests
1136 optionsSwipeToRefreshMenuItem.isChecked = currentWebView!!.swipeToRefresh
1137 optionsWideViewportMenuItem.isChecked = currentWebView!!.settings.useWideViewPort
1138 optionsDisplayImagesMenuItem.isChecked = currentWebView!!.settings.loadsImagesAutomatically
1140 // Initialize the display names for the filter lists with the number of blocked requests.
1141 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + currentWebView!!.getRequestsCount(BLOCKED_REQUESTS)
1142 optionsEasyListMenuItem.title = currentWebView!!.getRequestsCount(EASYLIST).toString() + " - " + getString(R.string.easylist)
1143 optionsEasyPrivacyMenuItem.title = currentWebView!!.getRequestsCount(EASYPRIVACY).toString() + " - " + getString(R.string.easyprivacy)
1144 optionsFanboysAnnoyanceListMenuItem.title = currentWebView!!.getRequestsCount(FANBOYS_ANNOYANCE_LIST).toString() + " - " + getString(R.string.fanboys_annoyance_list)
1145 optionsFanboysSocialBlockingListMenuItem.title = currentWebView!!.getRequestsCount(FANBOYS_SOCIAL_BLOCKING_LIST).toString() + " - " + getString(R.string.fanboys_social_blocking_list)
1146 optionsUltraListMenuItem.title = currentWebView!!.getRequestsCount(com.stoutner.privacybrowser.views.ULTRALIST).toString() + " - " + getString(R.string.ultralist)
1147 optionsUltraPrivacyMenuItem.title = currentWebView!!.getRequestsCount(ULTRAPRIVACY).toString() + " - " + getString(R.string.ultraprivacy)
1148 optionsBlockAllThirdPartyRequestsMenuItem.title = currentWebView!!.getRequestsCount(THIRD_PARTY_REQUESTS).toString() + " - " + getString(R.string.block_all_third_party_requests)
1150 // Enable DOM Storage if JavaScript is enabled.
1151 optionsDomStorageMenuItem.isEnabled = currentWebView!!.settings.javaScriptEnabled
1153 // Get the current theme status.
1154 val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
1156 // Enable dark WebView if night mode is enabled.
1157 optionsDarkWebViewMenuItem.isEnabled = (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES)
1159 // Set the checkbox status for dark WebView if algorithmic darkening is supported.
1160 if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING))
1161 optionsDarkWebViewMenuItem.isChecked = WebSettingsCompat.isAlgorithmicDarkeningAllowed(currentWebView!!.settings)
1164 // Set the cookies menu item checked status.
1165 optionsCookiesMenuItem.isChecked = cookieManager.acceptCookie()
1167 // Enable Clear Cookies if there are any.
1168 optionsClearCookiesMenuItem.isEnabled = cookieManager.hasCookies()
1170 // 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`.
1171 val privateDataDirectoryString = applicationInfo.dataDir
1173 // Get the storage directories.
1174 val localStorageDirectory = File("$privateDataDirectoryString/app_webview/Local Storage/")
1175 val indexedDBDirectory = File("$privateDataDirectoryString/app_webview/IndexedDB")
1177 // Initialize the number of files counters.
1178 var localStorageDirectoryNumberOfFiles = 0
1179 var indexedDBDirectoryNumberOfFiles = 0
1181 // 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.
1182 if (localStorageDirectory.exists())
1183 localStorageDirectoryNumberOfFiles = (localStorageDirectory.list())?.size ?: 0
1185 // Get a count of the number of files in the IndexedDB directory. The list can be null, in which case a `0` is returned.
1186 if (indexedDBDirectory.exists())
1187 indexedDBDirectoryNumberOfFiles = (indexedDBDirectory.list())?.size ?: 0
1189 // Enable Clear DOM Storage if there is any.
1190 optionsClearDomStorageMenuItem.isEnabled = localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0
1192 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
1193 if (Build.VERSION.SDK_INT < 26) {
1194 // Get the WebView database.
1195 val webViewDatabase = WebViewDatabase.getInstance(this)
1197 // Enable the clear form data menu item if there is anything to clear.
1198 @Suppress("DEPRECATION")
1199 optionsClearFormDataMenuItem.isEnabled = webViewDatabase.hasFormData()
1202 // Enable Clear Data if any of the submenu items are enabled.
1203 optionsClearDataMenuItem.isEnabled = (optionsClearCookiesMenuItem.isEnabled || optionsClearDomStorageMenuItem.isEnabled || optionsClearFormDataMenuItem.isEnabled)
1205 // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
1206 optionsFanboysSocialBlockingListMenuItem.isEnabled = !optionsFanboysAnnoyanceListMenuItem.isChecked
1208 // Set the proxy title and check the applied proxy.
1210 ProxyHelper.NONE -> {
1211 // Set the proxy title.
1212 optionsProxyMenuItem.title = getString(R.string.proxy) + " - " + getString(R.string.proxy_none)
1214 // Check the proxy None radio button.
1215 optionsProxyNoneMenuItem.isChecked = true
1218 ProxyHelper.TOR -> {
1219 // Set the proxy title.
1220 optionsProxyMenuItem.title = getString(R.string.proxy) + " - " + getString(R.string.proxy_tor)
1222 // Check the proxy Tor radio button.
1223 optionsProxyTorMenuItem.isChecked = true
1226 ProxyHelper.I2P -> {
1227 // Set the proxy title.
1228 optionsProxyMenuItem.title = getString(R.string.proxy) + " - " + getString(R.string.proxy_i2p)
1230 // Check the proxy I2P radio button.
1231 optionsProxyI2pMenuItem.isChecked = true
1234 ProxyHelper.CUSTOM -> {
1235 // Set the proxy title.
1236 optionsProxyMenuItem.title = getString(R.string.proxy) + " - " + getString(R.string.proxy_custom)
1238 // Check the proxy Custom radio button.
1239 optionsProxyCustomMenuItem.isChecked = true
1243 // Select the current user agent menu item.
1244 when (currentUserAgent) {
1245 resources.getStringArray(R.array.user_agent_data)[0] -> { // Privacy Browser.
1246 // Update the user agent menu item title.
1247 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_privacy_browser)
1249 // Select the Privacy Browser radio box.
1250 optionsUserAgentPrivacyBrowserMenuItem.isChecked = true
1253 webViewDefaultUserAgent -> { // WebView Default.
1254 // Update the user agent menu item title.
1255 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_webview_default)
1257 // Select the WebView Default radio box.
1258 optionsUserAgentWebViewDefaultMenuItem.isChecked = true
1261 resources.getStringArray(R.array.user_agent_data)[2] -> { // Firefox on Android.
1262 // Update the user agent menu item title.
1263 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_android)
1265 // Select the Firefox on Android radio box.
1266 optionsUserAgentFirefoxOnAndroidMenuItem.isChecked = true
1269 resources.getStringArray(R.array.user_agent_data)[3] -> { // Chrome on Android.
1270 // Update the user agent menu item title.
1271 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_android)
1273 // Select the Chrome on Android radio box.
1274 optionsUserAgentChromeOnAndroidMenuItem.isChecked = true
1277 resources.getStringArray(R.array.user_agent_data)[4] -> { // Safari on iOS.
1278 // Update the user agent menu item title.
1279 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_ios)
1281 // Select the Safari on iOS radio box.
1282 optionsUserAgentSafariOnIosMenuItem.isChecked = true
1285 resources.getStringArray(R.array.user_agent_data)[5] -> { // Firefox on Linux.
1286 // Update the user agent menu item title.
1287 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_linux)
1289 // Select the Firefox on Linux radio box.
1290 optionsUserAgentFirefoxOnLinuxMenuItem.isChecked = true
1293 resources.getStringArray(R.array.user_agent_data)[6] -> { // Chromium on Linux.
1294 // Update the user agent menu item title.
1295 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chromium_on_linux)
1297 // Select the Chromium on Linux radio box.
1298 optionsUserAgentChromiumOnLinuxMenuItem.isChecked = true
1301 resources.getStringArray(R.array.user_agent_data)[7] -> { // Firefox on Windows.
1302 // Update the user agent menu item title.
1303 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_windows)
1305 // Select the Firefox on Windows radio box.
1306 optionsUserAgentFirefoxOnWindowsMenuItem.isChecked = true
1309 resources.getStringArray(R.array.user_agent_data)[8] -> { // Chrome on Windows.
1310 // Update the user agent menu item title.
1311 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_windows)
1313 // Select the Chrome on Windows radio box.
1314 optionsUserAgentChromeOnWindowsMenuItem.isChecked = true
1317 resources.getStringArray(R.array.user_agent_data)[9] -> { // Edge on Windows.
1318 // Update the user agent menu item title.
1319 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_edge_on_windows)
1321 // Select the Edge on Windows radio box.
1322 optionsUserAgentEdgeOnWindowsMenuItem.isChecked = true
1325 resources.getStringArray(R.array.user_agent_data)[10] -> { // Internet Explorer on Windows.
1326 // Update the user agent menu item title.
1327 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_internet_explorer_on_windows)
1329 // Select the Internet on Windows radio box.
1330 optionsUserAgentInternetExplorerOnWindowsMenuItem.isChecked = true
1333 resources.getStringArray(R.array.user_agent_data)[11] -> { // Safari on macOS.
1334 // Update the user agent menu item title.
1335 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_macos)
1337 // Select the Safari on macOS radio box.
1338 optionsUserAgentSafariOnMacosMenuItem.isChecked = true
1341 else -> { // Custom user agent.
1342 // Update the user agent menu item title.
1343 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_custom)
1345 // Select the Custom radio box.
1346 optionsUserAgentCustomMenuItem.isChecked = true
1350 // Set the font size title.
1351 optionsFontSizeMenuItem.title = getString(R.string.font_size) + " - " + fontSize + "%"
1353 // Run all the other default commands.
1354 super.onPrepareOptionsMenu(menu)
1356 // Display the menu.
1360 override fun onOptionsItemSelected(menuItem: MenuItem): Boolean {
1361 // Run the commands that correlate to the selected menu item.
1362 return when (menuItem.itemId) {
1363 R.id.javascript -> { // JavaScript.
1364 // Toggle the JavaScript status.
1365 currentWebView!!.settings.javaScriptEnabled = !currentWebView!!.settings.javaScriptEnabled
1367 // Update the privacy icon.
1368 updatePrivacyIcons(true)
1370 // Display a snackbar.
1371 if (currentWebView!!.settings.javaScriptEnabled) // JavaScrip is enabled.
1372 Snackbar.make(webViewViewPager2, R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show()
1373 else if (cookieManager.acceptCookie()) // JavaScript is disabled, but cookies are enabled.
1374 Snackbar.make(webViewViewPager2, R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show()
1375 else // Privacy mode.
1376 Snackbar.make(webViewViewPager2, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show()
1378 // Reload the current WebView.
1379 currentWebView!!.reload()
1381 // Consume the event.
1385 R.id.refresh -> { // Refresh.
1386 // Run the command that correlates to the current status of the menu item.
1387 if (menuItem.title == getString(R.string.refresh)) // The refresh button was pushed.
1388 currentWebView!!.reload()
1389 else // The stop button was pushed.
1390 currentWebView!!.stopLoading()
1392 // Consume the event.
1396 R.id.bookmarks -> { // Bookmarks.
1397 // Open the bookmarks drawer.
1398 drawerLayout.openDrawer(GravityCompat.END)
1400 // Consume the event.
1404 R.id.cookies -> { // Cookies.
1405 // Toggle the cookie status.
1406 cookieManager.setAcceptCookie(!cookieManager.acceptCookie())
1408 // Store the cookie status.
1409 currentWebView!!.acceptCookies = cookieManager.acceptCookie()
1411 // Update the menu checkbox.
1412 menuItem.isChecked = cookieManager.acceptCookie()
1414 // Update the privacy icon.
1415 updatePrivacyIcons(true)
1417 // Display a snackbar.
1418 if (cookieManager.acceptCookie()) // Cookies are enabled.
1419 Snackbar.make(webViewViewPager2, R.string.cookies_enabled, Snackbar.LENGTH_SHORT).show()
1420 else if (currentWebView!!.settings.javaScriptEnabled) // JavaScript is still enabled.
1421 Snackbar.make(webViewViewPager2, R.string.cookies_disabled, Snackbar.LENGTH_SHORT).show()
1422 else // Privacy mode.
1423 Snackbar.make(webViewViewPager2, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show()
1425 // Reload the current WebView.
1426 currentWebView!!.reload()
1428 // Consume the event.
1432 R.id.dom_storage -> { // DOM storage.
1433 // Toggle the DOM storage status.
1434 currentWebView!!.settings.domStorageEnabled = !currentWebView!!.settings.domStorageEnabled
1436 // Update the menu checkbox.
1437 menuItem.isChecked = currentWebView!!.settings.domStorageEnabled
1439 // Update the privacy icon.
1440 updatePrivacyIcons(true)
1442 // Display a snackbar.
1443 if (currentWebView!!.settings.domStorageEnabled)
1444 Snackbar.make(webViewViewPager2, R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show()
1446 Snackbar.make(webViewViewPager2, R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show()
1448 // Reload the current WebView.
1449 currentWebView!!.reload()
1451 // Consume the event.
1455 R.id.save_form_data -> { // Form data. This can be removed once the minimum API >= 26.
1456 // Switch the status of saveFormDataEnabled.
1457 @Suppress("DEPRECATION")
1458 currentWebView!!.settings.saveFormData = !currentWebView!!.settings.saveFormData
1460 // Update the menu checkbox.
1461 @Suppress("DEPRECATION")
1462 menuItem.isChecked = currentWebView!!.settings.saveFormData
1464 // Display a snackbar.
1465 @Suppress("DEPRECATION")
1466 if (currentWebView!!.settings.saveFormData)
1467 Snackbar.make(webViewViewPager2, R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show()
1469 Snackbar.make(webViewViewPager2, R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show()
1471 // Update the privacy icon.
1472 updatePrivacyIcons(true)
1474 // Reload the current WebView.
1475 currentWebView!!.reload()
1477 // Consume the event.
1481 R.id.clear_cookies -> { // Clear cookies.
1482 // Create a snackbar.
1483 Snackbar.make(webViewViewPager2, R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1484 .setAction(R.string.undo) {} // Everything will be handled by `onDismissed()` below.
1485 .addCallback(object : Snackbar.Callback() {
1486 override fun onDismissed(snackbar: Snackbar, event: Int) {
1487 if (event != DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1488 // Delete the cookies.
1489 cookieManager.removeAllCookies(null)
1495 // Consume the event.
1499 R.id.clear_dom_storage -> { // Clear DOM storage.
1500 // Create a snackbar.
1501 Snackbar.make(webViewViewPager2, R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1502 .setAction(R.string.undo) {} // Everything will be handled by `onDismissed()` below.
1503 .addCallback(object : Snackbar.Callback() {
1504 override fun onDismissed(snackbar: Snackbar, event: Int) {
1505 if (event != DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1506 // Get a handle for the web storage.
1507 val webStorage = WebStorage.getInstance()
1509 // Delete the DOM Storage.
1510 webStorage.deleteAllData()
1512 // Initialize a handler to manually delete the DOM storage files and directories.
1513 val deleteDomStorageHandler = Handler(Looper.getMainLooper())
1515 // Setup a runnable to manually delete the DOM storage files and directories.
1516 val deleteDomStorageRunnable = Runnable {
1518 // Get a handle for the runtime.
1519 val runtime = Runtime.getRuntime()
1521 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1522 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1523 val privateDataDirectoryString = applicationInfo.dataDir
1525 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1526 val deleteLocalStorageProcess = runtime.exec(arrayOf("rm", "-rf", "$privateDataDirectoryString/app_webview/Local Storage/"))
1528 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1529 val deleteIndexProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview/IndexedDB")
1530 val deleteQuotaManagerProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/QuotaManager")
1531 val deleteQuotaManagerJournalProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/QuotaManager-journal")
1532 val deleteDatabasesProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview/databases")
1534 // Wait for the processes to finish.
1535 deleteLocalStorageProcess.waitFor()
1536 deleteIndexProcess.waitFor()
1537 deleteQuotaManagerProcess.waitFor()
1538 deleteQuotaManagerJournalProcess.waitFor()
1539 deleteDatabasesProcess.waitFor()
1540 } catch (exception: Exception) {
1541 // Do nothing if an error is thrown.
1545 // Manually delete the DOM storage files after 200 milliseconds.
1546 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200)
1552 // Consume the event.
1556 R.id.clear_form_data -> { // Clear form data. This can be remove once the minimum API >= 26.
1557 // Create a snackbar.
1558 Snackbar.make(webViewViewPager2, R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1559 .setAction(R.string.undo) {} // Everything will be handled by `onDismissed()` below.
1560 .addCallback(object : Snackbar.Callback() {
1561 override fun onDismissed(snackbar: Snackbar, event: Int) {
1562 if (event != DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1563 // Get a handle for the webView database.
1564 val webViewDatabase = WebViewDatabase.getInstance(applicationContext)
1566 // Delete the form data.
1567 @Suppress("DEPRECATION")
1568 webViewDatabase.clearFormData()
1574 // Consume the event.
1578 R.id.easylist -> { // EasyList.
1579 // Toggle the EasyList status.
1580 currentWebView!!.easyListEnabled = !currentWebView!!.easyListEnabled
1582 // Update the menu checkbox.
1583 menuItem.isChecked = currentWebView!!.easyListEnabled
1585 // Reload the current WebView.
1586 currentWebView!!.reload()
1588 // Consume the event.
1592 R.id.easyprivacy -> { // EasyPrivacy.
1593 // Toggle the EasyPrivacy status.
1594 currentWebView!!.easyPrivacyEnabled = !currentWebView!!.easyPrivacyEnabled
1596 // Update the menu checkbox.
1597 menuItem.isChecked = currentWebView!!.easyPrivacyEnabled
1599 // Reload the current WebView.
1600 currentWebView!!.reload()
1602 // Consume the event.
1606 R.id.fanboys_annoyance_list -> { // Fanboy's Annoyance List.
1607 // Toggle Fanboy's Annoyance List status.
1608 currentWebView!!.fanboysAnnoyanceListEnabled = !currentWebView!!.fanboysAnnoyanceListEnabled
1610 // Update the menu checkbox.
1611 menuItem.isChecked = currentWebView!!.fanboysAnnoyanceListEnabled
1613 // Update the status of Fanboy's Social Blocking List.
1614 optionsFanboysSocialBlockingListMenuItem.isEnabled = !currentWebView!!.fanboysAnnoyanceListEnabled
1616 // Reload the current WebView.
1617 currentWebView!!.reload()
1619 // Consume the event.
1623 R.id.fanboys_social_blocking_list -> { // Fanboy's Social Blocking List.
1624 // Toggle Fanboy's Social Blocking List status.
1625 currentWebView!!.fanboysSocialBlockingListEnabled = !currentWebView!!.fanboysSocialBlockingListEnabled
1627 // Update the menu checkbox.
1628 menuItem.isChecked = currentWebView!!.fanboysSocialBlockingListEnabled
1630 // Reload the current WebView.
1631 currentWebView!!.reload()
1633 // Consume the event.
1637 R.id.ultralist -> { // UltraList.
1638 // Toggle the UltraList status.
1639 currentWebView!!.ultraListEnabled = !currentWebView!!.ultraListEnabled
1641 // Update the menu checkbox.
1642 menuItem.isChecked = currentWebView!!.ultraListEnabled
1644 // Reload the current WebView.
1645 currentWebView!!.reload()
1647 // Consume the event.
1651 R.id.ultraprivacy -> { // UltraPrivacy.
1652 // Toggle the UltraPrivacy status.
1653 currentWebView!!.ultraPrivacyEnabled = !currentWebView!!.ultraPrivacyEnabled
1655 // Update the menu checkbox.
1656 menuItem.isChecked = currentWebView!!.ultraPrivacyEnabled
1658 // Reload the current WebView.
1659 currentWebView!!.reload()
1661 // Consume the event.
1665 R.id.block_all_third_party_requests -> { // Block all third-party requests.
1666 //Toggle the third-party requests blocker status.
1667 currentWebView!!.blockAllThirdPartyRequests = !currentWebView!!.blockAllThirdPartyRequests
1669 // Update the menu checkbox.
1670 menuItem.isChecked = currentWebView!!.blockAllThirdPartyRequests
1672 // Reload the current WebView.
1673 currentWebView!!.reload()
1675 // Consume the event.
1679 R.id.proxy_none -> { // Proxy - None.
1680 // Update the proxy mode.
1681 proxyMode = ProxyHelper.NONE
1683 // Apply the proxy mode.
1686 // Consume the event.
1690 R.id.proxy_tor -> { // Proxy - Tor.
1691 // Update the proxy mode.
1692 proxyMode = ProxyHelper.TOR
1694 // Apply the proxy mode.
1697 // Consume the event.
1701 R.id.proxy_i2p -> { // Proxy - I2P.
1702 // Update the proxy mode.
1703 proxyMode = ProxyHelper.I2P
1705 // Apply the proxy mode.
1708 // Consume the event.
1712 R.id.proxy_custom -> { // Proxy - Custom.
1713 // Update the proxy mode.
1714 proxyMode = ProxyHelper.CUSTOM
1716 // Apply the proxy mode.
1719 // Consume the event.
1723 R.id.user_agent_privacy_browser -> { // User Agent - Privacy Browser.
1724 // Update the user agent.
1725 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[0]
1727 // Reload the current WebView.
1728 currentWebView!!.reload()
1730 // Consume the event.
1734 R.id.user_agent_webview_default -> { // User Agent - WebView Default.
1735 // Update the user agent.
1736 currentWebView!!.settings.userAgentString = ""
1738 // Reload the current WebView.
1739 currentWebView!!.reload()
1741 // Consume the event.
1745 R.id.user_agent_firefox_on_android -> { // User Agent - Firefox on Android.
1746 // Update the user agent.
1747 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[2]
1749 // Reload the current WebView.
1750 currentWebView!!.reload()
1752 // Consume the event.
1756 R.id.user_agent_chrome_on_android -> { // User Agent - Chrome on Android.
1757 // Update the user agent.
1758 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[3]
1760 // Reload the current WebView.
1761 currentWebView!!.reload()
1763 // Consume the event.
1767 R.id.user_agent_safari_on_ios -> { // User Agent - Safari on iOS.
1768 // Update the user agent.
1769 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[4]
1771 // Reload the current WebView.
1772 currentWebView!!.reload()
1774 // Consume the event.
1778 R.id.user_agent_firefox_on_linux -> { // User Agent - Firefox on Linux.
1779 // Update the user agent.
1780 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[5]
1782 // Reload the current WebView.
1783 currentWebView!!.reload()
1785 // Consume the event.
1789 R.id.user_agent_chromium_on_linux -> { // User Agent - Chromium on Linux.
1790 // Update the user agent.
1791 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[6]
1793 // Reload the current WebView.
1794 currentWebView!!.reload()
1796 // Consume the event.
1800 R.id.user_agent_firefox_on_windows -> { // User Agent - Firefox on Windows.
1801 // Update the user agent.
1802 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[7]
1804 // Reload the current WebView.
1805 currentWebView!!.reload()
1807 // Consume the event.
1811 R.id.user_agent_chrome_on_windows -> { // User Agent - Chrome on Windows.
1812 // Update the user agent.
1813 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[8]
1815 // Reload the current WebView.
1816 currentWebView!!.reload()
1818 // Consume the event.
1822 R.id.user_agent_edge_on_windows -> { // User Agent - Edge on Windows.
1823 // Update the user agent.
1824 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[9]
1826 // Reload the current WebView.
1827 currentWebView!!.reload()
1829 // Consume the event.
1833 R.id.user_agent_internet_explorer_on_windows -> { // User Agent - Internet Explorer on Windows.
1834 // Update the user agent.
1835 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[10]
1837 // Reload the current WebView.
1838 currentWebView!!.reload()
1840 // Consume the event.
1844 R.id.user_agent_safari_on_macos -> { // User Agent - Safari on macOS.
1845 // Update the user agent.
1846 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[11]
1848 // Reload the current WebView.
1849 currentWebView!!.reload()
1851 // Consume the event.
1855 R.id.user_agent_custom -> { // User Agent - Custom.
1856 // Update the user agent.
1857 currentWebView!!.settings.userAgentString = sharedPreferences.getString(getString(R.string.custom_user_agent_key), getString(R.string.custom_user_agent_default_value))
1859 // Reload the current WebView.
1860 currentWebView!!.reload()
1862 // Consume the event.
1866 R.id.font_size -> { // Font size.
1867 // Instantiate the font size dialog.
1868 val fontSizeDialogFragment: DialogFragment = FontSizeDialog.displayDialog(currentWebView!!.settings.textZoom)
1870 // Show the font size dialog.
1871 fontSizeDialogFragment.show(supportFragmentManager, getString(R.string.font_size))
1873 // Consume the event.
1877 R.id.swipe_to_refresh -> { // Swipe to refresh.
1878 // Toggle the stored status of swipe to refresh.
1879 currentWebView!!.swipeToRefresh = !currentWebView!!.swipeToRefresh
1881 // Update the swipe refresh layout.
1882 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.
1883 swipeRefreshLayout.isEnabled = currentWebView!!.scrollY == 0
1884 else // Swipe to refresh is disabled.
1885 swipeRefreshLayout.isEnabled = false
1887 // Consume the event.
1891 R.id.wide_viewport -> { // Wide viewport.
1892 // Toggle the viewport.
1893 currentWebView!!.settings.useWideViewPort = !currentWebView!!.settings.useWideViewPort
1895 // Consume the event.
1899 R.id.display_images -> { // Display images.
1900 // Toggle the displaying of images.
1901 if (currentWebView!!.settings.loadsImagesAutomatically) { // Images are currently loaded automatically.
1902 // Disable loading of images.
1903 currentWebView!!.settings.loadsImagesAutomatically = false
1905 // Reload the website to remove existing images.
1906 currentWebView!!.reload()
1907 } else { // Images are not currently loaded automatically.
1908 // Enable loading of images. Missing images will be loaded without the need for a reload.
1909 currentWebView!!.settings.loadsImagesAutomatically = true
1912 // Consume the event.
1916 R.id.dark_webview -> { // Dark WebView.
1917 // Toggle dark WebView if supported.
1918 if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING))
1919 WebSettingsCompat.setAlgorithmicDarkeningAllowed(currentWebView!!.settings, !WebSettingsCompat.isAlgorithmicDarkeningAllowed(currentWebView!!.settings)
1922 // Consume the event.
1926 R.id.find_on_page -> { // Find on page.
1927 // Set the minimum height of the find on page linear layout to match the toolbar.
1928 findOnPageLinearLayout.minimumHeight = toolbar.height
1930 // Hide the toolbar.
1931 toolbar.visibility = View.GONE
1933 // Show the find on page linear layout.
1934 findOnPageLinearLayout.visibility = View.VISIBLE
1936 // Display the keyboard. The app must wait 200 ms before running the command to work around a bug in Android.
1937 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1938 findOnPageEditText.postDelayed({
1939 // Set the focus on the find on page edit text.
1940 findOnPageEditText.requestFocus()
1942 // Get a handle for the input method manager.
1943 val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
1945 // Display the keyboard. `0` sets no input flags.
1946 inputMethodManager.showSoftInput(findOnPageEditText, 0)
1949 // Consume the event.
1953 R.id.print -> { // Print.
1954 // Get a print manager instance.
1955 val printManager = (getSystemService(PRINT_SERVICE) as PrintManager)
1957 // Create a print document adapter from the current WebView.
1958 val printDocumentAdapter = currentWebView!!.createPrintDocumentAdapter(getString(R.string.print))
1960 // Print the document.
1961 printManager.print(getString(R.string.privacy_browser_webpage), printDocumentAdapter, null)
1963 // Consume the event.
1967 R.id.save_url -> { // Save URL.
1968 // Check the download preference.
1969 if (downloadWithExternalApp) // Download with an external app.
1970 downloadUrlWithExternalApp(currentWebView!!.currentUrl)
1971 else // Handle the download inside of Privacy Browser. The dialog will be displayed once the file size and the content disposition have been acquired.
1972 PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, currentWebView!!.currentUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
1974 // Consume the event.
1978 R.id.save_archive -> {
1979 // Open the file picker with a default file name built from the current domain name.
1980 saveWebpageArchiveActivityResultLauncher.launch(currentWebView!!.currentDomainName + ".mht")
1982 // Consume the event.
1986 R.id.save_image -> { // Save image.
1987 // Open the file picker with a default file name built from the current domain name.
1988 saveWebpageImageActivityResultLauncher.launch(currentWebView!!.currentDomainName + ".png")
1990 // Consume the event.
1994 R.id.add_to_homescreen -> { // Add to homescreen.
1995 // Instantiate the create home screen shortcut dialog.
1996 val createHomeScreenShortcutDialogFragment: DialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView!!.title!!, currentWebView!!.url!!, currentWebView!!.getFavoriteIcon())
1998 // Show the create home screen shortcut dialog.
1999 createHomeScreenShortcutDialogFragment.show(supportFragmentManager, getString(R.string.create_shortcut))
2001 // Consume the event.
2005 R.id.view_source -> { // View source.
2006 // Create an intent to launch the view source activity.
2007 val viewSourceIntent = Intent(this, ViewSourceActivity::class.java)
2009 // Add the variables to the intent.
2010 viewSourceIntent.putExtra(CURRENT_URL, currentWebView!!.url)
2011 viewSourceIntent.putExtra(USER_AGENT, currentWebView!!.settings.userAgentString)
2014 startActivity(viewSourceIntent)
2016 // Consume the event.
2020 R.id.share_message -> { // Share a message.
2021 // Prepare the share string.
2022 val shareString = currentWebView!!.title + " – " + currentWebView!!.url
2024 // Create the share intent.
2025 val shareMessageIntent = Intent(Intent.ACTION_SEND)
2027 // Add the share string to the intent.
2028 shareMessageIntent.putExtra(Intent.EXTRA_TEXT, shareString)
2030 // Set the MIME type.
2031 shareMessageIntent.type = "text/plain"
2033 // Set the intent to open in a new task.
2034 shareMessageIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
2037 startActivity(Intent.createChooser(shareMessageIntent, getString(R.string.share_message)))
2039 // Consume the event.
2043 R.id.share_url -> { // Share URL.
2044 // Create the share intent.
2045 val shareUrlIntent = Intent(Intent.ACTION_SEND)
2047 // Add the URL to the intent.
2048 shareUrlIntent.putExtra(Intent.EXTRA_TEXT, currentWebView!!.url)
2050 // Add the title to the intent.
2051 shareUrlIntent.putExtra(Intent.EXTRA_SUBJECT, currentWebView!!.title)
2053 // Set the MIME type.
2054 shareUrlIntent.type = "text/plain"
2056 // Set the intent to open in a new task.
2057 shareUrlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
2060 startActivity(Intent.createChooser(shareUrlIntent, getString(R.string.share_url)))
2062 // Consume the event.
2066 R.id.open_with_app -> { // Open with app.
2067 // Open the URL with an outside app.
2068 openWithApp(currentWebView!!.url!!)
2070 // Consume the event.
2074 R.id.open_with_browser -> { // Open with browser.
2075 // Open the URL with an outside browser.
2076 openWithBrowser(currentWebView!!.url!!)
2078 // Consume the event.
2082 R.id.add_or_edit_domain -> { // Add or edit domain.
2083 // Reapply the domain settings on returning to `MainWebViewActivity`.
2084 reapplyDomainSettingsOnRestart = true
2086 // Check if domain settings are currently applied.
2087 if (currentWebView!!.domainSettingsApplied) { // Edit the current domain settings.
2088 // Create an intent to launch the domains activity.
2089 val domainsIntent = Intent(this, DomainsActivity::class.java)
2091 // Add the extra information to the intent.
2092 domainsIntent.putExtra(LOAD_DOMAIN, currentWebView!!.domainSettingsDatabaseId)
2093 domainsIntent.putExtra(CLOSE_ON_BACK, true)
2094 domainsIntent.putExtra(CURRENT_URL, currentWebView!!.url)
2095 domainsIntent.putExtra(CURRENT_IP_ADDRESSES, currentWebView!!.currentIpAddresses)
2097 // Get the current certificate.
2098 val sslCertificate = currentWebView!!.certificate
2100 // Check to see if the SSL certificate is populated.
2101 if (sslCertificate != null) {
2102 // Extract the certificate to strings.
2103 val issuedToCName = sslCertificate.issuedTo.cName
2104 val issuedToOName = sslCertificate.issuedTo.oName
2105 val issuedToUName = sslCertificate.issuedTo.uName
2106 val issuedByCName = sslCertificate.issuedBy.cName
2107 val issuedByOName = sslCertificate.issuedBy.oName
2108 val issuedByUName = sslCertificate.issuedBy.uName
2109 val startDateLong = sslCertificate.validNotBeforeDate.time
2110 val endDateLong = sslCertificate.validNotAfterDate.time
2112 // Add the certificate to the intent.
2113 domainsIntent.putExtra(SSL_ISSUED_TO_CNAME, issuedToCName)
2114 domainsIntent.putExtra(SSL_ISSUED_TO_ONAME, issuedToOName)
2115 domainsIntent.putExtra(SSL_ISSUED_TO_UNAME, issuedToUName)
2116 domainsIntent.putExtra(SSL_ISSUED_BY_CNAME, issuedByCName)
2117 domainsIntent.putExtra(SSL_ISSUED_BY_ONAME, issuedByOName)
2118 domainsIntent.putExtra(SSL_ISSUED_BY_UNAME, issuedByUName)
2119 domainsIntent.putExtra(SSL_START_DATE, startDateLong)
2120 domainsIntent.putExtra(SSL_END_DATE, endDateLong)
2124 startActivity(domainsIntent)
2125 } else { // Add a new domain.
2126 // Get the current URI.
2127 val currentUri = Uri.parse(currentWebView!!.url)
2129 // Get the current domain from the URI. Use an empty string if it is null.
2130 val currentDomain = currentUri.host?: ""
2132 // Create the domain and store the database ID.
2133 val newDomainDatabaseId = domainsDatabaseHelper!!.addDomain(currentDomain)
2135 // Create an intent to launch the domains activity.
2136 val domainsIntent = Intent(this, DomainsActivity::class.java)
2138 // Add the extra information to the intent.
2139 domainsIntent.putExtra(LOAD_DOMAIN, newDomainDatabaseId)
2140 domainsIntent.putExtra(CLOSE_ON_BACK, true)
2141 domainsIntent.putExtra(CURRENT_URL, currentWebView!!.url)
2142 domainsIntent.putExtra(CURRENT_IP_ADDRESSES, currentWebView!!.currentIpAddresses)
2144 // Get the current certificate.
2145 val sslCertificate = currentWebView!!.certificate
2147 // Check to see if the SSL certificate is populated.
2148 if (sslCertificate != null) {
2149 // Extract the certificate to strings.
2150 val issuedToCName = sslCertificate.issuedTo.cName
2151 val issuedToOName = sslCertificate.issuedTo.oName
2152 val issuedToUName = sslCertificate.issuedTo.uName
2153 val issuedByCName = sslCertificate.issuedBy.cName
2154 val issuedByOName = sslCertificate.issuedBy.oName
2155 val issuedByUName = sslCertificate.issuedBy.uName
2156 val startDateLong = sslCertificate.validNotBeforeDate.time
2157 val endDateLong = sslCertificate.validNotAfterDate.time
2159 // Add the certificate to the intent.
2160 domainsIntent.putExtra(SSL_ISSUED_TO_CNAME, issuedToCName)
2161 domainsIntent.putExtra(SSL_ISSUED_TO_ONAME, issuedToOName)
2162 domainsIntent.putExtra(SSL_ISSUED_TO_UNAME, issuedToUName)
2163 domainsIntent.putExtra(SSL_ISSUED_BY_CNAME, issuedByCName)
2164 domainsIntent.putExtra(SSL_ISSUED_BY_ONAME, issuedByOName)
2165 domainsIntent.putExtra(SSL_ISSUED_BY_UNAME, issuedByUName)
2166 domainsIntent.putExtra(SSL_START_DATE, startDateLong)
2167 domainsIntent.putExtra(SSL_END_DATE, endDateLong)
2171 startActivity(domainsIntent)
2174 // Consume the event.
2178 else -> { // There is no match with the options menu. Pass the event up to the parent method.
2179 // Don't consume the event.
2180 super.onOptionsItemSelected(menuItem)
2185 override fun onNavigationItemSelected(menuItem: MenuItem): Boolean {
2186 // Run the commands that correspond to the selected menu item.
2187 when (menuItem.itemId) {
2188 R.id.clear_and_exit -> { // Clear and exit.
2189 // Clear and exit Privacy Browser.
2193 R.id.home -> { // Home.
2194 // Load the homepage.
2195 loadUrl(currentWebView!!, sharedPreferences.getString(getString(R.string.homepage_key), getString(R.string.homepage_default_value))!!)
2198 R.id.back -> { // Back.
2199 // Check if the WebView can go back.
2200 if (currentWebView!!.canGoBack()) {
2201 // Get the current web back forward list.
2202 val webBackForwardList = currentWebView!!.copyBackForwardList()
2204 // Get the previous entry URL.
2205 val previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex - 1).url
2207 // Apply the domain settings.
2208 applyDomainSettings(currentWebView!!, previousUrl, resetTab = false, reloadWebsite = false, loadUrl = false)
2210 // Load the previous website in the history.
2211 currentWebView!!.goBack()
2215 R.id.forward -> { // Forward.
2216 // Check if the WebView can go forward.
2217 if (currentWebView!!.canGoForward()) {
2218 // Get the current web back forward list.
2219 val webBackForwardList = currentWebView!!.copyBackForwardList()
2221 // Get the next entry URL.
2222 val nextUrl = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex + 1).url
2224 // Apply the domain settings.
2225 applyDomainSettings(currentWebView!!, nextUrl, resetTab = false, reloadWebsite = false, loadUrl = false)
2227 // Load the next website in the history.
2228 currentWebView!!.goForward()
2232 R.id.history -> { // History.
2233 // Instantiate the URL history dialog.
2234 val urlHistoryDialogFragment: DialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView!!.webViewFragmentId)
2236 // Show the URL history dialog.
2237 urlHistoryDialogFragment.show(supportFragmentManager, getString(R.string.history))
2240 R.id.open -> { // Open.
2241 // Instantiate the open file dialog.
2242 val openDialogFragment: DialogFragment = OpenDialog()
2244 // Show the open file dialog.
2245 openDialogFragment.show(supportFragmentManager, getString(R.string.open))
2248 R.id.requests -> { // Requests.
2249 // Populate the resource requests.
2250 RequestsActivity.resourceRequests = currentWebView!!.getResourceRequests()
2252 // Create an intent to launch the Requests activity.
2253 val requestsIntent = Intent(this, RequestsActivity::class.java)
2255 // Add the block third-party requests status to the intent.
2256 requestsIntent.putExtra(BLOCK_ALL_THIRD_PARTY_REQUESTS, currentWebView!!.blockAllThirdPartyRequests)
2259 startActivity(requestsIntent)
2262 R.id.downloads -> { // Downloads.
2263 // Try the default system download manager.
2265 // Launch the default system Download Manager.
2266 val defaultDownloadManagerIntent = Intent(DownloadManager.ACTION_VIEW_DOWNLOADS)
2268 // Launch as a new task so that the download manager and Privacy Browser show as separate windows in the recent tasks list.
2269 defaultDownloadManagerIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2272 startActivity(defaultDownloadManagerIntent)
2273 } catch (defaultDownloadManagerException: Exception) { // The system download manager is not available.
2274 // Try a generic file manager.
2276 // Create a generic file manager intent.
2277 val genericFileManagerIntent = Intent(Intent.ACTION_VIEW)
2279 // Open the download directory.
2280 genericFileManagerIntent.setDataAndType(Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()), DocumentsContract.Document.MIME_TYPE_DIR)
2282 // Launch as a new task so that the file manager and Privacy Browser show as separate windows in the recent tasks list.
2283 genericFileManagerIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2286 startActivity(genericFileManagerIntent)
2287 } catch (genericFileManagerException: Exception) { // A generic file manager is not available.
2288 // Try an alternate file manager.
2290 // Create an alternate file manager intent.
2291 val alternateFileManagerIntent = Intent(Intent.ACTION_VIEW)
2293 // Open the download directory.
2294 alternateFileManagerIntent.setDataAndType(Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()), "resource/folder")
2296 // Launch as a new task so that the file manager and Privacy Browser show as separate windows in the recent tasks list.
2297 alternateFileManagerIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2299 // Open the alternate file manager.
2300 startActivity(alternateFileManagerIntent)
2301 } catch (alternateFileManagerException: Exception) {
2302 // Display a snackbar.
2303 Snackbar.make(currentWebView!!, R.string.no_file_manager_detected, Snackbar.LENGTH_INDEFINITE).show()
2309 R.id.domains -> { // Domains.
2310 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2311 reapplyDomainSettingsOnRestart = true
2313 // Create a domains activity intent.
2314 val domainsIntent = Intent(this, DomainsActivity::class.java)
2316 // Add the extra information to the intent.
2317 domainsIntent.putExtra(CURRENT_URL, currentWebView!!.url)
2318 domainsIntent.putExtra(CURRENT_IP_ADDRESSES, currentWebView!!.currentIpAddresses)
2320 // Get the current certificate.
2321 val sslCertificate = currentWebView!!.certificate
2323 // Check to see if the SSL certificate is populated.
2324 if (sslCertificate != null) {
2325 // Extract the certificate to strings.
2326 val issuedToCName = sslCertificate.issuedTo.cName
2327 val issuedToOName = sslCertificate.issuedTo.oName
2328 val issuedToUName = sslCertificate.issuedTo.uName
2329 val issuedByCName = sslCertificate.issuedBy.cName
2330 val issuedByOName = sslCertificate.issuedBy.oName
2331 val issuedByUName = sslCertificate.issuedBy.uName
2332 val startDateLong = sslCertificate.validNotBeforeDate.time
2333 val endDateLong = sslCertificate.validNotAfterDate.time
2335 // Add the certificate to the intent.
2336 domainsIntent.putExtra(SSL_ISSUED_TO_CNAME, issuedToCName)
2337 domainsIntent.putExtra(SSL_ISSUED_TO_ONAME, issuedToOName)
2338 domainsIntent.putExtra(SSL_ISSUED_TO_UNAME, issuedToUName)
2339 domainsIntent.putExtra(SSL_ISSUED_BY_CNAME, issuedByCName)
2340 domainsIntent.putExtra(SSL_ISSUED_BY_ONAME, issuedByOName)
2341 domainsIntent.putExtra(SSL_ISSUED_BY_UNAME, issuedByUName)
2342 domainsIntent.putExtra(SSL_START_DATE, startDateLong)
2343 domainsIntent.putExtra(SSL_END_DATE, endDateLong)
2347 startActivity(domainsIntent)
2350 R.id.settings -> { // Settings.
2351 // Set the reapply on restart flags.
2352 reapplyAppSettingsOnRestart = true
2353 reapplyDomainSettingsOnRestart = true
2355 // Create a settings intent.
2356 val settingsIntent = Intent(this, SettingsActivity::class.java)
2359 startActivity(settingsIntent)
2362 R.id.import_export -> { // Import/Export.
2363 // Create an intent to launch the import/export activity.
2364 val importExportIntent = Intent(this, ImportExportActivity::class.java)
2367 startActivity(importExportIntent)
2370 R.id.logcat -> { // Logcat.
2371 // Create an intent to launch the logcat activity.
2372 val logcatIntent = Intent(this, LogcatActivity::class.java)
2375 startActivity(logcatIntent)
2378 R.id.webview_devtools -> { // WebView DevTools.
2379 // Create a WebView DevTools intent.
2380 val webViewDevToolsIntent = Intent("com.android.webview.SHOW_DEV_UI")
2382 // Launch as a new task so that the WebView DevTools and Privacy Browser show as a separate windows in the recent tasks list.
2383 webViewDevToolsIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2386 startActivity(webViewDevToolsIntent)
2389 R.id.guide -> { // Guide.
2390 // Create an intent to launch the guide activity.
2391 val guideIntent = Intent(this, GuideActivity::class.java)
2394 startActivity(guideIntent)
2397 R.id.about -> { // About
2398 // Create an intent to launch the about activity.
2399 val aboutIntent = Intent(this, AboutActivity::class.java)
2401 // Create a string array for the filter list versions.
2402 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])
2404 // Add the filter list versions to the intent.
2405 aboutIntent.putExtra(FILTERLIST_VERSIONS, filterListVersions)
2408 startActivity(aboutIntent)
2412 // Close the navigation drawer.
2413 drawerLayout.closeDrawer(GravityCompat.START)
2419 override fun onCreateContextMenu(contextMenu: ContextMenu, view: View, contextMenuInfo: ContextMenu.ContextMenuInfo?) {
2420 // Get the hit test result.
2421 val hitTestResult = currentWebView!!.hitTestResult
2423 // Define the URL strings.
2424 val imageUrl: String?
2425 val linkUrl: String?
2427 // Get a handle for the clipboard manager.
2428 val clipboardManager = (getSystemService(CLIPBOARD_SERVICE) as ClipboardManager)
2430 // Process the link according to the type.
2431 when (hitTestResult.type) {
2432 // `SRC_ANCHOR_TYPE` is a link.
2433 WebView.HitTestResult.SRC_ANCHOR_TYPE -> {
2434 // Get the target URL.
2435 linkUrl = hitTestResult.extra!!
2437 // Set the target URL as the context menu title.
2438 contextMenu.setHeaderTitle(linkUrl)
2440 // Add an open in new tab entry.
2441 contextMenu.add(R.string.open_in_new_tab).setOnMenuItemClickListener {
2442 // Load the link URL in a new tab and move to it.
2443 addNewTab(linkUrl, true)
2445 // Consume the event.
2449 // Add an open in background entry.
2450 contextMenu.add(R.string.open_in_background).setOnMenuItemClickListener {
2451 // Load the link URL in a new tab but do not move to it.
2452 addNewTab(linkUrl, false)
2454 // Consume the event.
2458 // Add an open with app entry.
2459 contextMenu.add(R.string.open_with_app).setOnMenuItemClickListener {
2460 // Open the URL with another app.
2461 openWithApp(linkUrl)
2463 // Consume the event.
2467 // Add an open with browser entry.
2468 contextMenu.add(R.string.open_with_browser).setOnMenuItemClickListener {
2469 // Open the URL with another browser.
2470 openWithBrowser(linkUrl)
2472 // Consume the event.
2476 // Add a copy URL entry.
2477 contextMenu.add(R.string.copy_url).setOnMenuItemClickListener {
2478 // Save the link URL in a clip data.
2479 val srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl)
2481 // Set the clip data as the clipboard's primary clip.
2482 clipboardManager.setPrimaryClip(srcAnchorTypeClipData)
2484 // Consume the event.
2488 // Add a Save URL entry.
2489 contextMenu.add(R.string.save_url).setOnMenuItemClickListener {
2490 // Check the download preference.
2491 if (downloadWithExternalApp) // Download with an external app.
2492 downloadUrlWithExternalApp(linkUrl)
2493 else // Handle the download inside of Privacy Browser. The dialog will be displayed once the file size and the content disposition have been acquired.
2494 PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, linkUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
2496 // Consume the event.
2500 // Add an empty cancel entry, which by default closes the context menu.
2501 contextMenu.add(R.string.cancel)
2504 // `IMAGE_TYPE` is an image.
2505 WebView.HitTestResult.IMAGE_TYPE -> {
2506 // Get the image URL.
2507 imageUrl = hitTestResult.extra!!
2509 // Set the context menu title.
2510 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.
2511 contextMenu.setHeaderTitle(imageUrl.substring(0, 100))
2512 else // The image URL does not contain the full image data. Set the image URL as the title of the context menu.
2513 contextMenu.setHeaderTitle(imageUrl)
2515 // Add an open in new tab entry.
2516 contextMenu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener {
2517 // Load the image in a new tab.
2518 addNewTab(imageUrl, true)
2520 // Consume the event.
2524 // Add an open with app entry.
2525 contextMenu.add(R.string.open_with_app).setOnMenuItemClickListener {
2526 // Open the image URL with an external app.
2527 openWithApp(imageUrl)
2529 // Consume the event.
2533 // Add an open with browser entry.
2534 contextMenu.add(R.string.open_with_browser).setOnMenuItemClickListener {
2535 // Open the image URL with an external browser.
2536 openWithBrowser(imageUrl)
2538 // Consume the event.
2542 // Add a view image entry.
2543 contextMenu.add(R.string.view_image).setOnMenuItemClickListener {
2544 // Load the image in the current tab.
2545 loadUrl(currentWebView!!, imageUrl)
2547 // Consume the event.
2551 // Add a save image entry.
2552 contextMenu.add(R.string.save_image).setOnMenuItemClickListener {
2553 // Check the download preference.
2554 if (downloadWithExternalApp) { // Download with an external app.
2555 downloadUrlWithExternalApp(imageUrl)
2556 } else { // Handle the download inside of Privacy Browser. The dialog will be displayed once the file size and the content disposition have been acquired.
2557 PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, imageUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
2560 // Consume the event.
2564 // Add a copy URL entry.
2565 contextMenu.add(R.string.copy_url).setOnMenuItemClickListener {
2566 // Save the image URL in a clip data.
2567 val imageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl)
2569 // Set the clip data as the clipboard's primary clip.
2570 clipboardManager.setPrimaryClip(imageTypeClipData)
2572 // Consume the event.
2576 // Add an empty cancel entry, which by default closes the context menu.
2577 contextMenu.add(R.string.cancel)
2580 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2581 WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE -> {
2582 // Get the image URL.
2583 imageUrl = hitTestResult.extra!!
2585 // Instantiate a handler.
2586 val handler = Handler(Looper.getMainLooper())
2588 // Get a handle for the handler message.
2589 val message = handler.obtainMessage()
2591 // Request the image details from the last touched node be returned in the message.
2592 currentWebView!!.requestFocusNodeHref(message)
2594 // Get the link URL from the message data.
2595 linkUrl = message.data.getString("url")!!
2597 // Set the link URL as the title of the context menu.
2598 contextMenu.setHeaderTitle(linkUrl)
2600 // Add an open in new tab entry.
2601 contextMenu.add(R.string.open_in_new_tab).setOnMenuItemClickListener {
2602 // Load the link URL in a new tab and move to it.
2603 addNewTab(linkUrl, true)
2605 // Consume the event.
2609 // Add an open in background entry.
2610 contextMenu.add(R.string.open_in_background).setOnMenuItemClickListener {
2611 // Lod the link URL in a new tab but do not move to it.
2612 addNewTab(linkUrl, false)
2614 // Consume the event.
2618 // Add an open image in new tab entry.
2619 contextMenu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener {
2620 // Load the image in a new tab and move to it.
2621 addNewTab(imageUrl, true)
2623 // Consume the event.
2627 // Add an open with app entry.
2628 contextMenu.add(R.string.open_with_app).setOnMenuItemClickListener {
2629 // Open the link URL with an external app.
2630 openWithApp(linkUrl)
2632 // Consume the event.
2636 // Add an open with browser entry.
2637 contextMenu.add(R.string.open_with_browser).setOnMenuItemClickListener {
2638 // Open the link URL with an external browser.
2639 openWithBrowser(linkUrl)
2641 // Consume the event.
2645 // Add a view image entry.
2646 contextMenu.add(R.string.view_image).setOnMenuItemClickListener {
2647 // View the image in the current tab.
2648 loadUrl(currentWebView!!, imageUrl)
2650 // Consume the event.
2654 // Add a Save Image entry.
2655 contextMenu.add(R.string.save_image).setOnMenuItemClickListener {
2656 // Check the download preference.
2657 if (downloadWithExternalApp) // Download with an external app.
2658 downloadUrlWithExternalApp(imageUrl)
2659 else // Handle the download inside of Privacy Browser. The dialog will be displayed once the file size and the content disposition have been acquired.
2660 PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, imageUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
2662 // Consume the event.
2666 // Add a copy URL entry.
2667 contextMenu.add(R.string.copy_url).setOnMenuItemClickListener {
2668 // Save the link URL in a clip data.
2669 val srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl)
2671 // Set the clip data as the clipboard's primary clip.
2672 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData)
2674 // Consume the event.
2678 // Add a save URL entry.
2679 contextMenu.add(R.string.save_url).setOnMenuItemClickListener {
2680 // Check the download preference.
2681 if (downloadWithExternalApp) // Download with an external app.
2682 downloadUrlWithExternalApp(linkUrl)
2683 else // Handle the download inside of Privacy Browser. The dialog will be displayed once the file size and the content disposition have been acquired.
2684 PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, linkUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
2686 // Consume the event.
2690 // Add an empty cancel entry, which by default closes the context menu.
2691 contextMenu.add(R.string.cancel)
2694 WebView.HitTestResult.EMAIL_TYPE -> {
2695 // Get the target URL.
2696 linkUrl = hitTestResult.extra
2698 // Set the target URL as the title of the context menu.
2699 contextMenu.setHeaderTitle(linkUrl)
2701 // Add a write email entry.
2702 contextMenu.add(R.string.write_email).setOnMenuItemClickListener {
2703 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2704 val emailIntent = Intent(Intent.ACTION_SENDTO)
2706 // Parse the url and set it as the data for the intent.
2707 emailIntent.data = Uri.parse("mailto:$linkUrl")
2709 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2710 emailIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2714 startActivity(emailIntent)
2715 } catch (exception: ActivityNotFoundException) {
2716 // Display a snackbar.
2717 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
2720 // Consume the event.
2724 // Add a copy email address entry.
2725 contextMenu.add(R.string.copy_email_address).setOnMenuItemClickListener {
2726 // Save the email address in a clip data.
2727 val srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl)
2729 // Set the clip data as the clipboard's primary clip.
2730 clipboardManager.setPrimaryClip(srcEmailTypeClipData)
2732 // Consume the event.
2736 // Add an empty cancel entry, which by default closes the context menu.
2737 contextMenu.add(R.string.cancel)
2742 // The view parameter cannot be removed because it is called from the layout onClick.
2743 fun addTab(@Suppress("UNUSED_PARAMETER")view: View?) {
2744 // Add a new tab with a blank URL.
2748 private fun addNewTab(urlString: String, moveToTab: Boolean) {
2749 // Clear the focus from the URL edit text, so that it will be populated with the information from the new tab.
2750 urlEditText.clearFocus()
2752 // Get the new page number. The page numbers are 0 indexed, so the new page number will match the current count.
2753 val newTabNumber = tabLayout.tabCount
2756 tabLayout.addTab(tabLayout.newTab())
2759 val newTab = tabLayout.getTabAt(newTabNumber)!!
2761 // Set a custom view on the new tab.
2762 newTab.setCustomView(R.layout.tab_custom_view)
2764 // Add the new WebView page.
2765 webViewStateAdapter!!.addPage(newTabNumber, webViewViewPager2, urlString, moveToTab)
2767 // Show the app bar if it is at the bottom of the screen and the new tab is taking focus.
2768 if (bottomAppBar && moveToTab && appBarLayout.translationY != 0f) {
2769 // Animate the bottom app bar onto the screen.
2770 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0f)
2773 objectAnimator.start()
2777 private fun applyAppSettings() {
2778 // 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.
2779 defaultJavaScript = sharedPreferences.getBoolean(getString(R.string.javascript_key), false)
2780 defaultCookies = sharedPreferences.getBoolean(getString(R.string.cookies_key), false)
2781 defaultDomStorage = sharedPreferences.getBoolean(getString(R.string.dom_storage_key), false)
2782 defaultFormData = sharedPreferences.getBoolean(getString(R.string.save_form_data_key), false) // Form data can be removed once the minimum API >= 26.
2783 defaultEasyList = sharedPreferences.getBoolean(getString(R.string.easylist_key), true)
2784 defaultEasyPrivacy = sharedPreferences.getBoolean(getString(R.string.easyprivacy_key), true)
2785 defaultFanboysAnnoyanceList = sharedPreferences.getBoolean(getString(R.string.fanboys_annoyance_list_key), true)
2786 defaultFanboysSocialBlockingList = sharedPreferences.getBoolean(getString(R.string.fanboys_social_blocking_list_key), true)
2787 defaultUltraList = sharedPreferences.getBoolean(getString(R.string.ultralist_key), true)
2788 defaultUltraPrivacy = sharedPreferences.getBoolean(getString(R.string.ultraprivacy_key), true)
2789 defaultBlockAllThirdPartyRequests = sharedPreferences.getBoolean(getString(R.string.block_all_third_party_requests_key), false)
2790 defaultFontSizeString = sharedPreferences.getString(getString(R.string.font_size_key), getString(R.string.font_size_default_value))!!
2791 defaultUserAgentName = sharedPreferences.getString(getString(R.string.user_agent_key), getString(R.string.user_agent_default_value))!!
2792 defaultSwipeToRefresh = sharedPreferences.getBoolean(getString(R.string.swipe_to_refresh_key), true)
2793 defaultWebViewTheme = sharedPreferences.getString(getString(R.string.webview_theme_key), getString(R.string.webview_theme_default_value))!!
2794 defaultWideViewport = sharedPreferences.getBoolean(getString(R.string.wide_viewport_key), true)
2795 defaultDisplayWebpageImages = sharedPreferences.getBoolean(getString(R.string.display_webpage_images_key), true)
2797 // 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.
2798 webViewThemeEntryValuesStringArray = resources.getStringArray(R.array.webview_theme_entry_values)
2800 // 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.
2801 userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item)
2802 userAgentDataArray = resources.getStringArray(R.array.user_agent_data)
2804 // Store the values from the shared preferences in variables.
2805 incognitoModeEnabled = sharedPreferences.getBoolean(getString(R.string.incognito_mode_key), false)
2806 sanitizeTrackingQueries = sharedPreferences.getBoolean(getString(R.string.tracking_queries_key), true)
2807 sanitizeAmpRedirects = sharedPreferences.getBoolean(getString(R.string.amp_redirects_key), true)
2808 proxyMode = sharedPreferences.getString(getString(R.string.proxy_key), getString(R.string.proxy_default_value))!!
2809 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean(getString(R.string.full_screen_browsing_mode_key), false)
2810 hideAppBar = sharedPreferences.getBoolean(getString(R.string.hide_app_bar_key), true)
2811 downloadWithExternalApp = sharedPreferences.getBoolean(getString(R.string.download_with_external_app_key), false)
2812 scrollAppBar = sharedPreferences.getBoolean(getString(R.string.scroll_app_bar_key), true)
2814 // Apply the saved proxy mode if the app has been restarted.
2815 if (savedProxyMode != null) {
2816 // Apply the saved proxy mode.
2817 proxyMode = savedProxyMode!!
2819 // Reset the saved proxy mode.
2820 savedProxyMode = null
2823 // Get the search string.
2824 val searchString = sharedPreferences.getString(getString(R.string.search_key), getString(R.string.search_default_value))!!
2826 // Set the search string, using the custom search URL if specified.
2827 searchURL = if (searchString == getString(R.string.custom_url_item))
2828 sharedPreferences.getString(getString(R.string.search_custom_url_key), getString(R.string.search_custom_url_default_value))!!
2835 // Adjust the layout and scrolling parameters according to the position of the app bar.
2836 if (bottomAppBar) { // The app bar is on the bottom.
2838 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) { // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
2839 // Reset the WebView padding to fill the available space.
2840 swipeRefreshLayout.setPadding(0, 0, 0, 0)
2841 } else { // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
2842 // Move the WebView above the app bar layout.
2843 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
2845 // Show the app bar if it is scrolled off the screen.
2846 if (appBarLayout.translationY != 0f) {
2847 // Animate the bottom app bar onto the screen.
2848 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0f)
2851 objectAnimator.start()
2854 } else { // The app bar is on the top.
2855 // Get the current layout parameters. Using coordinator layout parameters allows the `setBehavior()` command and using app bar layout parameters allows the `setScrollFlags()` command.
2856 val swipeRefreshLayoutParams = swipeRefreshLayout.layoutParams as CoordinatorLayout.LayoutParams
2857 val toolbarLayoutParams = toolbar.layoutParams as AppBarLayout.LayoutParams
2858 val findOnPageLayoutParams = findOnPageLinearLayout.layoutParams as AppBarLayout.LayoutParams
2859 val tabsLayoutParams = tabsLinearLayout.layoutParams as AppBarLayout.LayoutParams
2861 // Add the scrolling behavior to the layout parameters.
2863 // Enable scrolling of the app bar.
2864 swipeRefreshLayoutParams.behavior = AppBarLayout.ScrollingViewBehavior()
2865 toolbarLayoutParams.scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS or AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP
2866 findOnPageLayoutParams.scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS or AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP
2867 tabsLayoutParams.scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS or AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP
2869 // Disable scrolling of the app bar.
2870 swipeRefreshLayoutParams.behavior = null
2871 toolbarLayoutParams.scrollFlags = 0
2872 findOnPageLayoutParams.scrollFlags = 0
2873 tabsLayoutParams.scrollFlags = 0
2875 // Expand the app bar if it is currently collapsed.
2876 appBarLayout.setExpanded(true)
2879 // Set the app bar scrolling for each WebView.
2880 for (i in 0 until webViewStateAdapter!!.itemCount) {
2881 // Get the WebView tab fragment.
2882 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
2884 // Get the fragment view.
2885 val fragmentView = webViewTabFragment.view
2887 // Only modify the WebViews if they exist.
2888 if (fragmentView != null) {
2889 // Get the nested scroll WebView from the tab fragment.
2890 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
2892 // Set the app bar scrolling.
2893 nestedScrollWebView.isNestedScrollingEnabled = scrollAppBar
2898 // Update the full screen browsing mode settings.
2899 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
2900 // Update the visibility of the app bar, which might have changed in the settings.
2902 // Hide the tab linear layout.
2903 tabsLinearLayout.visibility = View.GONE
2905 // Hide the app bar.
2908 // Show the tab linear layout.
2909 tabsLinearLayout.visibility = View.VISIBLE
2911 // Show the app bar.
2915 /* Hide the system bars.
2916 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2917 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
2918 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2919 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
2922 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
2923 @Suppress("DEPRECATION")
2924 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
2925 } else { // Privacy Browser is not in full screen browsing mode.
2926 // 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.
2927 inFullScreenBrowsingMode = false
2929 // Show the tab linear layout.
2930 tabsLinearLayout.visibility = View.VISIBLE
2932 // Show the app bar.
2935 // Remove the `SYSTEM_UI` flags from the root frame layout. The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
2936 @Suppress("DEPRECATION")
2937 rootFrameLayout.systemUiVisibility = 0
2941 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
2942 @SuppressLint("SetJavaScriptEnabled")
2943 private fun applyDomainSettings(nestedScrollWebView: NestedScrollWebView, url: String?, resetTab: Boolean, reloadWebsite: Boolean, loadUrl: Boolean) {
2944 // Store the current URL.
2945 nestedScrollWebView.currentUrl = url!!
2947 // Parse the URL into a URI.
2948 val uri = Uri.parse(url)
2950 // Extract the domain from the URI.
2951 var newHostName = uri.host
2953 // Strings don't like to be null.
2954 if (newHostName == null)
2957 // 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.
2958 if ((nestedScrollWebView.currentDomainName != newHostName) || (newHostName == "")) { // A new domain is being loaded.
2959 // Set the new host name as the current domain name.
2960 nestedScrollWebView.currentDomainName = newHostName
2962 // Reset the ignoring of pinned domain information.
2963 nestedScrollWebView.ignorePinnedDomainInformation = false
2965 // Clear any pinned SSL certificate or IP addresses.
2966 nestedScrollWebView.clearPinnedSslCertificate()
2967 nestedScrollWebView.pinnedIpAddresses = ""
2969 // Reset the favorite icon if specified.
2971 // Initialize the favorite icon.
2972 nestedScrollWebView.initializeFavoriteIcon()
2974 // Get the current page position.
2975 val currentPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
2977 // Get the corresponding tab.
2978 val tab = tabLayout.getTabAt(currentPagePosition)
2980 // Update the tab if it isn't null, which sometimes happens when restarting from the background.
2982 // Get the tab custom view.
2983 val tabCustomView = tab.customView!!
2985 // Get the tab views.
2986 val tabFavoriteIconImageView = tabCustomView.findViewById<ImageView>(R.id.favorite_icon_imageview)
2987 val tabTitleTextView = tabCustomView.findViewById<TextView>(R.id.title_textview)
2989 // Set the default favorite icon as the favorite icon for this tab.
2990 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nestedScrollWebView.getFavoriteIcon(), 64, 64, true))
2992 // Set the loading title text.
2993 tabTitleTextView.setText(R.string.loading)
2997 // Initialize the domain name in database variable.
2998 var domainNameInDatabase: String? = null
3000 // Check the hostname against the domain settings set.
3001 if (domainsSettingsSet.contains(newHostName)) { // The hostname is contained in the domain settings set.
3002 // Record the domain name in the database.
3003 domainNameInDatabase = newHostName
3005 // Set the domain settings applied tracker to true.
3006 nestedScrollWebView.domainSettingsApplied = true
3007 } else { // The hostname is not contained in the domain settings set.
3008 // Set the domain settings applied tracker to false.
3009 nestedScrollWebView.domainSettingsApplied = false
3012 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3013 while (!nestedScrollWebView.domainSettingsApplied && newHostName!!.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the hostname.
3014 if (domainsSettingsSet.contains("*.$newHostName")) { // Check the host name prepended by `*.`.
3015 // Set the domain settings applied tracker to true.
3016 nestedScrollWebView.domainSettingsApplied = true
3018 // Store the applied domain names as it appears in the database.
3019 domainNameInDatabase = "*.$newHostName"
3022 // Strip out the lowest subdomain of of the host name.
3023 newHostName = newHostName.substring(newHostName.indexOf(".") + 1)
3026 // Apply either the domain settings or the default settings.
3027 if (nestedScrollWebView.domainSettingsApplied) { // The url has custom domain settings.
3028 // Get a cursor for the current host.
3029 val currentDomainSettingsCursor = domainsDatabaseHelper!!.getCursorForDomainName(domainNameInDatabase!!)
3031 // Move to the first position.
3032 currentDomainSettingsCursor.moveToFirst()
3034 // Get the settings from the cursor.
3035 nestedScrollWebView.domainSettingsDatabaseId = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ID))
3036 val javaScriptInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_JAVASCRIPT))
3037 val cookiesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(COOKIES))
3038 val domStorageInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_DOM_STORAGE))
3039 val formDataInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_FORM_DATA)) // Form data can be removed once the minimum API >= 26.
3040 val easyListInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_EASYLIST))
3041 val easyPrivacyInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_EASYPRIVACY))
3042 val fanboysAnnoyanceListInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_FANBOYS_ANNOYANCE_LIST))
3043 val fanboysSocialBlockingListInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST))
3044 val ultraListInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.ULTRALIST))
3045 val ultraPrivacyInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_ULTRAPRIVACY))
3046 val blockAllThirdPartyRequestsInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.BLOCK_ALL_THIRD_PARTY_REQUESTS))
3047 val userAgentName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.USER_AGENT))
3048 val fontSize = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(FONT_SIZE))
3049 val swipeToRefreshInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(SWIPE_TO_REFRESH))
3050 val webViewThemeInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(WEBVIEW_THEME))
3051 val wideViewportInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(WIDE_VIEWPORT))
3052 val displayWebpageImagesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DISPLAY_IMAGES))
3053 val pinnedSslCertificate = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(PINNED_SSL_CERTIFICATE)) == 1)
3054 val pinnedSslIssuedToCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_TO_COMMON_NAME))
3055 val pinnedSslIssuedToOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_TO_ORGANIZATION))
3056 val pinnedSslIssuedToUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_TO_ORGANIZATIONAL_UNIT))
3057 val pinnedSslIssuedByCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_BY_COMMON_NAME))
3058 val pinnedSslIssuedByOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_BY_ORGANIZATION))
3059 val pinnedSslIssuedByUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_BY_ORGANIZATIONAL_UNIT))
3060 val pinnedSslStartDate = Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.SSL_START_DATE)))
3061 val pinnedSslEndDate = Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.SSL_END_DATE)))
3062 val pinnedIpAddresses = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(PINNED_IP_ADDRESSES)) == 1)
3063 val pinnedHostIpAddresses = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(IP_ADDRESSES))
3065 // Close the current host domain settings cursor.
3066 currentDomainSettingsCursor.close()
3068 // Set the JavaScript status.
3069 when (javaScriptInt) {
3070 SYSTEM_DEFAULT -> nestedScrollWebView.settings.javaScriptEnabled = defaultJavaScript
3071 ENABLED -> nestedScrollWebView.settings.javaScriptEnabled = true
3072 DISABLED -> nestedScrollWebView.settings.javaScriptEnabled = false
3075 // Store the cookies status.
3077 SYSTEM_DEFAULT -> nestedScrollWebView.acceptCookies = defaultCookies
3078 ENABLED -> nestedScrollWebView.acceptCookies = true
3079 DISABLED -> nestedScrollWebView.acceptCookies = false
3082 // Apply the cookies status.
3083 cookieManager.setAcceptCookie(nestedScrollWebView.acceptCookies)
3085 // Set the DOM storage status.
3086 when (domStorageInt) {
3087 SYSTEM_DEFAULT -> nestedScrollWebView.settings.domStorageEnabled = defaultDomStorage
3088 ENABLED -> nestedScrollWebView.settings.domStorageEnabled = true
3089 DISABLED -> nestedScrollWebView.settings.domStorageEnabled = false
3092 // Apply the form data setting if the API < 26.
3093 @Suppress("DEPRECATION")
3094 if (Build.VERSION.SDK_INT < 26) {
3095 // Set the form data status.
3096 when (formDataInt) {
3097 SYSTEM_DEFAULT -> nestedScrollWebView.settings.saveFormData = defaultFormData
3098 ENABLED -> nestedScrollWebView.settings.saveFormData = true
3099 DISABLED -> nestedScrollWebView.settings.saveFormData = false
3103 // Set the EasyList status.
3104 when (easyListInt) {
3105 SYSTEM_DEFAULT -> nestedScrollWebView.easyListEnabled = defaultEasyList
3106 ENABLED -> nestedScrollWebView.easyListEnabled = true
3107 DISABLED -> nestedScrollWebView.easyListEnabled = false
3110 // Set the EasyPrivacy status.
3111 when (easyPrivacyInt) {
3112 SYSTEM_DEFAULT -> nestedScrollWebView.easyPrivacyEnabled = defaultEasyPrivacy
3113 ENABLED -> nestedScrollWebView.easyPrivacyEnabled = true
3114 DISABLED -> nestedScrollWebView.easyPrivacyEnabled = false
3117 // Set the Fanboy's Annoyance List status.
3118 when (fanboysAnnoyanceListInt) {
3119 SYSTEM_DEFAULT -> nestedScrollWebView.fanboysAnnoyanceListEnabled = defaultFanboysAnnoyanceList
3120 ENABLED -> nestedScrollWebView.fanboysAnnoyanceListEnabled = true
3121 DISABLED -> nestedScrollWebView.fanboysAnnoyanceListEnabled = false
3124 // Set the Fanboy's Social Blocking List status.
3125 when (fanboysSocialBlockingListInt) {
3126 SYSTEM_DEFAULT -> nestedScrollWebView.fanboysSocialBlockingListEnabled = defaultFanboysSocialBlockingList
3127 ENABLED -> nestedScrollWebView.fanboysSocialBlockingListEnabled = true
3128 DISABLED -> nestedScrollWebView.fanboysSocialBlockingListEnabled = false
3131 // Set the UltraList status.
3132 when (ultraListInt) {
3133 SYSTEM_DEFAULT -> nestedScrollWebView.ultraListEnabled = defaultUltraList
3134 ENABLED -> nestedScrollWebView.ultraListEnabled = true
3135 DISABLED -> nestedScrollWebView.ultraListEnabled = false
3138 // Set the UltraPrivacy status.
3139 when (ultraPrivacyInt) {
3140 SYSTEM_DEFAULT -> nestedScrollWebView.ultraPrivacyEnabled = defaultUltraPrivacy
3141 ENABLED -> nestedScrollWebView.ultraPrivacyEnabled = true
3142 DISABLED -> nestedScrollWebView.ultraPrivacyEnabled = false
3145 // Set the block all third-party requests status.
3146 when (blockAllThirdPartyRequestsInt) {
3147 SYSTEM_DEFAULT -> nestedScrollWebView.blockAllThirdPartyRequests = defaultBlockAllThirdPartyRequests
3148 ENABLED -> nestedScrollWebView.blockAllThirdPartyRequests = true
3149 DISABLED -> nestedScrollWebView.blockAllThirdPartyRequests = false
3152 // Set the user agent.
3153 if (userAgentName == getString(R.string.system_default_user_agent)) { // Use the system default user agent.
3154 // Set the user agent according to the system default.
3155 when (val defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName)) {
3156 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3157 UNRECOGNIZED_USER_AGENT -> nestedScrollWebView.settings.userAgentString = defaultUserAgentName
3159 // Set the user agent to `""`, which uses the default value.
3160 SETTINGS_WEBVIEW_DEFAULT_USER_AGENT -> nestedScrollWebView.settings.userAgentString = ""
3162 // Set the default custom user agent.
3163 SETTINGS_CUSTOM_USER_AGENT -> nestedScrollWebView.settings.userAgentString =
3164 sharedPreferences.getString(getString(R.string.custom_user_agent_key), getString(R.string.custom_user_agent_default_value))
3166 // Get the user agent string from the user agent data array
3167 else -> nestedScrollWebView.settings.userAgentString = userAgentDataArray[defaultUserAgentArrayPosition]
3169 } else { // Set the user agent according to the stored name.
3170 // Set the user agent.
3171 when (val userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName)) {
3172 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3173 UNRECOGNIZED_USER_AGENT ->
3174 nestedScrollWebView.settings.userAgentString = userAgentName
3176 // Set the user agent to `""`, which uses the default value.
3177 SETTINGS_WEBVIEW_DEFAULT_USER_AGENT ->
3178 nestedScrollWebView.settings.userAgentString = ""
3180 // Get the user agent string from the user agent data array.
3182 nestedScrollWebView.settings.userAgentString = userAgentDataArray[userAgentArrayPosition]
3186 // Apply the font size.
3187 try { // Try the specified font size to see if it is valid.
3188 if (fontSize == 0) { // Apply the default font size.
3189 // Set the font size from the value in the app settings.
3190 nestedScrollWebView.settings.textZoom = defaultFontSizeString.toInt()
3191 } else { // Apply the font size from domain settings.
3192 nestedScrollWebView.settings.textZoom = fontSize
3194 } catch (exception: Exception) { // The specified font size is invalid
3195 // Set the font size to be 100%
3196 nestedScrollWebView.settings.textZoom = 100
3199 // Set swipe to refresh.
3200 when (swipeToRefreshInt) {
3202 // Store the swipe to refresh status in the nested scroll WebView.
3203 nestedScrollWebView.swipeToRefresh = defaultSwipeToRefresh
3205 // Update the swipe refresh layout.
3206 if (defaultSwipeToRefresh) { // Swipe to refresh is enabled.
3207 // 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).
3208 if (currentWebView != null) {
3209 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
3210 swipeRefreshLayout.isEnabled = (currentWebView!!.scrollY == 0)
3212 } else { // Swipe to refresh is disabled.
3213 // Disable the swipe refresh layout.
3214 swipeRefreshLayout.isEnabled = false
3219 // Store the swipe to refresh status in the nested scroll WebView.
3220 nestedScrollWebView.swipeToRefresh = true
3222 // 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).
3223 if (currentWebView != null) {
3224 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
3225 swipeRefreshLayout.isEnabled = (currentWebView!!.scrollY == 0)
3230 // Store the swipe to refresh status in the nested scroll WebView.
3231 nestedScrollWebView.swipeToRefresh = false
3233 // Disable swipe to refresh.
3234 swipeRefreshLayout.isEnabled = false
3238 // Set the WebView theme if algorithmic darkening is supported.
3239 if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {
3240 // Set the WebView theme.
3241 when (webViewThemeInt) {
3242 // Set the WebView theme.
3244 when (defaultWebViewTheme) {
3245 // The light theme is selected. Turn off algorithmic darkening.
3246 webViewThemeEntryValuesStringArray[1] -> WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
3248 // The dark theme is selected. Turn on algorithmic darkening.
3249 webViewThemeEntryValuesStringArray[2] -> WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
3251 // The system default theme is selected.
3253 // Get the current system theme status.
3254 val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
3256 // Set the algorithmic darkening according to the current system theme status.
3257 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, currentThemeStatus == Configuration.UI_MODE_NIGHT_YES)
3261 // Turn off algorithmic darkening.
3262 LIGHT_THEME -> WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
3264 // Turn on algorithmic darkening.
3265 DARK_THEME -> WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
3269 // Set the wide viewport status.
3270 when (wideViewportInt) {
3271 SYSTEM_DEFAULT -> nestedScrollWebView.settings.useWideViewPort = defaultWideViewport
3272 ENABLED -> nestedScrollWebView.settings.useWideViewPort = true
3273 DISABLED -> nestedScrollWebView.settings.useWideViewPort = false
3276 // Set the display webpage images status.
3277 when (displayWebpageImagesInt) {
3278 SYSTEM_DEFAULT -> nestedScrollWebView.settings.loadsImagesAutomatically = defaultDisplayWebpageImages
3279 ENABLED -> nestedScrollWebView.settings.loadsImagesAutomatically = true
3280 DISABLED -> nestedScrollWebView.settings.loadsImagesAutomatically = false
3283 // If there is a pinned SSL certificate, store it in the WebView.
3284 if (pinnedSslCertificate)
3285 nestedScrollWebView.setPinnedSslCertificate(pinnedSslIssuedToCName, pinnedSslIssuedToOName, pinnedSslIssuedToUName, pinnedSslIssuedByCName, pinnedSslIssuedByOName, pinnedSslIssuedByUName,
3286 pinnedSslStartDate, pinnedSslEndDate)
3288 // If there is a pinned IP address, store it in the WebView.
3289 if (pinnedIpAddresses)
3290 nestedScrollWebView.pinnedIpAddresses = pinnedHostIpAddresses
3292 // Set a background on the URL relative layout to indicate that custom domain settings are being used.
3293 urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.drawable.domain_settings_url_background)
3294 } else { // The new URL does not have custom domain settings. Load the defaults.
3295 // Store the values from the shared preferences.
3296 nestedScrollWebView.settings.javaScriptEnabled = defaultJavaScript
3297 nestedScrollWebView.acceptCookies = defaultCookies
3298 nestedScrollWebView.settings.domStorageEnabled = defaultDomStorage
3299 nestedScrollWebView.easyListEnabled = defaultEasyList
3300 nestedScrollWebView.easyPrivacyEnabled = defaultEasyPrivacy
3301 nestedScrollWebView.fanboysAnnoyanceListEnabled = defaultFanboysAnnoyanceList
3302 nestedScrollWebView.fanboysSocialBlockingListEnabled = defaultFanboysSocialBlockingList
3303 nestedScrollWebView.ultraListEnabled = defaultUltraList
3304 nestedScrollWebView.ultraPrivacyEnabled = defaultUltraPrivacy
3305 nestedScrollWebView.blockAllThirdPartyRequests = defaultBlockAllThirdPartyRequests
3307 // Apply the default cookie setting.
3308 cookieManager.setAcceptCookie(nestedScrollWebView.acceptCookies)
3310 // Apply the form data setting if the API < 26.
3311 if (Build.VERSION.SDK_INT < 26)
3312 @Suppress("DEPRECATION")
3313 nestedScrollWebView.settings.saveFormData = defaultFormData
3315 // Apply the default font size setting.
3317 // Try to set the font size from the value in the app settings.
3318 nestedScrollWebView.settings.textZoom = defaultFontSizeString.toInt()
3319 } catch (exception: Exception) {
3320 // If the app settings value is invalid, set the font size to 100%.
3321 nestedScrollWebView.settings.textZoom = 100
3324 // Store the swipe to refresh status in the nested scroll WebView.
3325 nestedScrollWebView.swipeToRefresh = defaultSwipeToRefresh
3327 // Update the swipe refresh layout.
3328 if (defaultSwipeToRefresh) { // Swipe to refresh is enabled.
3329 // 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).
3330 if (currentWebView != null) {
3331 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
3332 swipeRefreshLayout.isEnabled = currentWebView!!.scrollY == 0
3334 } else { // Swipe to refresh is disabled.
3335 // Disable the swipe refresh layout.
3336 swipeRefreshLayout.isEnabled = false
3339 // Reset the domain settings database ID.
3340 nestedScrollWebView.domainSettingsDatabaseId = -1
3342 // Set the user agent.
3343 when (val userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName)) {
3344 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3345 UNRECOGNIZED_USER_AGENT -> nestedScrollWebView.settings.userAgentString = defaultUserAgentName
3347 // Set the user agent to `""`, which uses the default value.
3348 SETTINGS_WEBVIEW_DEFAULT_USER_AGENT -> nestedScrollWebView.settings.userAgentString = ""
3350 // Set the default custom user agent.
3351 SETTINGS_CUSTOM_USER_AGENT -> nestedScrollWebView.settings.userAgentString =
3352 sharedPreferences.getString(getString(R.string.custom_user_agent_key), getString(R.string.custom_user_agent_default_value))
3354 // Get the user agent string from the user agent data array
3355 else -> nestedScrollWebView.settings.userAgentString = userAgentDataArray[userAgentArrayPosition]
3358 // Set the WebView theme if algorithmic darkening is supported.
3359 if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {
3360 // Set the WebView theme.
3361 when (defaultWebViewTheme) {
3362 // The light theme is selected. Turn off algorithmic darkening.
3363 webViewThemeEntryValuesStringArray[1] -> WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
3365 // The dark theme is selected. Turn on algorithmic darkening.
3366 webViewThemeEntryValuesStringArray[2] -> WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
3368 // The system default theme is selected. Get the current system theme status.
3370 // Get the current theme status.
3371 val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
3373 // Set the algorithmic darkening according to the current system theme status.
3374 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, currentThemeStatus == Configuration.UI_MODE_NIGHT_YES)
3379 // Set the viewport.
3380 nestedScrollWebView.settings.useWideViewPort = defaultWideViewport
3382 // Set the loading of webpage images.
3383 nestedScrollWebView.settings.loadsImagesAutomatically = defaultDisplayWebpageImages
3385 // Set a transparent background on the URL relative layout.
3386 urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.color.transparent)
3389 // Update the privacy icons.
3390 updatePrivacyIcons(true)
3393 // Reload the website if returning from the Domains activity.
3395 nestedScrollWebView.reload()
3397 // 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.
3399 nestedScrollWebView.loadUrl(url)
3402 private fun applyProxy(reloadWebViews: Boolean) {
3403 // Set the proxy according to the mode.
3404 proxyHelper.setProxy(applicationContext, appBarLayout, proxyMode)
3406 // Reset the waiting for proxy tracker.
3407 waitingForProxy = false
3411 ProxyHelper.NONE -> {
3412 // Initialize a color background typed value.
3413 val colorBackgroundTypedValue = TypedValue()
3415 // Get the color background from the theme.
3416 theme.resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true)
3418 // Get the color background int from the typed value.
3419 val colorBackgroundInt = colorBackgroundTypedValue.data
3421 // Set the default app bar layout background.
3422 appBarLayout.setBackgroundColor(colorBackgroundInt)
3425 ProxyHelper.TOR -> {
3426 // Set the app bar background to indicate proxying is enabled.
3427 appBarLayout.setBackgroundResource(R.color.blue_background)
3429 // Check to see if Orbot is installed.
3431 // Get the package manager.
3432 val packageManager = packageManager
3434 // 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.
3435 @Suppress("DEPRECATION")
3436 packageManager.getPackageInfo("org.torproject.android", 0)
3438 // Check to see if the proxy is ready.
3439 if (orbotStatus != ProxyHelper.ORBOT_STATUS_ON) { // Orbot is not ready.
3440 // Set the waiting for proxy status.
3441 waitingForProxy = true
3443 // Show the waiting for proxy dialog if it isn't already displayed.
3444 if (supportFragmentManager.findFragmentByTag(getString(R.string.waiting_for_proxy_dialog)) == null) {
3445 // Get a handle for the waiting for proxy alert dialog.
3446 val waitingForProxyDialogFragment = WaitingForProxyDialog()
3448 // Try to show the dialog. Sometimes the window is not yet active if returning from Settings.
3450 // Show the waiting for proxy alert dialog.
3451 waitingForProxyDialogFragment.show(supportFragmentManager, getString(R.string.waiting_for_proxy_dialog))
3452 } catch (waitingForTorException: Exception) {
3453 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
3454 pendingDialogsArrayList.add(PendingDialogDataClass(waitingForProxyDialogFragment, getString(R.string.waiting_for_proxy_dialog)))
3458 } catch (exception: PackageManager.NameNotFoundException) { // Orbot is not installed.
3459 // Show the Orbot not installed dialog if it is not already displayed.
3460 if (supportFragmentManager.findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
3461 // Get a handle for the Orbot not installed alert dialog.
3462 val orbotNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode)
3464 // Try to show the dialog. Sometimes the window is not yet active if returning from Settings.
3466 // Display the Orbot not installed alert dialog.
3467 orbotNotInstalledDialogFragment.show(supportFragmentManager, getString(R.string.proxy_not_installed_dialog))
3468 } catch (orbotNotInstalledException: Exception) {
3469 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
3470 pendingDialogsArrayList.add(PendingDialogDataClass(orbotNotInstalledDialogFragment, getString(R.string.proxy_not_installed_dialog)))
3476 ProxyHelper.I2P -> {
3477 // Set the app bar background to indicate proxying is enabled.
3478 appBarLayout.setBackgroundResource(R.color.blue_background)
3480 // Check to see if I2P is installed.
3482 // 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.
3483 // The deprecated method must be used until the minimum API >= 33.
3484 @Suppress("DEPRECATION")
3485 packageManager.getPackageInfo("net.i2p.android.router", 0)
3486 } catch (fdroidException: PackageManager.NameNotFoundException) { // The F-Droid flavor is not installed.
3488 // 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.
3489 // The deprecated method must be used until the minimum API >= 33.
3490 @Suppress("DEPRECATION")
3491 packageManager.getPackageInfo("net.i2p.android", 0)
3492 } catch (googlePlayException: PackageManager.NameNotFoundException) { // The Google Play flavor is not installed.
3493 // Sow the I2P not installed dialog if it is not already displayed.
3494 if (supportFragmentManager.findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
3495 // Get a handle for the waiting for proxy alert dialog.
3496 val i2pNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode)
3498 // Try to show the dialog. Sometimes the window is not yet active if returning from Settings.
3500 // Display the I2P not installed alert dialog.
3501 i2pNotInstalledDialogFragment.show(supportFragmentManager, getString(R.string.proxy_not_installed_dialog))
3502 } catch (i2pNotInstalledException: Exception) {
3503 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
3504 pendingDialogsArrayList.add(PendingDialogDataClass(i2pNotInstalledDialogFragment, getString(R.string.proxy_not_installed_dialog)))
3511 ProxyHelper.CUSTOM ->
3512 // Set the app bar background to indicate proxying is enabled.
3513 appBarLayout.setBackgroundResource(R.color.blue_background)
3516 // Reload the WebViews if requested and not waiting for the proxy.
3517 if (reloadWebViews && !waitingForProxy) {
3518 // Reload the WebViews.
3519 for (i in 0 until webViewStateAdapter!!.itemCount) {
3520 // Get the WebView tab fragment.
3521 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
3523 // Get the fragment view.
3524 val fragmentView = webViewTabFragment.view
3526 // Only reload the WebViews if they exist.
3527 if (fragmentView != null) {
3528 // Get the nested scroll WebView from the tab fragment.
3529 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
3531 // Reload the WebView.
3532 nestedScrollWebView.reload()
3538 // The view parameter cannot be removed because it is called from the layout onClick.
3539 fun bookmarksBack(@Suppress("UNUSED_PARAMETER")view: View?) {
3540 if (currentBookmarksFolderId == HOME_FOLDER_ID) { // The home folder is displayed.
3541 // close the bookmarks drawer.
3542 drawerLayout.closeDrawer(GravityCompat.END)
3543 } else { // A subfolder is displayed.
3544 // Set the former parent folder as the current folder.
3545 currentBookmarksFolderId = bookmarksDatabaseHelper!!.getParentFolderId(currentBookmarksFolderId)
3547 // Load the new folder.
3548 loadBookmarksFolder()
3552 private fun clearAndExit() {
3553 // Close the bookmarks cursor if it exists.
3554 bookmarksCursor?.close()
3556 // Close the databases helpers if they exist.
3557 bookmarksDatabaseHelper?.close()
3558 domainsDatabaseHelper?.close()
3560 // Get the status of the clear everything preference.
3561 val clearEverything = sharedPreferences.getBoolean(getString(R.string.clear_everything_key), true)
3563 // Get a handle for the runtime.
3564 val runtime = Runtime.getRuntime()
3566 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
3567 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
3568 val privateDataDirectoryString = applicationInfo.dataDir
3571 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_cookies_key), true)) {
3572 // Ass the cookie manager to delete all the cookies.
3573 cookieManager.removeAllCookies(null)
3575 // Ask the cookie manager to flush the cookie database.
3576 cookieManager.flush()
3578 // Manually delete the cookies database, as the cookie manager sometimes will not flush its changes to disk before system exit is run.
3580 // Two commands must be used because `Runtime.exec()` does not like `*`.
3581 val deleteCookiesProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/Cookies")
3582 val deleteCookiesJournalProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/Cookies-journal")
3584 // Wait until the processes have finished.
3585 deleteCookiesProcess.waitFor()
3586 deleteCookiesJournalProcess.waitFor()
3587 } catch (exception: Exception) {
3588 // Do nothing if an error is thrown.
3592 // Clear DOM storage.
3593 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_dom_storage_key), true)) {
3594 // Ask web storage to clear the DOM storage.
3595 WebStorage.getInstance().deleteAllData()
3597 // Manually delete the DOM storage files and directories, as web storage sometimes will not flush its changes to disk before system exit is run.
3599 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
3600 val deleteLocalStorageProcess = runtime.exec(arrayOf("rm", "-rf", "$privateDataDirectoryString/app_webview/Local Storage/"))
3602 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
3603 val deleteIndexProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview/IndexedDB")
3604 val deleteQuotaManagerProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/QuotaManager")
3605 val deleteQuotaManagerJournalProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/QuotaManager-journal")
3606 val deleteDatabaseProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview/databases")
3608 // Wait until the processes have finished.
3609 deleteLocalStorageProcess.waitFor()
3610 deleteIndexProcess.waitFor()
3611 deleteQuotaManagerProcess.waitFor()
3612 deleteQuotaManagerJournalProcess.waitFor()
3613 deleteDatabaseProcess.waitFor()
3614 } catch (exception: Exception) {
3615 // Do nothing if an error is thrown.
3619 // Clear form data if the API < 26.
3620 if (Build.VERSION.SDK_INT < 26 && (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_form_data_key), true))) {
3621 // Ask the WebView database to clear the form data.
3622 @Suppress("DEPRECATION")
3623 WebViewDatabase.getInstance(this).clearFormData()
3625 // Manually delete the form data database, as the WebView database sometimes will not flush its changes to disk before system exit is run.
3627 // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
3628 val deleteWebDataProcess = runtime.exec(arrayOf("rm", "-f", "$privateDataDirectoryString/app_webview/Web Data"))
3629 val deleteWebDataJournalProcess = runtime.exec(arrayOf("rm", "-f", "$privateDataDirectoryString/app_webview/Web Data-journal"))
3631 // Wait until the processes have finished.
3632 deleteWebDataProcess.waitFor()
3633 deleteWebDataJournalProcess.waitFor()
3634 } catch (exception: Exception) {
3635 // Do nothing if an error is thrown.
3639 // Clear the logcat.
3640 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_logcat_key), true)) {
3642 // Clear the logcat. `-c` clears the logcat. `-b all` clears all the buffers (instead of just crash, main, and system).
3643 val process = Runtime.getRuntime().exec("logcat -b all -c")
3645 // Wait for the process to finish.
3647 } catch (exception: IOException) {
3649 } catch (exception: InterruptedException) {
3655 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_cache_key), true)) {
3656 // Clear the cache from each WebView.
3657 for (i in 0 until webViewStateAdapter!!.itemCount) {
3658 // Get the WebView tab fragment.
3659 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
3661 // Get the WebView fragment view.
3662 val webViewFragmentView = webViewTabFragment.view
3664 // Only clear the cache if the WebView exists.
3665 if (webViewFragmentView != null) {
3666 // Get the nested scroll WebView from the tab fragment.
3667 val nestedScrollWebView = webViewFragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
3669 // Clear the cache for this WebView.
3670 nestedScrollWebView.clearCache(true)
3674 // Manually delete the cache directories.
3676 // Delete the main cache directory.
3677 val deleteCacheProcess = runtime.exec("rm -rf $privateDataDirectoryString/cache")
3679 // Delete the secondary `Service Worker` cache directory.
3680 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
3681 val deleteServiceWorkerProcess = runtime.exec(arrayOf("rm", "-rf", "$privateDataDirectoryString/app_webview/Default/Service Worker/"))
3683 // Wait until the processes have finished.
3684 deleteCacheProcess.waitFor()
3685 deleteServiceWorkerProcess.waitFor()
3686 } catch (exception: Exception) {
3687 // Do nothing if an error is thrown.
3691 // Wipe out 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 frame layout.
3697 val webViewFrameLayout = webViewTabFragment.view as FrameLayout?
3699 // Only wipe out the WebView if it exists.
3700 if (webViewFrameLayout != null) {
3701 // Get the nested scroll WebView from the tab fragment.
3702 val nestedScrollWebView = webViewFrameLayout.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
3704 // Clear SSL certificate preferences for this WebView.
3705 nestedScrollWebView.clearSslPreferences()
3707 // Clear the back/forward history for this WebView.
3708 nestedScrollWebView.clearHistory()
3710 // Remove all the views from the frame layout.
3711 webViewFrameLayout.removeAllViews()
3713 // Destroy the internal state of the WebView.
3714 nestedScrollWebView.destroy()
3718 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
3719 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
3720 if (clearEverything) {
3722 // Delete the folder.
3723 val deleteAppWebviewProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview")
3725 // Wait until the process has finished.
3726 deleteAppWebviewProcess.waitFor()
3727 } catch (exception: Exception) {
3728 // Do nothing if an error is thrown.
3732 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
3733 finishAndRemoveTask()
3735 // Remove the terminated program from RAM. The status code is `0`.
3739 // The view parameter cannot be removed because it is called from the layout onClick.
3740 fun closeFindOnPage(@Suppress("UNUSED_PARAMETER")view: View?) {
3741 // Delete the contents of the find on page edit text.
3742 findOnPageEditText.text = null
3744 // Clear the highlighted phrases if the WebView is not null.
3745 currentWebView?.clearMatches()
3747 // Hide the find on page linear layout.
3748 findOnPageLinearLayout.visibility = View.GONE
3750 // Show the toolbar.
3751 toolbar.visibility = View.VISIBLE
3753 // Get a handle for the input method manager.
3754 val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
3756 // Hide the keyboard.
3757 inputMethodManager.hideSoftInputFromWindow(toolbar.windowToken, 0)
3760 // The view parameter cannot be removed because it is called from the layout onClick.
3761 fun closeTab(@Suppress("UNUSED_PARAMETER")view: View?) {
3762 // Run the command according to the number of tabs.
3763 if (tabLayout.tabCount > 1) { // There is more than one tab open.
3764 // Get the current tab number.
3765 val currentTabNumber = tabLayout.selectedTabPosition
3767 // Delete the current tab.
3768 tabLayout.removeTabAt(currentTabNumber)
3770 // 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,
3771 // meaning that the current WebView must be reset. Otherwise it will happen automatically as the selected tab number changes.
3772 if (webViewStateAdapter!!.deletePage(currentTabNumber, webViewViewPager2))
3773 setCurrentWebView(currentTabNumber)
3774 } else { // There is only one tab open.
3779 override fun createBookmark(dialogFragment: DialogFragment, favoriteIconBitmap: Bitmap) {
3781 val dialog = dialogFragment.dialog!!
3783 // Get the views from the dialog fragment.
3784 val createBookmarkNameEditText = dialog.findViewById<EditText>(R.id.create_bookmark_name_edittext)
3785 val createBookmarkUrlEditText = dialog.findViewById<EditText>(R.id.create_bookmark_url_edittext)
3787 // Extract the strings from the edit texts.
3788 val bookmarkNameString = createBookmarkNameEditText.text.toString()
3789 val bookmarkUrlString = createBookmarkUrlEditText.text.toString()
3791 // Create a favorite icon byte array output stream.
3792 val favoriteIconByteArrayOutputStream = ByteArrayOutputStream()
3794 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
3795 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream)
3797 // Convert the favorite icon byte array stream to a byte array.
3798 val favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray()
3800 // Display the new bookmark below the current items in the (0 indexed) list.
3801 val newBookmarkDisplayOrder = bookmarksListView.count
3803 // Create the bookmark.
3804 bookmarksDatabaseHelper!!.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolderId, newBookmarkDisplayOrder, favoriteIconByteArray)
3806 // Update the bookmarks cursor with the current contents of this folder.
3807 bookmarksCursor = bookmarksDatabaseHelper!!.getBookmarksByDisplayOrder(currentBookmarksFolderId)
3809 // Update the list view.
3810 bookmarksCursorAdapter.changeCursor(bookmarksCursor)
3812 // Scroll to the new bookmark.
3813 bookmarksListView.setSelection(newBookmarkDisplayOrder)
3816 override fun createBookmarkFolder(dialogFragment: DialogFragment, favoriteIconBitmap: Bitmap) {
3818 val dialog = dialogFragment.dialog!!
3820 // Get handles for the views in the dialog fragment.
3821 val folderNameEditText = dialog.findViewById<EditText>(R.id.folder_name_edittext)
3822 val defaultIconRadioButton = dialog.findViewById<RadioButton>(R.id.default_icon_radiobutton)
3823 val defaultIconImageView = dialog.findViewById<ImageView>(R.id.default_icon_imageview)
3825 // Get new folder name string.
3826 val folderNameString = folderNameEditText.text.toString()
3828 // Set the folder icon bitmap according to the dialog.
3829 val folderIconBitmap: Bitmap = if (defaultIconRadioButton.isChecked) { // Use the default folder icon.
3830 // Get the default folder icon drawable.
3831 val folderIconDrawable = defaultIconImageView.drawable
3833 // Convert the folder icon drawable to a bitmap drawable.
3834 val folderIconBitmapDrawable = folderIconDrawable as BitmapDrawable
3836 // Convert the folder icon bitmap drawable to a bitmap.
3837 folderIconBitmapDrawable.bitmap
3838 } else { // Use the WebView favorite icon.
3839 // Copy the favorite icon bitmap to the folder icon bitmap.
3843 // Create a folder icon byte array output stream.
3844 val folderIconByteArrayOutputStream = ByteArrayOutputStream()
3846 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
3847 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream)
3849 // Convert the folder icon byte array stream to a byte array.
3850 val folderIconByteArray = folderIconByteArrayOutputStream.toByteArray()
3852 // Move all the bookmarks down one in the display order.
3853 for (i in 0 until bookmarksListView.count) {
3854 // Get the bookmark database id.
3855 val databaseId = bookmarksListView.getItemIdAtPosition(i).toInt()
3857 // Move the bookmark down one slot.
3858 bookmarksDatabaseHelper!!.updateDisplayOrder(databaseId, i + 1)
3861 // Create the folder, which will be placed at the top of the list view.
3862 bookmarksDatabaseHelper!!.createFolder(folderNameString, currentBookmarksFolderId, folderIconByteArray)
3864 // Update the bookmarks cursor with the current contents of this folder.
3865 bookmarksCursor = bookmarksDatabaseHelper!!.getBookmarksByDisplayOrder(currentBookmarksFolderId)
3867 // Update the list view.
3868 bookmarksCursorAdapter.changeCursor(bookmarksCursor)
3870 // Scroll to the new folder.
3871 bookmarksListView.setSelection(0)
3874 private fun downloadUrlWithExternalApp(url: String) {
3875 // Create a download intent. Not specifying the action type will display the maximum number of options.
3876 val downloadIntent = Intent()
3878 // Set the URI and the mime type.
3879 downloadIntent.setDataAndType(Uri.parse(url), "text/html")
3881 // Flag the intent to open in a new task.
3882 downloadIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
3884 // Show the chooser.
3885 startActivity(Intent.createChooser(downloadIntent, getString(R.string.download_with_external_app)))
3888 private fun exitFullScreenVideo() {
3889 // Re-enable the screen timeout.
3890 fullScreenVideoFrameLayout.keepScreenOn = false
3892 // Unset the full screen video flag.
3893 displayingFullScreenVideo = false
3895 // Remove all the views from the full screen video frame layout.
3896 fullScreenVideoFrameLayout.removeAllViews()
3898 // Hide the full screen video frame layout.
3899 fullScreenVideoFrameLayout.visibility = View.GONE
3901 // Enable the sliding drawers.
3902 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED)
3904 // Show the coordinator layout.
3905 coordinatorLayout.visibility = View.VISIBLE
3907 // Apply the appropriate full screen mode flags.
3908 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
3909 // Hide the app bar if specified.
3911 // Hide the tab linear layout.
3912 tabsLinearLayout.visibility = View.GONE
3914 // Hide the app bar.
3918 /* Hide the system bars.
3919 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3920 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
3921 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3922 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3925 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
3926 @Suppress("DEPRECATION")
3927 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
3928 } else { // Switch to normal viewing mode.
3929 // Remove the `SYSTEM_UI` flags from the root frame layout. The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
3930 @Suppress("DEPRECATION")
3931 rootFrameLayout.systemUiVisibility = 0
3935 // The view parameter cannot be removed because it is called from the layout onClick.
3936 fun findNextOnPage(@Suppress("UNUSED_PARAMETER")view: View?) {
3937 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
3938 currentWebView!!.findNext(true)
3941 // The view parameter cannot be removed because it is called from the layout onClick.
3942 fun findPreviousOnPage(@Suppress("UNUSED_PARAMETER")view: View?) {
3943 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
3944 currentWebView!!.findNext(false)
3947 override fun finishedPopulatingFilterLists(combinedFilterLists: ArrayList<ArrayList<List<Array<String>>>>) {
3948 // Store the filter lists.
3949 easyList = combinedFilterLists[0]
3950 easyPrivacy = combinedFilterLists[1]
3951 fanboysAnnoyanceList = combinedFilterLists[2]
3952 fanboysSocialList = combinedFilterLists[3]
3953 ultraList = combinedFilterLists[4]
3954 ultraPrivacy = combinedFilterLists[5]
3956 // Check to see if the activity has been restarted with a saved state.
3957 if ((savedStateArrayList == null) || (savedStateArrayList!!.size == 0)) { // The activity has not been restarted or it was restarted on start to change the theme.
3958 // Add the first tab.
3959 addNewTab("", false)
3960 } else { // The activity has been restarted.
3961 // Restore each tab.
3962 for (i in savedStateArrayList!!.indices) {
3964 tabLayout.addTab(tabLayout.newTab())
3967 val newTab = tabLayout.getTabAt(i)!!
3969 // Set a custom view on the new tab.
3970 newTab.setCustomView(R.layout.tab_custom_view)
3972 // Add the new page.
3973 webViewStateAdapter!!.restorePage(savedStateArrayList!![i], savedNestedScrollWebViewStateArrayList!![i])
3976 // Reset the saved state variables.
3977 savedStateArrayList = null
3978 savedNestedScrollWebViewStateArrayList = null
3980 // Restore the selected tab position.
3981 if (savedTabPosition == 0) { // The first tab is selected.
3982 // Set the first page as the current WebView.
3983 setCurrentWebView(0)
3984 } else { // The first tab is not selected.
3985 // Create a handler move to the page.
3986 val setCurrentPageHandler = Handler(Looper.getMainLooper())
3988 // Create a runnable to move to the page.
3989 val setCurrentPageRunnable = Runnable {
3990 // Move to the page.
3991 webViewViewPager2.currentItem = savedTabPosition
3994 // Move to the page after 50 milliseconds, which should be enough time to for the WebView state adapter to populate the restored pages.
3995 setCurrentPageHandler.postDelayed(setCurrentPageRunnable, 50)
3998 // Get the intent that started the app.
4001 // Reset the intent. This prevents a duplicate tab from being created on restart.
4004 // Get the information from the intent.
4005 val intentAction = intent.action
4006 val intentUriData = intent.data
4007 val intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT)
4009 // Determine if this is a web search.
4010 val isWebSearch = (intentAction != null) && (intentAction == Intent.ACTION_WEB_SEARCH)
4012 // 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.
4013 if ((intentUriData != null) || (intentStringExtra != null) || isWebSearch) {
4014 // Get the URL string.
4015 val urlString = if (isWebSearch) { // The intent is a web search.
4016 // Sanitize the search input.
4017 val encodedSearchString: String = try {
4018 URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8")
4019 } catch (exception: UnsupportedEncodingException) {
4023 // Add the base search URL.
4024 searchURL + encodedSearchString
4025 } else { // The intent contains a URL formatted as a URI or a URL in the string extra.
4026 // Get the URL string.
4027 intentUriData?.toString() ?: intentStringExtra!!
4030 // Add a new tab if specified in the preferences.
4031 if (sharedPreferences.getBoolean(getString(R.string.open_intents_in_new_tab_key), true)) { // Load the URL in a new tab.
4032 // Set the loading new intent flag.
4033 loadingNewIntent = true
4036 addNewTab(urlString, true)
4037 } else { // Load the URL in the current tab.
4039 loadUrl(currentWebView!!, urlString)
4045 // Remove the warning that `OnTouchListener()` needs to override `performClick()`, as the only purpose of setting the `OnTouchListener()` is to make it do nothing.
4046 @SuppressLint("ClickableViewAccessibility")
4047 private fun initializeApp() {
4048 // Get a handle for the input method.
4049 val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
4051 // Initialize the color spans for highlighting the URLs.
4052 initialGrayColorSpan = ForegroundColorSpan(getColor(R.color.gray_500))
4053 finalGrayColorSpan = ForegroundColorSpan(getColor(R.color.gray_500))
4054 redColorSpan = ForegroundColorSpan(getColor(R.color.red_text))
4056 // Remove the formatting from the URL edit text when the user is editing the text.
4057 urlEditText.onFocusChangeListener = View.OnFocusChangeListener { _: View?, hasFocus: Boolean ->
4058 if (hasFocus) { // The user is editing the URL text box.
4059 // Remove the syntax highlighting.
4060 urlEditText.text.removeSpan(redColorSpan)
4061 urlEditText.text.removeSpan(initialGrayColorSpan)
4062 urlEditText.text.removeSpan(finalGrayColorSpan)
4063 } else { // The user has stopped editing the URL text box.
4064 // Move to the beginning of the string.
4065 urlEditText.setSelection(0)
4067 // Reapply the syntax highlighting.
4068 UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
4072 // Set the go button on the keyboard to load the URL in url text box.
4073 urlEditText.setOnKeyListener { _: View?, keyCode: Int, keyEvent: KeyEvent ->
4074 // If the event is a key-down event on the `enter` button, load the URL.
4075 if ((keyEvent.action == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The enter key was pressed.
4077 loadUrlFromTextBox()
4079 // Consume the event.
4080 return@setOnKeyListener true
4081 } else { // Some other key was pressed.
4082 // Do not consume the event.
4083 return@setOnKeyListener false
4087 // Create an Orbot status broadcast receiver.
4088 orbotStatusBroadcastReceiver = object : BroadcastReceiver() {
4089 override fun onReceive(context: Context, intent: Intent) {
4090 // Get the content of the status message.
4091 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS")!!
4093 // If Privacy Browser is waiting on the proxy, load the website now that Orbot is connected.
4094 if ((orbotStatus == ProxyHelper.ORBOT_STATUS_ON) && waitingForProxy) {
4095 // Reset the waiting for proxy status.
4096 waitingForProxy = false
4098 // Get a list of the current fragments.
4099 val fragmentList = supportFragmentManager.fragments
4101 // Check each fragment to see if it is a waiting for proxy dialog. Sometimes more than one is displayed.
4102 for (i in fragmentList.indices) {
4103 // Get the fragment tag.
4104 val fragmentTag = fragmentList[i].tag
4106 // Check to see if it is the waiting for proxy dialog.
4107 if (fragmentTag != null && fragmentTag == getString(R.string.waiting_for_proxy_dialog)) {
4108 // Dismiss the waiting for proxy dialog.
4109 (fragmentList[i] as DialogFragment).dismiss()
4113 // Reload existing URLs and load any URLs that are waiting for the proxy.
4114 for (i in 0 until webViewStateAdapter!!.itemCount) {
4115 // Get the WebView tab fragment.
4116 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
4118 // Get the fragment view.
4119 val fragmentView = webViewTabFragment.view
4121 // Only process the WebViews if they exist.
4122 if (fragmentView != null) {
4123 // Get the nested scroll WebView from the tab fragment.
4124 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
4126 // Get the waiting for proxy URL string.
4127 val waitingForProxyUrlString = nestedScrollWebView.waitingForProxyUrlString
4129 // Load the pending URL if it exists.
4130 if (waitingForProxyUrlString.isNotEmpty()) { // A URL is waiting to be loaded.
4132 loadUrl(nestedScrollWebView, waitingForProxyUrlString)
4134 // Reset the waiting for proxy URL string.
4135 nestedScrollWebView.waitingForProxyUrlString = ""
4136 } else { // No URL is waiting to be loaded.
4137 // Reload the existing URL.
4138 nestedScrollWebView.reload()
4146 // Register the Orbot status broadcast receiver.
4147 registerReceiver(orbotStatusBroadcastReceiver, IntentFilter("org.torproject.android.intent.action.STATUS"))
4149 // Get handles for views that need to be modified.
4150 val bookmarksHeaderLinearLayout = findViewById<LinearLayout>(R.id.bookmarks_header_linearlayout)
4151 val launchBookmarksActivityFab = findViewById<FloatingActionButton>(R.id.launch_bookmarks_activity_fab)
4152 val createBookmarkFolderFab = findViewById<FloatingActionButton>(R.id.create_bookmark_folder_fab)
4153 val createBookmarkFab = findViewById<FloatingActionButton>(R.id.create_bookmark_fab)
4155 // Update the WebView pager every time a tab is modified.
4156 webViewViewPager2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
4157 override fun onPageSelected(position: Int) {
4158 // Close the find on page bar if it is open.
4159 closeFindOnPage(null)
4161 // Set the current WebView.
4162 setCurrentWebView(position)
4164 // 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.
4165 if (tabLayout.selectedTabPosition != position) {
4166 // Wait until the new tab has been created.
4168 // Get a handle for the tab.
4169 val tab = tabLayout.getTabAt(position)!!
4178 // Handle tab selections.
4179 tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
4180 override fun onTabSelected(tab: TabLayout.Tab) {
4181 // Select the same page in the view pager.
4182 webViewViewPager2.currentItem = tab.position
4185 override fun onTabUnselected(tab: TabLayout.Tab) {}
4187 override fun onTabReselected(tab: TabLayout.Tab) {
4188 // Instantiate the View SSL Certificate dialog.
4189 val viewSslCertificateDialogFragment: DialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView!!.webViewFragmentId, currentWebView!!.getFavoriteIcon())
4191 // Display the View SSL Certificate dialog.
4192 viewSslCertificateDialogFragment.show(supportFragmentManager, getString(R.string.view_ssl_certificate))
4196 // Set a touch listener on the bookmarks header linear layout so that touches don't pass through to the button underneath.
4197 bookmarksHeaderLinearLayout.setOnTouchListener { _: View?, _: MotionEvent? -> true }
4199 // Set the launch bookmarks activity floating action button to launch the bookmarks activity.
4200 launchBookmarksActivityFab.setOnClickListener {
4201 // Get a copy of the favorite icon bitmap.
4202 val currentFavoriteIconBitmap = currentWebView!!.getFavoriteIcon()
4204 // Create a favorite icon byte array output stream.
4205 val currentFavoriteIconByteArrayOutputStream = ByteArrayOutputStream()
4207 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
4208 currentFavoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, currentFavoriteIconByteArrayOutputStream)
4210 // Convert the favorite icon byte array stream to a byte array.
4211 val currentFavoriteIconByteArray = currentFavoriteIconByteArrayOutputStream.toByteArray()
4213 // Create an intent to launch the bookmarks activity.
4214 val bookmarksIntent = Intent(applicationContext, BookmarksActivity::class.java)
4216 // Add the extra information to the intent.
4217 bookmarksIntent.putExtra(CURRENT_FOLDER_ID, currentBookmarksFolderId)
4218 bookmarksIntent.putExtra(CURRENT_TITLE, currentWebView!!.title)
4219 bookmarksIntent.putExtra(CURRENT_URL, currentWebView!!.url)
4220 bookmarksIntent.putExtra(CURRENT_FAVORITE_ICON_BYTE_ARRAY, currentFavoriteIconByteArray)
4223 startActivity(bookmarksIntent)
4226 // Set the create new bookmark folder floating action button to display an alert dialog.
4227 createBookmarkFolderFab.setOnClickListener {
4228 // Create a create bookmark folder dialog.
4229 val createBookmarkFolderDialog: DialogFragment = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView!!.getFavoriteIcon())
4231 // Show the create bookmark folder dialog.
4232 createBookmarkFolderDialog.show(supportFragmentManager, getString(R.string.create_folder))
4235 // Set the create new bookmark floating action button to display an alert dialog.
4236 createBookmarkFab.setOnClickListener {
4237 // Instantiate the create bookmark dialog.
4238 val createBookmarkDialog: DialogFragment = CreateBookmarkDialog.createBookmark(currentWebView!!.url!!, currentWebView!!.title!!, currentWebView!!.getFavoriteIcon())
4240 // Display the create bookmark dialog.
4241 createBookmarkDialog.show(supportFragmentManager, getString(R.string.create_bookmark))
4244 // Search for the string on the page whenever a character changes in the find on page edit text.
4245 findOnPageEditText.addTextChangedListener(object : TextWatcher {
4246 override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
4248 override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
4250 override fun afterTextChanged(s: Editable) {
4251 // 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.
4252 currentWebView?.findAllAsync(findOnPageEditText.text.toString())
4256 // Set the `check mark` button for the find on page edit text keyboard to close the soft keyboard.
4257 findOnPageEditText.setOnKeyListener { _: View?, keyCode: Int, keyEvent: KeyEvent ->
4258 if ((keyEvent.action == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
4259 // Hide the soft keyboard.
4260 inputMethodManager.hideSoftInputFromWindow(currentWebView!!.windowToken, 0)
4262 // Consume the event.
4263 return@setOnKeyListener true
4264 } else { // A different key was pressed.
4265 // Do not consume the event.
4266 return@setOnKeyListener false
4270 // Implement swipe to refresh.
4271 swipeRefreshLayout.setOnRefreshListener {
4272 // Reload the website.
4273 currentWebView!!.reload()
4276 // Store the default progress view offsets.
4277 defaultProgressViewStartOffset = swipeRefreshLayout.progressViewStartOffset
4278 defaultProgressViewEndOffset = swipeRefreshLayout.progressViewEndOffset
4280 // Set the refresh color scheme according to the theme.
4281 swipeRefreshLayout.setColorSchemeResources(R.color.blue_text)
4283 // Initialize a color background typed value.
4284 val colorBackgroundTypedValue = TypedValue()
4286 // Get the color background from the theme.
4287 theme.resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true)
4289 // Get the color background int from the typed value.
4290 val colorBackgroundInt = colorBackgroundTypedValue.data
4292 // Set the swipe refresh background color.
4293 swipeRefreshLayout.setProgressBackgroundColorSchemeColor(colorBackgroundInt)
4295 // Set the drawer titles, which identify the drawer layouts in accessibility mode.
4296 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer))
4297 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks))
4299 // Load the bookmarks folder.
4300 loadBookmarksFolder()
4302 // Handle clicks on bookmarks.
4303 bookmarksListView.onItemClickListener = AdapterView.OnItemClickListener { _: AdapterView<*>?, _: View?, _: Int, id: Long ->
4304 // Convert the id from long to int to match the format of the bookmarks database.
4305 val databaseId = id.toInt()
4307 // Get the bookmark cursor for this ID.
4308 val bookmarkCursor = bookmarksDatabaseHelper!!.getBookmark(databaseId)
4310 // Move the bookmark cursor to the first row.
4311 bookmarkCursor.moveToFirst()
4313 // Act upon the bookmark according to the type.
4314 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndexOrThrow(IS_FOLDER)) == 1) { // The selected bookmark is a folder.
4315 // Store the folder ID.
4316 currentBookmarksFolderId = bookmarkCursor.getLong(bookmarkCursor.getColumnIndexOrThrow(FOLDER_ID))
4318 // Load the new folder.
4319 loadBookmarksFolder()
4320 } else { // The selected bookmark is not a folder.
4321 // Load the bookmark URL.
4322 loadUrl(currentWebView!!, bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BOOKMARK_URL)))
4324 // Close the bookmarks drawer if it is not pinned.
4325 if (!bookmarksDrawerPinned)
4326 drawerLayout.closeDrawer(GravityCompat.END)
4329 // Close the cursor.
4330 bookmarkCursor.close()
4333 // Handle long-presses on bookmarks.
4334 bookmarksListView.onItemLongClickListener = AdapterView.OnItemLongClickListener { _: AdapterView<*>?, _: View?, _: Int, id: Long ->
4335 // Convert the database ID from `long` to `int`.
4336 val databaseId = id.toInt()
4338 // Run the commands associated with the type.
4339 if (bookmarksDatabaseHelper!!.isFolder(databaseId)) { // The bookmark is a folder.
4340 // Get the folder ID.
4341 val folderId = bookmarksDatabaseHelper!!.getFolderId(databaseId)
4343 // Get a cursor of all the bookmarks in the folder.
4344 val bookmarksCursor = bookmarksDatabaseHelper!!.getFolderBookmarks(folderId)
4346 // Move to the first entry in the cursor.
4347 bookmarksCursor.moveToFirst()
4349 // Open each bookmark
4350 for (i in 0 until bookmarksCursor.count) {
4351 // Load the bookmark in a new tab, moving to the tab for the first bookmark if the drawer is not pinned.
4352 addNewTab(bookmarksCursor.getString(bookmarksCursor.getColumnIndexOrThrow(BOOKMARK_URL)), !bookmarksDrawerPinned && (i == 0))
4354 // Move to the next bookmark.
4355 bookmarksCursor.moveToNext()
4358 // Close the cursor.
4359 bookmarksCursor.close()
4360 } else { // The bookmark is not a folder.
4361 // Get the bookmark cursor for this ID.
4362 val bookmarkCursor = bookmarksDatabaseHelper!!.getBookmark(databaseId)
4364 // Move the bookmark cursor to the first row.
4365 bookmarkCursor.moveToFirst()
4367 // Load the bookmark in a new tab and move to the tab if the drawer is not pinned.
4368 addNewTab(bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BOOKMARK_URL)), !bookmarksDrawerPinned)
4370 // Close the cursor.
4371 bookmarkCursor.close()
4374 // Close the bookmarks drawer if it is not pinned.
4375 if (!bookmarksDrawerPinned)
4376 drawerLayout.closeDrawer(GravityCompat.END)
4378 // Consume the event.
4382 // The drawer listener is used to update the navigation menu.
4383 drawerLayout.addDrawerListener(object : DrawerLayout.DrawerListener {
4384 override fun onDrawerSlide(drawerView: View, slideOffset: Float) {}
4386 override fun onDrawerOpened(drawerView: View) {}
4388 override fun onDrawerClosed(drawerView: View) {
4389 // Reset the drawer icon when the drawer is closed. Otherwise, it remains an arrow if the drawer is open when the app is restarted.
4390 actionBarDrawerToggle!!.syncState()
4393 override fun onDrawerStateChanged(newState: Int) {
4394 if (newState == DrawerLayout.STATE_SETTLING || newState == DrawerLayout.STATE_DRAGGING) { // A drawer is opening or closing.
4395 // Update the navigation menu items if the WebView is not null.
4396 if (currentWebView != null) {
4397 navigationBackMenuItem.isEnabled = currentWebView!!.canGoBack()
4398 navigationForwardMenuItem.isEnabled = currentWebView!!.canGoForward()
4399 navigationHistoryMenuItem.isEnabled = currentWebView!!.canGoBack() || currentWebView!!.canGoForward()
4400 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + currentWebView!!.getRequestsCount(BLOCKED_REQUESTS)
4402 // Hide the keyboard (if displayed).
4403 inputMethodManager.hideSoftInputFromWindow(currentWebView!!.windowToken, 0)
4406 // 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.
4407 urlEditText.clearFocus()
4409 // 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.
4410 // Clearing the focus from the WebView removes any text selection markers and context menus, which otherwise draw above the open drawers.
4411 currentWebView?.clearFocus()
4416 // Inflate a bare WebView to get the default user agent. It is not used to render content on the screen.
4417 @SuppressLint("InflateParams") val webViewLayout = layoutInflater.inflate(R.layout.bare_webview, null, false)
4419 // Get a handle for the WebView.
4420 val bareWebView = webViewLayout.findViewById<WebView>(R.id.bare_webview)
4422 // Store the default user agent.
4423 webViewDefaultUserAgent = bareWebView.settings.userAgentString
4425 // Destroy the bare WebView.
4426 bareWebView.destroy()
4428 // Update the domains settings set.
4429 updateDomainsSettingsSet()
4431 // Instantiate the check filter list helper.
4432 checkFilterListHelper = CheckFilterListHelper()
4435 @SuppressLint("ClickableViewAccessibility")
4436 override fun initializeWebView(nestedScrollWebView: NestedScrollWebView, pageNumber: Int, progressBar: ProgressBar, urlString: String, restoringState: Boolean) {
4437 // Get the WebView theme.
4438 val webViewTheme = sharedPreferences.getString(getString(R.string.webview_theme_key), getString(R.string.webview_theme_default_value))
4440 // Get the WebView theme entry values string array.
4441 val webViewThemeEntryValuesStringArray = resources.getStringArray(R.array.webview_theme_entry_values)
4443 // Set the WebView theme if algorithmic darkening is supported.
4444 if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {
4445 // Set the WebView them. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
4446 if (webViewTheme == webViewThemeEntryValuesStringArray[1]) { // The light theme is selected.
4447 // Turn off algorithmic darkening.
4448 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
4450 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
4451 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
4452 nestedScrollWebView.visibility = View.VISIBLE
4453 } else if (webViewTheme == webViewThemeEntryValuesStringArray[2]) { // The dark theme is selected.
4454 // Turn on algorithmic darkening.
4455 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
4456 } else { // The system default theme is selected.
4457 // Get the current theme status.
4458 val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
4460 // Set the algorithmic darkening according to the current system theme status.
4461 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) { // The system is in day mode.
4462 // Turn off algorithmic darkening.
4463 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
4465 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
4466 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
4467 nestedScrollWebView.visibility = View.VISIBLE
4468 } else { // The system is in night mode.
4469 // Turn on algorithmic darkening.
4470 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
4475 // Get a handle for the input method manager.
4476 val inputMethodManager = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
4478 // Set the app bar scrolling.
4479 nestedScrollWebView.isNestedScrollingEnabled = scrollAppBar
4481 // Allow pinch to zoom.
4482 nestedScrollWebView.settings.builtInZoomControls = true
4484 // Hide zoom controls.
4485 nestedScrollWebView.settings.displayZoomControls = false
4487 // Don't allow mixed content (HTTP and HTTPS) on the same website.
4488 nestedScrollWebView.settings.mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW
4490 // Set the WebView to load in overview mode (zoomed out to the maximum width).
4491 nestedScrollWebView.settings.loadWithOverviewMode = true
4493 // Explicitly disable geolocation.
4494 nestedScrollWebView.settings.setGeolocationEnabled(false)
4496 // Allow loading of file:// URLs. This is necessary for opening MHT web archives, which are copied into a temporary cache location.
4497 nestedScrollWebView.settings.allowFileAccess = true
4499 // Create a double-tap gesture detector to toggle full-screen mode.
4500 val doubleTapGestureDetector = GestureDetector(this, object : GestureDetector.SimpleOnGestureListener() {
4501 // Override `onDoubleTap()`. All other events are handled using the default settings.
4502 override fun onDoubleTap(motionEvent: MotionEvent): Boolean {
4503 return if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
4504 // Toggle the full screen browsing mode tracker.
4505 inFullScreenBrowsingMode = !inFullScreenBrowsingMode
4507 // Toggle the full screen browsing mode.
4508 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
4509 // Hide the app bar if specified.
4510 if (hideAppBar) { // App bar hiding is enabled.
4511 // Close the find on page bar if it is visible.
4512 closeFindOnPage(null)
4514 // Hide the tab linear layout.
4515 tabsLinearLayout.visibility = View.GONE
4517 // Hide the app bar.
4520 // Set layout and scrolling parameters according to the position of the app bar.
4521 if (bottomAppBar) { // The app bar is at the bottom.
4522 // Reset the WebView padding to fill the available space.
4523 swipeRefreshLayout.setPadding(0, 0, 0, 0)
4524 } else { // The app bar is at the top.
4525 // Check to see if the app bar is normally scrolled.
4526 if (scrollAppBar) { // The app bar is scrolled when it is displayed.
4527 // Get the swipe refresh layout parameters.
4528 val swipeRefreshLayoutParams = swipeRefreshLayout.layoutParams as CoordinatorLayout.LayoutParams
4530 // Remove the off-screen scrolling layout.
4531 swipeRefreshLayoutParams.behavior = null
4532 } else { // The app bar is not scrolled when it is displayed.
4533 // Remove the padding from the top of the swipe refresh layout.
4534 swipeRefreshLayout.setPadding(0, 0, 0, 0)
4536 // The swipe refresh circle must be moved above the now removed status bar location.
4537 swipeRefreshLayout.setProgressViewOffset(false, -200, defaultProgressViewEndOffset)
4540 } else { // App bar hiding is not enabled.
4541 // Adjust the UI for the bottom app bar.
4543 // Adjust the UI according to the scrolling of the app bar.
4545 // Reset the WebView padding to fill the available space.
4546 swipeRefreshLayout.setPadding(0, 0, 0, 0)
4548 // Move the WebView above the app bar layout.
4549 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
4554 /* Hide the system bars.
4555 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4556 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4557 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4558 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4561 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4562 @Suppress("DEPRECATION")
4563 rootFrameLayout.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
4564 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
4565 } else { // Switch to normal viewing mode.
4566 // Show the app bar if it was hidden.
4568 // Show the tab linear layout.
4569 tabsLinearLayout.visibility = View.VISIBLE
4571 // Show the app bar.
4575 // Set layout and scrolling parameters according to the position of the app bar.
4576 if (bottomAppBar) { // The app bar is at the bottom.
4579 // Reset the WebView padding to fill the available space.
4580 swipeRefreshLayout.setPadding(0, 0, 0, 0)
4582 // Move the WebView above the app bar layout.
4583 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
4585 } else { // The app bar is at the top.
4586 // Check to see if the app bar is normally scrolled.
4587 if (scrollAppBar) { // The app bar is scrolled when it is displayed.
4588 // Get the swipe refresh layout parameters.
4589 val swipeRefreshLayoutParams = swipeRefreshLayout.layoutParams as CoordinatorLayout.LayoutParams
4591 // Add the off-screen scrolling layout.
4592 swipeRefreshLayoutParams.behavior = AppBarLayout.ScrollingViewBehavior()
4593 } else { // The app bar is not scrolled when it is displayed.
4594 // The swipe refresh layout must be manually moved below the app bar layout.
4595 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0)
4597 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
4598 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight)
4602 // Remove the `SYSTEM_UI` flags from the root frame layout. The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4603 @Suppress("DEPRECATION")
4604 rootFrameLayout.systemUiVisibility = 0
4607 // Consume the double-tap.
4609 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
4615 override fun onFling(motionEvent1: MotionEvent, motionEvent2: MotionEvent, velocityX: Float, velocityY: Float): Boolean {
4616 // Scroll the bottom app bar if enabled.
4617 if (bottomAppBar && scrollAppBar && !objectAnimator.isRunning) {
4618 // Calculate the Y change.
4619 val motionY = motionEvent2.y - motionEvent1.y
4621 // Scroll the app bar if the change is greater than 50 pixels.
4623 // Animate the bottom app bar onto the screen.
4624 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0f)
4625 } else if (motionY < -50) {
4626 // Animate the bottom app bar off the screen.
4627 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", appBarLayout.height.toFloat())
4631 objectAnimator.start()
4634 // Do not consume the event.
4639 // Pass all touch events on the WebView through the double-tap gesture detector.
4640 nestedScrollWebView.setOnTouchListener { view: View, motionEvent: MotionEvent? ->
4641 // Call `performClick()` on the view, which is required for accessibility.
4644 // Check for double-taps.
4645 doubleTapGestureDetector.onTouchEvent(motionEvent!!)
4648 // Register the WebView for a context menu. This is used to see link targets and download images.
4649 registerForContextMenu(nestedScrollWebView)
4651 // Allow the downloading of files.
4652 nestedScrollWebView.setDownloadListener { downloadUrlString: String?, userAgent: String?, contentDisposition: String?, mimetype: String?, contentLength: Long ->
4653 // Check the download preference.
4654 if (downloadWithExternalApp) { // Download with an external app.
4655 downloadUrlWithExternalApp(downloadUrlString!!)
4656 } else { // Handle the download inside of Privacy Browser.
4657 // Define a formatted file size string.
4659 // Process the content length if it contains data.
4660 val formattedFileSizeString = if (contentLength > 0) { // The content length is greater than 0.
4661 // Format the content length as a string.
4662 NumberFormat.getInstance().format(contentLength) + " " + getString(R.string.bytes)
4663 } else { // The content length is not greater than 0.
4664 // Set the formatted file size string to be `unknown size`.
4665 getString(R.string.unknown_size)
4668 // Get the file name from the content disposition.
4669 val fileNameString = UrlHelper.getFileName(this, contentDisposition, mimetype, downloadUrlString!!)
4671 // Instantiate the save dialog.
4672 val saveDialogFragment = SaveDialog.saveUrl(downloadUrlString, fileNameString, formattedFileSizeString, userAgent!!, nestedScrollWebView.acceptCookies)
4674 // 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.
4676 // Show the save dialog.
4677 saveDialogFragment.show(supportFragmentManager, getString(R.string.save_dialog))
4678 } catch (exception: Exception) { // The dialog could not be shown.
4679 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
4680 pendingDialogsArrayList.add(PendingDialogDataClass(saveDialogFragment, getString(R.string.save_dialog)))
4685 // Update the find on page count.
4686 nestedScrollWebView.setFindListener { activeMatchOrdinal, numberOfMatches, isDoneCounting ->
4687 if (isDoneCounting && (numberOfMatches == 0)) { // There are no matches.
4688 // Set the find on page count text view to be `0/0`.
4689 findOnPageCountTextView.setText(R.string.zero_of_zero)
4690 } else if (isDoneCounting) { // There are matches.
4691 // The active match ordinal is zero-based.
4692 val activeMatch = activeMatchOrdinal + 1
4694 // Build the match string.
4695 val matchString = "$activeMatch/$numberOfMatches"
4697 // Update the find on page count text view.
4698 findOnPageCountTextView.text = matchString
4702 // Process scroll changes.
4703 nestedScrollWebView.setOnScrollChangeListener { _: View?, _: Int, _: Int, _: Int, _: Int ->
4704 // Set the swipe to refresh status.
4705 if (nestedScrollWebView.swipeToRefresh) // Only enable swipe to refresh if the WebView is scrolled to the top.
4706 swipeRefreshLayout.isEnabled = nestedScrollWebView.scrollY == 0
4707 else // Disable swipe to refresh.
4708 swipeRefreshLayout.isEnabled = false
4710 // Reinforce the system UI visibility flags if in full screen browsing mode.
4711 // This hides the status and navigation bars, which are displayed if other elements are shown, like dialog boxes, the options menu, or the keyboard.
4712 if (inFullScreenBrowsingMode) {
4713 /* Hide the system bars.
4714 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4715 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4716 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4717 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4720 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4721 @Suppress("DEPRECATION")
4722 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
4726 // Set the web chrome client.
4727 nestedScrollWebView.webChromeClient = object : WebChromeClient() {
4728 // Update the progress bar when a page is loading.
4729 override fun onProgressChanged(view: WebView, progress: Int) {
4730 // Update the progress bar.
4731 progressBar.progress = progress
4733 // Set the visibility of the progress bar.
4734 if (progress < 100) {
4735 // Show the progress bar.
4736 progressBar.visibility = View.VISIBLE
4738 // Hide the progress bar.
4739 progressBar.visibility = View.GONE
4741 //Stop the swipe to refresh indicator if it is running
4742 swipeRefreshLayout.isRefreshing = false
4744 // 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.
4745 nestedScrollWebView.visibility = View.VISIBLE
4749 // Set the favorite icon when it changes.
4750 override fun onReceivedIcon(view: WebView, icon: Bitmap) {
4751 // 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.
4752 // This prevents low resolution icons from replacing high resolution one.
4753 // The check for the visibility of the progress bar can possibly be removed once https://redmine.stoutner.com/issues/747 is fixed.
4754 if ((progressBar.visibility == View.GONE) && (icon.height > nestedScrollWebView.getFavoriteIconHeight())) {
4755 // Store the new favorite icon.
4756 nestedScrollWebView.setFavoriteIcon(icon)
4758 // Get the current page position.
4759 val currentPosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
4761 // Get the current tab.
4762 val tab = tabLayout.getTabAt(currentPosition)
4764 // Check to see if the tab has been populated.
4766 // Get the custom view from the tab.
4767 val tabView = tab.customView
4769 // Check to see if the custom tab view has been populated.
4770 if (tabView != null) {
4771 // Get the favorite icon image view from the tab.
4772 val tabFavoriteIconImageView = tabView.findViewById<ImageView>(R.id.favorite_icon_imageview)
4774 // Display the favorite icon in the tab.
4775 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true))
4781 // Save a copy of the title when it changes.
4782 override fun onReceivedTitle(view: WebView, title: String) {
4783 // Get the current page position.
4784 val currentPosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
4786 // Get the current tab.
4787 val tab = tabLayout.getTabAt(currentPosition)
4789 // Only populate the title text view if the tab has been fully created.
4791 // Get the custom view from the tab.
4792 val tabView = tab.customView
4794 // Only populate the title text view if the tab view has been fully populated.
4795 if (tabView != null) {
4796 // Get the title text view from the tab.
4797 val tabTitleTextView = tabView.findViewById<TextView>(R.id.title_textview)
4799 // Set the title according to the URL.
4800 if (title == "about:blank") {
4801 // Set the title to indicate a new tab.
4802 tabTitleTextView.setText(R.string.new_tab)
4804 // Set the title as the tab text.
4805 tabTitleTextView.text = title
4811 // Enter full screen video.
4812 override fun onShowCustomView(video: View, callback: CustomViewCallback) {
4813 // Set the full screen video flag.
4814 displayingFullScreenVideo = true
4816 // Hide the keyboard.
4817 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.windowToken, 0)
4819 // Hide the coordinator layout.
4820 coordinatorLayout.visibility = View.GONE
4822 /* Hide the system bars.
4823 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4824 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4825 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4826 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4829 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4830 @Suppress("DEPRECATION")
4831 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
4833 // Disable the sliding drawers.
4834 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
4836 // Add the video view to the full screen video frame layout.
4837 fullScreenVideoFrameLayout.addView(video)
4839 // Show the full screen video frame layout.
4840 fullScreenVideoFrameLayout.visibility = View.VISIBLE
4842 // Disable the screen timeout while the video is playing. YouTube does this automatically, but not all other videos do.
4843 fullScreenVideoFrameLayout.keepScreenOn = true
4846 // Exit full screen video.
4847 override fun onHideCustomView() {
4848 // Exit the full screen video.
4849 exitFullScreenVideo()
4853 override fun onShowFileChooser(webView: WebView, filePathCallback: ValueCallback<Array<Uri>>, fileChooserParams: FileChooserParams): Boolean {
4854 // Store the file path callback.
4855 fileChooserCallback = filePathCallback
4857 // Create an intent to open a chooser based on the file chooser parameters.
4858 val fileChooserIntent = fileChooserParams.createIntent()
4860 // Check to see if the file chooser intent resolves to an installed package.
4861 if (fileChooserIntent.resolveActivity(packageManager) != null) { // The file chooser intent is fine.
4862 // Launch the file chooser intent.
4863 browseFileUploadActivityResultLauncher.launch(fileChooserIntent)
4864 } else { // The file chooser intent will cause a crash.
4865 // Create a generic intent to open a chooser.
4866 val genericFileChooserIntent = Intent(Intent.ACTION_GET_CONTENT)
4868 // Request an openable file.
4869 genericFileChooserIntent.addCategory(Intent.CATEGORY_OPENABLE)
4871 // Set the file type to everything.
4872 genericFileChooserIntent.type = "*/*"
4874 // Launch the generic file chooser intent.
4875 browseFileUploadActivityResultLauncher.launch(genericFileChooserIntent)
4878 // Handle the event.
4882 nestedScrollWebView.webViewClient = object : WebViewClient() {
4883 // `shouldOverrideUrlLoading` makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
4884 override fun shouldOverrideUrlLoading(view: WebView, webResourceRequest: WebResourceRequest): Boolean {
4885 // Get the URL from the web resource request.
4886 var requestUrlString = webResourceRequest.url.toString()
4888 // Sanitize the url.
4889 requestUrlString = sanitizeUrl(requestUrlString)
4891 // Handle the URL according to the type.
4892 return if (requestUrlString.startsWith("http")) { // Load the URL in Privacy Browser.
4893 // Load the URL. By using `loadUrl()`, instead of `loadUrlFromBase()`, the Referer header will never be sent.
4894 loadUrl(nestedScrollWebView, requestUrlString)
4896 // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
4897 // Custom headers cannot be added if false is returned and the WebView handles the loading of the URL.
4899 } else if (requestUrlString.startsWith("mailto:")) { // Load the email address in an external email program.
4900 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
4901 val emailIntent = Intent(Intent.ACTION_SENDTO)
4903 // Parse the url and set it as the data for the intent.
4904 emailIntent.data = Uri.parse(requestUrlString)
4906 // Open the email program in a new task instead of as part of Privacy Browser.
4907 emailIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
4911 startActivity(emailIntent)
4912 } catch (exception: ActivityNotFoundException) {
4913 // Display a snackbar.
4914 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
4917 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
4919 } else if (requestUrlString.startsWith("tel:")) { // Load the phone number in the dialer.
4920 // Create a dial intent.
4921 val dialIntent = Intent(Intent.ACTION_DIAL)
4923 // Add the phone number to the intent.
4924 dialIntent.data = Uri.parse(requestUrlString)
4926 // Open the dialer in a new task instead of as part of Privacy Browser.
4927 dialIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
4931 startActivity(dialIntent)
4932 } catch (exception: ActivityNotFoundException) {
4933 // Display a snackbar.
4934 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
4937 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
4939 } else { // Load a system chooser to select an app that can handle the URL.
4940 // Create a generic intent to open an app.
4941 val genericIntent = Intent(Intent.ACTION_VIEW)
4943 // Add the URL to the intent.
4944 genericIntent.data = Uri.parse(requestUrlString)
4946 // List all apps that can handle the URL instead of just opening the first one.
4947 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE)
4949 // Open the app in a new task instead of as part of Privacy Browser.
4950 genericIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
4954 startActivity(genericIntent)
4955 } catch (exception: ActivityNotFoundException) {
4956 // Display a snackbar.
4957 Snackbar.make(nestedScrollWebView, getString(R.string.unrecognized_url, requestUrlString), Snackbar.LENGTH_SHORT).show()
4960 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
4965 // Check requests against the block lists.
4966 override fun shouldInterceptRequest(view: WebView, webResourceRequest: WebResourceRequest): WebResourceResponse? {
4968 val requestUrlString = webResourceRequest.url.toString()
4970 // Check to see if the resource request is for the main URL.
4971 if (requestUrlString == nestedScrollWebView.currentUrl) {
4972 // `return null` loads the resource request, which should never be blocked if it is the main URL.
4976 // 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.
4977 while (ultraPrivacy == null) {
4979 // Check to see if the filter lists have been populated after 100 ms.
4981 } catch (exception: InterruptedException) {
4986 // Create an empty web resource response to be used if the resource request is blocked.
4987 val emptyWebResourceResponse = WebResourceResponse("text/plain", "utf8", ByteArrayInputStream("".toByteArray()))
4989 // Initialize the variables.
4990 var allowListResultStringArray: Array<String>? = null
4991 var isThirdPartyRequest = false
4993 // Get the current URL. `.getUrl()` throws an error because operations on the WebView cannot be made from this thread.
4994 var currentBaseDomain = nestedScrollWebView.currentDomainName
4996 // Store a copy of the current domain for use in later requests.
4997 val currentDomain = currentBaseDomain
4999 // Get the request host name.
5000 var requestBaseDomain = webResourceRequest.url.host
5002 // Only check for third-party requests if the current base domain is not empty and the request domain is not null.
5003 if (currentBaseDomain.isNotEmpty() && (requestBaseDomain != null)) {
5004 // Determine the current base domain.
5005 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5006 // Remove the first subdomain.
5007 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1)
5010 // Determine the request base domain.
5011 while (requestBaseDomain!!.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5012 // Remove the first subdomain.
5013 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1)
5016 // Update the third party request tracker.
5017 isThirdPartyRequest = currentBaseDomain != requestBaseDomain
5020 // Get the current WebView page position.
5021 val webViewPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
5023 // Determine if the WebView is currently displayed.
5024 val webViewDisplayed = (webViewPagePosition == tabLayout.selectedTabPosition)
5026 // Block third-party requests if enabled.
5027 if (isThirdPartyRequest && nestedScrollWebView.blockAllThirdPartyRequests) {
5028 // Add the result to the resource requests.
5029 nestedScrollWebView.addResourceRequest(arrayOf(REQUEST_THIRD_PARTY, requestUrlString))
5031 // Increment the blocked requests counters.
5032 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5033 nestedScrollWebView.incrementRequestsCount(THIRD_PARTY_REQUESTS)
5035 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5036 if (webViewDisplayed) {
5037 // Updating the UI must be run from the UI thread.
5039 // Update the menu item titles.
5040 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5042 // Update the options menu if it has been populated.
5043 if (optionsMenu != null) {
5044 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5045 optionsBlockAllThirdPartyRequestsMenuItem.title =
5046 nestedScrollWebView.getRequestsCount(THIRD_PARTY_REQUESTS).toString() + " - " + getString(R.string.block_all_third_party_requests)
5051 // The resource request was blocked. Return an empty web resource response.
5052 return emptyWebResourceResponse
5055 // Check UltraList if it is enabled.
5056 if (nestedScrollWebView.ultraListEnabled) {
5057 // Check the URL against UltraList.
5058 val ultraListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, ultraList)
5060 // Process the UltraList results.
5061 if (ultraListResults[0] == REQUEST_BLOCKED) { // The resource request matched UltraList's block list.
5062 // Add the result to the resource requests.
5063 nestedScrollWebView.addResourceRequest(arrayOf(ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]))
5065 // Increment the blocked requests counters.
5066 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5067 nestedScrollWebView.incrementRequestsCount(com.stoutner.privacybrowser.views.ULTRALIST)
5069 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5070 if (webViewDisplayed) {
5071 // Updating the UI must be run from the UI thread.
5073 // Update the menu item titles.
5074 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5076 // Update the options menu if it has been populated.
5077 if (optionsMenu != null) {
5078 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5079 optionsUltraListMenuItem.title = nestedScrollWebView.getRequestsCount(com.stoutner.privacybrowser.views.ULTRALIST).toString() + " - " + getString(R.string.ultralist)
5084 // The resource request was blocked. Return an empty web resource response.
5085 return emptyWebResourceResponse
5086 } else if (ultraListResults[0] == REQUEST_ALLOWED) { // The resource request matched UltraList's allow list.
5087 // Add an allow list entry to the resource requests array.
5088 nestedScrollWebView.addResourceRequest(arrayOf(ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]))
5090 // The resource request has been allowed by UltraList. `return null` loads the requested resource.
5095 // Check UltraPrivacy if it is enabled.
5096 if (nestedScrollWebView.ultraPrivacyEnabled) {
5097 // Check the URL against UltraPrivacy.
5098 val ultraPrivacyResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, ultraPrivacy!!)
5100 // Process the UltraPrivacy results.
5101 if (ultraPrivacyResults[0] == REQUEST_BLOCKED) { // The resource request matched UltraPrivacy's block list.
5102 // Add the result to the resource requests.
5103 nestedScrollWebView.addResourceRequest(arrayOf(ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5104 ultraPrivacyResults[5]))
5106 // Increment the blocked requests counters.
5107 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5108 nestedScrollWebView.incrementRequestsCount(ULTRAPRIVACY)
5110 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5111 if (webViewDisplayed) {
5112 // Updating the UI must be run from the UI thread.
5114 // Update the menu item titles.
5115 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5117 // Update the options menu if it has been populated.
5118 if (optionsMenu != null) {
5119 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5120 optionsUltraPrivacyMenuItem.title = nestedScrollWebView.getRequestsCount(ULTRAPRIVACY).toString() + " - " + getString(R.string.ultraprivacy)
5125 // The resource request was blocked. Return an empty web resource response.
5126 return emptyWebResourceResponse
5127 } else if (ultraPrivacyResults[0] == REQUEST_ALLOWED) { // The resource request matched UltraPrivacy's allow list.
5128 // Add an allow list entry to the resource requests array.
5129 nestedScrollWebView.addResourceRequest(arrayOf(ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5130 ultraPrivacyResults[5]))
5132 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
5137 // Check EasyList if it is enabled.
5138 if (nestedScrollWebView.easyListEnabled) {
5139 // Check the URL against EasyList.
5140 val easyListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, easyList)
5142 // Process the EasyList results.
5143 if (easyListResults[0] == REQUEST_BLOCKED) { // The resource request matched EasyList's block list.
5144 // Add the result to the resource requests.
5145 nestedScrollWebView.addResourceRequest(arrayOf(easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]))
5147 // Increment the blocked requests counters.
5148 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5149 nestedScrollWebView.incrementRequestsCount(EASYLIST)
5151 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5152 if (webViewDisplayed) {
5153 // Updating the UI must be run from the UI thread.
5155 // Update the menu item titles.
5156 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5158 // Update the options menu if it has been populated.
5159 if (optionsMenu != null) {
5160 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5161 optionsEasyListMenuItem.title = nestedScrollWebView.getRequestsCount(EASYLIST).toString() + " - " + getString(R.string.easylist)
5166 // The resource request was blocked. Return an empty web resource response.
5167 return emptyWebResourceResponse
5168 } else if (easyListResults[0] == REQUEST_ALLOWED) { // The resource request matched EasyList's allow list.
5169 // Update the allow list result string array tracker.
5170 allowListResultStringArray = arrayOf(easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5])
5174 // Check EasyPrivacy if it is enabled.
5175 if (nestedScrollWebView.easyPrivacyEnabled) {
5176 // Check the URL against EasyPrivacy.
5177 val easyPrivacyResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, easyPrivacy)
5179 // Process the EasyPrivacy results.
5180 if (easyPrivacyResults[0] == REQUEST_BLOCKED) { // The resource request matched EasyPrivacy's block list.
5181 // Add the result to the resource requests.
5182 nestedScrollWebView.addResourceRequest(arrayOf(easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5]))
5184 // Increment the blocked requests counters.
5185 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5186 nestedScrollWebView.incrementRequestsCount(EASYPRIVACY)
5188 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5189 if (webViewDisplayed) {
5190 // Updating the UI must be run from the UI thread.
5192 // Update the menu item titles.
5193 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5195 // Update the options menu if it has been populated.
5196 if (optionsMenu != null) {
5197 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5198 optionsEasyPrivacyMenuItem.title = nestedScrollWebView.getRequestsCount(EASYPRIVACY).toString() + " - " + getString(R.string.easyprivacy)
5203 // The resource request was blocked. Return an empty web resource response.
5204 return emptyWebResourceResponse
5205 } else if (easyPrivacyResults[0] == REQUEST_ALLOWED) { // The resource request matched EasyPrivacy's allow list.
5206 // Update the allow list result string array tracker.
5207 allowListResultStringArray = arrayOf(easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5])
5211 // Check Fanboy’s Annoyance List if it is enabled.
5212 if (nestedScrollWebView.fanboysAnnoyanceListEnabled) {
5213 // Check the URL against Fanboy's Annoyance List.
5214 val fanboysAnnoyanceListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, fanboysAnnoyanceList)
5216 // Process the Fanboy's Annoyance List results.
5217 if (fanboysAnnoyanceListResults[0] == REQUEST_BLOCKED) { // The resource request matched Fanboy's Annoyance List's block list.
5218 // Add the result to the resource requests.
5219 nestedScrollWebView.addResourceRequest(arrayOf(fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5220 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]))
5222 // Increment the blocked requests counters.
5223 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5224 nestedScrollWebView.incrementRequestsCount(FANBOYS_ANNOYANCE_LIST)
5226 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5227 if (webViewDisplayed) {
5228 // Updating the UI must be run from the UI thread.
5230 // Update the menu item titles.
5231 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5233 // Update the options menu if it has been populated.
5234 if (optionsMenu != null) {
5235 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5236 optionsFanboysAnnoyanceListMenuItem.title = nestedScrollWebView.getRequestsCount(FANBOYS_ANNOYANCE_LIST).toString() + " - " + getString(R.string.fanboys_annoyance_list)
5241 // The resource request was blocked. Return an empty web resource response.
5242 return emptyWebResourceResponse
5243 } else if (fanboysAnnoyanceListResults[0] == REQUEST_ALLOWED) { // The resource request matched Fanboy's Annoyance List's allow list.
5244 // Update the allow list result string array tracker.
5245 allowListResultStringArray = arrayOf(fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5246 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5])
5248 } else if (nestedScrollWebView.fanboysSocialBlockingListEnabled) { // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
5249 // Check the URL against Fanboy's Annoyance List.
5250 val fanboysSocialListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, fanboysSocialList)
5252 // Process the Fanboy's Social Blocking List results.
5253 if (fanboysSocialListResults[0] == REQUEST_BLOCKED) { // The resource request matched Fanboy's Social Blocking List's block list.
5254 // Add the result to the resource requests.
5255 nestedScrollWebView.addResourceRequest(arrayOf(fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5256 fanboysSocialListResults[4], fanboysSocialListResults[5]))
5258 // Increment the blocked requests counters.
5259 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5260 nestedScrollWebView.incrementRequestsCount(FANBOYS_SOCIAL_BLOCKING_LIST)
5262 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5263 if (webViewDisplayed) {
5264 // Updating the UI must be run from the UI thread.
5266 // Update the menu item titles.
5267 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5269 // Update the options menu if it has been populated.
5270 if (optionsMenu != null) {
5271 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5272 optionsFanboysSocialBlockingListMenuItem.title =
5273 nestedScrollWebView.getRequestsCount(FANBOYS_SOCIAL_BLOCKING_LIST).toString() + " - " + getString(R.string.fanboys_social_blocking_list)
5278 // The resource request was blocked. Return an empty web resource response.
5279 return emptyWebResourceResponse
5280 } else if (fanboysSocialListResults[0] == REQUEST_ALLOWED) { // The resource request matched Fanboy's Social Blocking List's allow list.
5281 // Update the allow list result string array tracker.
5282 allowListResultStringArray = arrayOf(fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3], fanboysSocialListResults[4],
5283 fanboysSocialListResults[5])
5287 // Add the request to the log because it hasn't been processed by any of the previous checks.
5288 if (allowListResultStringArray != null) { // The request was processed by an allow list.
5289 nestedScrollWebView.addResourceRequest(allowListResultStringArray)
5290 } else { // The request didn't match any filter list entry. Log it as a default request.
5291 nestedScrollWebView.addResourceRequest(arrayOf(REQUEST_DEFAULT, requestUrlString))
5294 // The resource request has not been blocked. `return null` loads the requested resource.
5298 // Handle HTTP authentication requests.
5299 override fun onReceivedHttpAuthRequest(view: WebView, handler: HttpAuthHandler, host: String, realm: String) {
5300 // Store the handler.
5301 nestedScrollWebView.httpAuthHandler = handler
5303 // Instantiate an HTTP authentication dialog.
5304 val httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm, nestedScrollWebView.webViewFragmentId)
5306 // Show the HTTP authentication dialog.
5307 httpAuthenticationDialogFragment.show(supportFragmentManager, getString(R.string.http_authentication))
5310 override fun onPageStarted(webView: WebView, url: String, favicon: Bitmap?) {
5311 // Get the app bar layout height. This can't be done in `applyAppSettings()` because the app bar is not yet populated there.
5312 // 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.
5313 if (appBarLayout.height > 0)
5314 appBarHeight = appBarLayout.height
5316 // Set the padding and layout settings according to the position of the app bar.
5317 if (bottomAppBar) { // The app bar is on the bottom.
5319 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) { // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
5320 // Reset the WebView padding to fill the available space.
5321 swipeRefreshLayout.setPadding(0, 0, 0, 0)
5322 } else { // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
5323 // Move the WebView above the app bar layout.
5324 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
5326 } else { // The app bar is on the top.
5327 // 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.
5328 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) { // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
5329 // No padding is needed because it will automatically be placed below the app bar layout due to the scrolling layout behavior.
5330 swipeRefreshLayout.setPadding(0, 0, 0, 0)
5332 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5333 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10, defaultProgressViewEndOffset)
5334 } else { // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
5335 // The swipe refresh layout must be manually moved below the app bar layout.
5336 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0)
5338 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5339 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight)
5343 // Reset the list of resource requests.
5344 nestedScrollWebView.clearResourceRequests()
5346 // Reset the requests counters.
5347 nestedScrollWebView.resetRequestsCounters()
5349 // Get the current page position.
5350 val currentPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
5352 // Update the URL text bar if the page is currently selected and the URL edit text is not currently being edited.
5353 if ((tabLayout.selectedTabPosition == currentPagePosition) && !urlEditText.hasFocus()) {
5354 // Display the formatted URL text.
5355 urlEditText.setText(url)
5357 // Highlight the URL syntax.
5358 UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
5360 // Hide the keyboard.
5361 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.windowToken, 0)
5364 // Reset the list of host IP addresses.
5365 nestedScrollWebView.currentIpAddresses = ""
5367 // Get a URI for the current URL.
5368 val currentUri = Uri.parse(url)
5370 // Get the current domain name.
5371 val currentDomainName = currentUri.host
5373 // Get the IP addresses for the current domain.
5374 if (!currentDomainName.isNullOrEmpty())
5375 GetHostIpAddressesCoroutine.checkPinnedMismatch(currentDomainName, nestedScrollWebView, supportFragmentManager, getString(R.string.pinned_mismatch))
5377 // 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.)
5378 if ((optionsMenu != null) && (webView == currentWebView)) {
5380 optionsRefreshMenuItem.setTitle(R.string.stop)
5382 // Set the icon if it is displayed in the AppBar.
5383 if (displayAdditionalAppBarIcons)
5384 optionsRefreshMenuItem.setIcon(R.drawable.close_blue)
5388 override fun onPageFinished(webView: WebView, url: String) {
5389 // Flush any cookies to persistent storage. The cookie manager has become very lazy about flushing cookies in recent versions.
5390 if (nestedScrollWebView.acceptCookies)
5391 cookieManager.flush()
5393 // Update the Refresh menu item if the options menu has been created and the WebView is currently displayed.
5394 if (optionsMenu != null && (webView == currentWebView)) {
5395 // Reset the Refresh title.
5396 optionsRefreshMenuItem.setTitle(R.string.refresh)
5398 // Reset the icon if it is displayed in the app bar.
5399 if (displayAdditionalAppBarIcons)
5400 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled)
5403 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
5404 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
5405 val privateDataDirectoryString = applicationInfo.dataDir
5407 // Clear the cache, history, and logcat if Incognito Mode is enabled.
5408 if (incognitoModeEnabled) {
5409 // Clear the cache. `true` includes disk files.
5410 nestedScrollWebView.clearCache(true)
5412 // Clear the back/forward history.
5413 nestedScrollWebView.clearHistory()
5415 // Manually delete cache folders.
5417 // Delete the main cache directory.
5418 Runtime.getRuntime().exec("rm -rf $privateDataDirectoryString/cache")
5419 } catch (exception: IOException) {
5420 // Do nothing if an error is thrown.
5423 // Clear the logcat.
5425 // Clear the logcat. `-c` clears the logcat. `-b all` clears all the buffers (instead of just crash, main, and system).
5426 Runtime.getRuntime().exec("logcat -b all -c")
5427 } catch (exception: IOException) {
5432 // Clear the `Service Worker` directory.
5434 // A string array must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
5435 Runtime.getRuntime().exec(arrayOf("rm", "-rf", "$privateDataDirectoryString/app_webview/Default/Service Worker/"))
5436 } catch (exception: IOException) {
5440 // Get the current page position.
5441 val currentPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
5443 // 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.
5444 val currentUrl = nestedScrollWebView.url
5446 // Get the current tab.
5447 val tab = tabLayout.getTabAt(currentPagePosition)
5449 // Update the URL text bar if the page is currently selected and the user is not currently typing in the URL edit text.
5450 // Crash records show that, in some crazy way, it is possible for the current URL to be blank at this point.
5451 // Probably some sort of race condition when Privacy Browser is being resumed.
5452 if ((tabLayout.selectedTabPosition == currentPagePosition) && !urlEditText.hasFocus() && (currentUrl != null)) {
5453 // Check to see if the URL is `about:blank`.
5454 if (currentUrl == "about:blank") { // The WebView is blank.
5455 // Display the hint in the URL edit text.
5456 urlEditText.setText("")
5458 // Request focus for the URL text box.
5459 urlEditText.requestFocus()
5461 // Display the keyboard.
5462 inputMethodManager.showSoftInput(urlEditText, 0)
5464 // Apply the domain settings. This clears any settings from the previous domain.
5465 applyDomainSettings(nestedScrollWebView, "", resetTab = true, reloadWebsite = false, loadUrl = false)
5467 // Only populate the title text view if the tab has been fully created.
5469 // Get the custom view from the tab.
5470 val tabView = tab.customView!!
5472 // Get the title text view from the tab.
5473 val tabTitleTextView = tabView.findViewById<TextView>(R.id.title_textview)
5475 // Set the title as the tab text.
5476 tabTitleTextView.setText(R.string.new_tab)
5478 } else { // The WebView has loaded a webpage.
5479 // Update the URL edit text if it is not currently being edited.
5480 if (!urlEditText.hasFocus()) {
5481 // 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.
5482 val sanitizedUrl = sanitizeUrl(currentUrl)
5484 // Display the final URL. Getting the URL from the WebView instead of using the one provided by `onPageFinished()` makes websites like YouTube function correctly.
5485 urlEditText.setText(sanitizedUrl)
5487 // Highlight the URL syntax.
5488 UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
5491 // Only populate the title text view if the tab has been fully created.
5493 // Get the custom view from the tab.
5494 val tabView = tab.customView!!
5496 // Get the title text view from the tab.
5497 val tabTitleTextView = tabView.findViewById<TextView>(R.id.title_textview)
5499 // Set the title as the tab text. Sometimes `onReceivedTitle()` is not called, especially when navigating history.
5500 tabTitleTextView.text = nestedScrollWebView.title
5506 // Handle SSL Certificate errors. Suppress the lint warning that ignoring the error might be dangerous.
5507 @SuppressLint("WebViewClientOnReceivedSslError")
5508 override fun onReceivedSslError(view: WebView, handler: SslErrorHandler, error: SslError) {
5509 // Get the current website SSL certificate.
5510 val currentWebsiteSslCertificate = error.certificate
5512 // Extract the individual pieces of information from the current website SSL certificate.
5513 val currentWebsiteIssuedToCName = currentWebsiteSslCertificate.issuedTo.cName
5514 val currentWebsiteIssuedToOName = currentWebsiteSslCertificate.issuedTo.oName
5515 val currentWebsiteIssuedToUName = currentWebsiteSslCertificate.issuedTo.uName
5516 val currentWebsiteIssuedByCName = currentWebsiteSslCertificate.issuedBy.cName
5517 val currentWebsiteIssuedByOName = currentWebsiteSslCertificate.issuedBy.oName
5518 val currentWebsiteIssuedByUName = currentWebsiteSslCertificate.issuedBy.uName
5519 val currentWebsiteSslStartDate = currentWebsiteSslCertificate.validNotBeforeDate
5520 val currentWebsiteSslEndDate = currentWebsiteSslCertificate.validNotAfterDate
5522 // Get the pinned SSL certificate.
5523 val (pinnedSslCertificateStringArray, pinnedSslCertificateDateArray) = nestedScrollWebView.getPinnedSslCertificate()
5525 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
5526 if (nestedScrollWebView.hasPinnedSslCertificate() &&
5527 (currentWebsiteIssuedToCName == pinnedSslCertificateStringArray[0]) &&
5528 (currentWebsiteIssuedToOName == pinnedSslCertificateStringArray[1]) &&
5529 (currentWebsiteIssuedToUName == pinnedSslCertificateStringArray[2]) &&
5530 (currentWebsiteIssuedByCName == pinnedSslCertificateStringArray[3]) &&
5531 (currentWebsiteIssuedByOName == pinnedSslCertificateStringArray[4]) &&
5532 (currentWebsiteIssuedByUName == pinnedSslCertificateStringArray[5]) &&
5533 (currentWebsiteSslStartDate == pinnedSslCertificateDateArray[0]) &&
5534 (currentWebsiteSslEndDate == pinnedSslCertificateDateArray[1])) {
5536 // An SSL certificate is pinned and matches the current domain certificate. Proceed to the website without displaying an error.
5538 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
5539 // Store the SSL error handler.
5540 nestedScrollWebView.sslErrorHandler = handler
5542 // Instantiate an SSL certificate error alert dialog.
5543 val sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error, nestedScrollWebView.webViewFragmentId)
5545 // 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.
5547 // Show the SSL certificate error dialog.
5548 sslCertificateErrorDialogFragment.show(supportFragmentManager, getString(R.string.ssl_certificate_error))
5549 } catch (exception: Exception) {
5550 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
5551 pendingDialogsArrayList.add(PendingDialogDataClass(sslCertificateErrorDialogFragment, getString(R.string.ssl_certificate_error)))
5557 // Check to see if the state is being restored.
5558 if (restoringState) { // The state is being restored.
5559 // Resume the nested scroll WebView JavaScript timers.
5560 nestedScrollWebView.resumeTimers()
5561 } else if (pageNumber == 0) { // The first page is being loaded.
5562 // Set this nested scroll WebView as the current WebView.
5563 currentWebView = nestedScrollWebView
5565 // Get the intent that started the app.
5566 val launchingIntent = intent
5568 // Reset the intent. This prevents a duplicate tab from being created on restart.
5571 // Get the information from the intent.
5572 val launchingIntentAction = launchingIntent.action
5573 val launchingIntentUriData = launchingIntent.data
5574 val launchingIntentStringExtra = launchingIntent.getStringExtra(Intent.EXTRA_TEXT)
5576 // Parse the launching intent URL. Suppress the suggestions of using elvis expressions as they make the logic very difficult to follow.
5577 @Suppress("IfThenToElvis") val urlToLoadString = if ((launchingIntentAction != null) && (launchingIntentAction == Intent.ACTION_WEB_SEARCH)) { // The intent contains a search string.
5578 // Sanitize the search input and convert it to a search.
5579 val encodedSearchString = try {
5580 URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8")
5581 } catch (exception: UnsupportedEncodingException) {
5585 // Add the search URL to the encodedSearchString
5586 searchURL + encodedSearchString
5587 } else if (launchingIntentUriData != null) { // The launching intent contains a URL formatted as a URI.
5588 // Get the URL from the URI.
5589 launchingIntentUriData.toString()
5590 } else if (launchingIntentStringExtra != null) { // The launching intent contains text that might be a URL.
5591 // Get the URL from the string extra.
5592 launchingIntentStringExtra
5593 } else if (urlString != "") { // The activity has been restarted.
5594 // Load the saved URL.
5596 } else { // The is no saved URL and there is no URL in the intent.
5597 // Load the homepage.
5598 sharedPreferences.getString("homepage", getString(R.string.homepage_default_value))
5601 // Load the website if not waiting for the proxy.
5602 if (waitingForProxy) { // Store the URL to be loaded in the Nested Scroll WebView.
5603 nestedScrollWebView.waitingForProxyUrlString = urlToLoadString!!
5604 } else { // Load the URL.
5605 loadUrl(nestedScrollWebView, urlToLoadString!!)
5608 // 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.
5609 // 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.
5611 } else { // This is not the first tab.
5613 loadUrl(nestedScrollWebView, urlString)
5615 // Set the focus and display the keyboard if the URL is blank.
5616 if (urlString == "") {
5617 // Request focus for the URL text box.
5618 urlEditText.requestFocus()
5620 // Create a display keyboard handler.
5621 val displayKeyboardHandler = Handler(Looper.getMainLooper())
5623 // Create a display keyboard runnable.
5624 val displayKeyboardRunnable = Runnable {
5625 // Display the keyboard.
5626 inputMethodManager.showSoftInput(urlEditText, 0)
5629 // Display the keyboard after 100 milliseconds, which leaves enough time for the tab to transition.
5630 displayKeyboardHandler.postDelayed(displayKeyboardRunnable, 100)
5635 private fun loadBookmarksFolder() {
5636 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
5637 bookmarksCursor = bookmarksDatabaseHelper!!.getBookmarksByDisplayOrder(currentBookmarksFolderId)
5639 // Populate the bookmarks cursor adapter.
5640 bookmarksCursorAdapter = object : CursorAdapter(this, bookmarksCursor, false) {
5641 override fun newView(context: Context, cursor: Cursor, parent: ViewGroup): View {
5642 // Inflate the individual item layout.
5643 return layoutInflater.inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false)
5646 override fun bindView(view: View, context: Context, cursor: Cursor) {
5647 // Get handles for the views.
5648 val bookmarkFavoriteIcon = view.findViewById<ImageView>(R.id.bookmark_favorite_icon)
5649 val bookmarkNameTextView = view.findViewById<TextView>(R.id.bookmark_name)
5651 // Get the favorite icon byte array from the cursor.
5652 val favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndexOrThrow(FAVORITE_ICON))
5654 // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
5655 val favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.size)
5657 // Display the bitmap in the bookmark favorite icon.
5658 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap)
5660 // Display the bookmark name from the cursor in the bookmark name text view.
5661 bookmarkNameTextView.text = cursor.getString(cursor.getColumnIndexOrThrow(BOOKMARK_NAME))
5663 // Make the font bold for folders.
5664 if (cursor.getInt(cursor.getColumnIndexOrThrow(IS_FOLDER)) == 1)
5665 bookmarkNameTextView.typeface = Typeface.DEFAULT_BOLD
5666 else // Reset the font to default for normal bookmarks.
5667 bookmarkNameTextView.typeface = Typeface.DEFAULT
5671 // Populate the list view with the adapter.
5672 bookmarksListView.adapter = bookmarksCursorAdapter
5674 // Set the bookmarks drawer title.
5675 if (currentBookmarksFolderId == HOME_FOLDER_ID) // The current bookmarks folder is the home folder.
5676 bookmarksTitleTextView.setText(R.string.bookmarks)
5678 bookmarksTitleTextView.text = bookmarksDatabaseHelper!!.getFolderName(currentBookmarksFolderId)
5681 private fun loadUrl(nestedScrollWebView: NestedScrollWebView, url: String) {
5682 // Sanitize the URL.
5683 val urlString = sanitizeUrl(url)
5685 // Apply the domain settings and load the URL.
5686 applyDomainSettings(nestedScrollWebView, urlString, resetTab = true, reloadWebsite = false, loadUrl = true)
5689 private fun loadUrlFromTextBox() {
5690 // 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.
5691 var unformattedUrlString = urlEditText.text.toString().trim { it <= ' ' }
5693 // Create the formatted URL string.
5696 // Check to see if the unformatted URL string is a valid URL. Otherwise, convert it into a search.
5697 if (unformattedUrlString.startsWith("content://")) { // This is a content URL.
5698 // Load the entire content URL.
5699 urlString = unformattedUrlString
5700 } else if (Patterns.WEB_URL.matcher(unformattedUrlString).matches() || unformattedUrlString.startsWith("http://") || unformattedUrlString.startsWith("https://") ||
5701 unformattedUrlString.startsWith("file://")) { // This is a standard URL.
5703 // Add `https://` at the beginning if there is no protocol. Otherwise the app will segfault.
5704 if (!unformattedUrlString.startsWith("http") && !unformattedUrlString.startsWith("file://"))
5705 unformattedUrlString = "https://$unformattedUrlString"
5707 // Initialize the unformatted URL.
5708 var unformattedUrl: URL? = null
5710 // Convert the unformatted URL string to a URL.
5712 unformattedUrl = URL(unformattedUrlString)
5713 } catch (exception: MalformedURLException) {
5714 exception.printStackTrace()
5717 // Get the components of the URL.
5718 val scheme = unformattedUrl?.protocol
5719 val authority = unformattedUrl?.authority
5720 val path = unformattedUrl?.path
5721 val query = unformattedUrl?.query
5722 val fragment = unformattedUrl?.ref
5725 val uri = Uri.Builder()
5727 // Build the URI from the components of the URL.
5728 uri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment)
5730 // Decode the URI as a UTF-8 string in.
5732 urlString = URLDecoder.decode(uri.build().toString(), "UTF-8")
5733 } catch (exception: UnsupportedEncodingException) {
5734 // Do nothing. The formatted URL string will remain blank.
5736 } else if (unformattedUrlString.isNotEmpty()) { // This is not a URL, but rather a search string.
5737 // Sanitize the search input.
5738 val encodedSearchString = try {
5739 URLEncoder.encode(unformattedUrlString, "UTF-8")
5740 } catch (exception: UnsupportedEncodingException) {
5744 // Add the base search URL.
5745 urlString = searchURL + encodedSearchString
5748 // 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.
5749 urlEditText.clearFocus()
5752 loadUrl(currentWebView!!, urlString)
5755 override fun navigateHistory(url: String, steps: Int) {
5756 // Apply the domain settings.
5757 applyDomainSettings(currentWebView!!, url, resetTab = false, reloadWebsite = false, loadUrl = false)
5759 // Load the history entry.
5760 currentWebView!!.goBackOrForward(steps)
5763 override fun openFile(dialogFragment: DialogFragment) {
5765 val dialog = dialogFragment.dialog!!
5767 // Get handles for the views.
5768 val fileNameEditText = dialog.findViewById<EditText>(R.id.file_name_edittext)
5769 val mhtCheckBox = dialog.findViewById<CheckBox>(R.id.mht_checkbox)
5771 // Get the file path string.
5772 val openFilePath = fileNameEditText.text.toString()
5774 // Apply the domain settings. This resets the favorite icon and removes any domain settings.
5775 applyDomainSettings(currentWebView!!, openFilePath, resetTab = true, reloadWebsite = false, loadUrl = false)
5777 // Open the file according to the type.
5778 if (mhtCheckBox.isChecked) { // Force opening of an MHT file.
5780 // Get the MHT file input stream.
5781 val mhtFileInputStream = contentResolver.openInputStream(Uri.parse(openFilePath))
5783 // Create a temporary MHT file.
5784 val temporaryMhtFile = File.createTempFile(TEMPORARY_MHT_FILE, ".mht", cacheDir)
5786 // Get a file output stream for the temporary MHT file.
5787 val temporaryMhtFileOutputStream = FileOutputStream(temporaryMhtFile)
5789 // Create a transfer byte array.
5790 val transferByteArray = ByteArray(1024)
5792 // Create an integer to track the number of bytes read.
5795 // Copy the temporary MHT file input stream to the MHT output stream.
5796 while (mhtFileInputStream!!.read(transferByteArray).also { bytesRead = it } > 0)
5797 temporaryMhtFileOutputStream.write(transferByteArray, 0, bytesRead)
5799 // Flush the temporary MHT file output stream.
5800 temporaryMhtFileOutputStream.flush()
5802 // Close the streams.
5803 temporaryMhtFileOutputStream.close()
5804 mhtFileInputStream.close()
5806 // Load the temporary MHT file.
5807 currentWebView!!.loadUrl(temporaryMhtFile.toString())
5808 } catch (exception: Exception) {
5809 // Display a snackbar.
5810 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
5812 } else { // Let the WebView handle opening of the file.
5814 currentWebView!!.loadUrl(openFilePath)
5818 private fun openWithApp(url: String) {
5819 // Create an open with app intent with `ACTION_VIEW`.
5820 val openWithAppIntent = Intent(Intent.ACTION_VIEW)
5822 // Set the URI but not the MIME type. This should open all available apps.
5823 openWithAppIntent.data = Uri.parse(url)
5825 // Flag the intent to open in a new task.
5826 openWithAppIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
5830 // Show the chooser.
5831 startActivity(openWithAppIntent)
5832 } catch (exception: ActivityNotFoundException) { // There are no apps available to open the URL.
5833 // Show a snackbar with the error.
5834 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
5838 private fun openWithBrowser(url: String) {
5840 // Create an open with browser intent with `ACTION_VIEW`.
5841 val openWithBrowserIntent = Intent(Intent.ACTION_VIEW)
5843 // Set the URI and the MIME type. `"text/html"` should load browser options.
5844 openWithBrowserIntent.setDataAndType(Uri.parse(url), "text/html")
5846 // Flag the intent to open in a new task.
5847 openWithBrowserIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
5851 // Show the chooser.
5852 startActivity(openWithBrowserIntent)
5853 } catch (exception: ActivityNotFoundException) { // There are no browsers available to open the URL.
5854 // Show a snackbar with the error.
5855 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
5859 override fun pinnedErrorGoBack() {
5860 // Get the current web back forward list.
5861 val webBackForwardList = currentWebView!!.copyBackForwardList()
5863 // Get the previous entry URL.
5864 val previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex - 1).url
5866 // Apply the domain settings.
5867 applyDomainSettings(currentWebView!!, previousUrl, resetTab = false, reloadWebsite = false, loadUrl = false)
5870 currentWebView!!.goBack()
5873 private fun sanitizeUrl(urlString: String): String {
5874 // Initialize a sanitized URL string.
5875 var sanitizedUrlString = urlString
5877 // Sanitize tracking queries.
5878 if (sanitizeTrackingQueries)
5879 sanitizedUrlString = SanitizeUrlHelper.sanitizeTrackingQueries(sanitizedUrlString)
5881 // Sanitize AMP redirects.
5882 if (sanitizeAmpRedirects)
5883 sanitizedUrlString = SanitizeUrlHelper.sanitizeAmpRedirects(sanitizedUrlString)
5885 // Return the sanitized URL string.
5886 return sanitizedUrlString
5889 override fun saveUrl(originalUrlString: String, fileNameString: String, dialogFragment: DialogFragment) {
5890 // Store the URL. This will be used in the save URL activity result launcher.
5891 saveUrlString = if (originalUrlString.startsWith("data:")) {
5892 // Save the original URL.
5896 val dialog = dialogFragment.dialog!!
5898 // Get a handle for the dialog URL edit text.
5899 val dialogUrlEditText = dialog.findViewById<EditText>(R.id.url_edittext)
5901 // Get the URL from the edit text, which may have been modified.
5902 dialogUrlEditText.text.toString()
5905 // Open the file picker.
5906 saveUrlActivityResultLauncher.launch(fileNameString)
5909 private fun setCurrentWebView(pageNumber: Int) {
5910 // Stop the swipe to refresh indicator if it is running
5911 swipeRefreshLayout.isRefreshing = false
5913 // Get the WebView tab fragment.
5914 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(pageNumber)
5916 // Get the fragment view.
5917 val webViewFragmentView = webViewTabFragment.view
5919 // Set the current WebView if the fragment view is not null.
5920 if (webViewFragmentView != null) { // The fragment has been populated.
5921 // Store the current WebView.
5922 currentWebView = webViewFragmentView.findViewById(R.id.nestedscroll_webview)
5924 // Update the status of swipe to refresh.
5925 if (currentWebView!!.swipeToRefresh) { // Swipe to refresh is enabled.
5926 // Enable the swipe refresh layout if the WebView is scrolled all the way to the top. It is updated every time the scroll changes.
5927 swipeRefreshLayout.isEnabled = (currentWebView!!.scrollY == 0)
5928 } else { // Swipe to refresh is disabled.
5929 // Disable the swipe refresh layout.
5930 swipeRefreshLayout.isEnabled = false
5933 // Set the cookie status.
5934 cookieManager.setAcceptCookie(currentWebView!!.acceptCookies)
5936 // Update the privacy icons. `true` redraws the icons in the app bar.
5937 updatePrivacyIcons(true)
5939 // Get a handle for the input method manager.
5940 val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
5942 // Get the current URL.
5943 val urlString = currentWebView!!.url
5945 // Update the URL edit text if not loading a new intent. Otherwise, this will be handled by `onPageStarted()` (if called) and `onPageFinished()`.
5946 if (!loadingNewIntent) { // A new intent is not being loaded.
5947 if ((urlString == null) || (urlString == "about:blank")) { // The WebView is blank.
5948 // Display the hint in the URL edit text.
5949 urlEditText.setText("")
5951 // Request focus for the URL text box.
5952 urlEditText.requestFocus()
5954 // Display the keyboard.
5955 inputMethodManager.showSoftInput(urlEditText, 0)
5956 } else { // The WebView has a loaded URL.
5957 // Clear the focus from the URL text box.
5958 urlEditText.clearFocus()
5960 // Hide the soft keyboard.
5961 inputMethodManager.hideSoftInputFromWindow(currentWebView!!.windowToken, 0)
5963 // Display the current URL in the URL text box.
5964 urlEditText.setText(urlString)
5966 // Highlight the URL syntax.
5967 UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
5969 } else { // A new intent is being loaded.
5970 // Reset the loading new intent flag.
5971 loadingNewIntent = false
5974 // Set the background to indicate the domain settings status.
5975 if (currentWebView!!.domainSettingsApplied) {
5976 // Set a background on the URL relative layout to indicate that custom domain settings are being used.
5977 urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.drawable.domain_settings_url_background)
5979 // Remove any background on the URL relative layout.
5980 urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.color.transparent)
5982 } else if ((pageNumber == savedTabPosition) || (pageNumber >= (webViewStateAdapter!!.itemCount - 1))) { // The tab has not been populated yet.
5983 // Try again in 100 milliseconds if the app is being restored or the a new tab has been added (the last tab).
5984 // Create a handler to set the current WebView.
5985 val setCurrentWebViewHandler = Handler(Looper.getMainLooper())
5987 // Create a runnable to set the current WebView.
5988 val setCurrentWebWebRunnable = Runnable {
5989 // Set the current WebView.
5990 setCurrentWebView(pageNumber)
5993 // Try setting the current WebView again after 100 milliseconds.
5994 setCurrentWebViewHandler.postDelayed(setCurrentWebWebRunnable, 100)
5998 // The view parameter cannot be removed because it is called from the layout onClick.
5999 fun toggleBookmarksDrawerPinned(@Suppress("UNUSED_PARAMETER")view: View?) {
6000 // Toggle the bookmarks drawer pinned tracker.
6001 bookmarksDrawerPinned = !bookmarksDrawerPinned
6003 // Update the bookmarks drawer pinned image view.
6004 updateBookmarksDrawerPinnedImageView()
6007 private fun updateBookmarksDrawerPinnedImageView() {
6008 // Set the current icon.
6009 if (bookmarksDrawerPinned)
6010 bookmarksDrawerPinnedImageView.setImageResource(R.drawable.pin_selected)
6012 bookmarksDrawerPinnedImageView.setImageResource(R.drawable.pin)
6015 private fun updateDomainsSettingsSet() {
6016 // Reset the domains settings set.
6017 domainsSettingsSet = HashSet()
6019 // Get a domains cursor.
6020 val domainsCursor = domainsDatabaseHelper!!.domainNameCursorOrderedByDomain
6022 // Get the current count of domains.
6023 val domainsCount = domainsCursor.count
6025 // Get the domain name column index.
6026 val domainNameColumnIndex = domainsCursor.getColumnIndexOrThrow(DOMAIN_NAME)
6028 // Populate the domain settings set.
6029 for (i in 0 until domainsCount) {
6030 // Move the domains cursor to the current row.
6031 domainsCursor.moveToPosition(i)
6033 // Store the domain name in the domain settings set.
6034 domainsSettingsSet.add(domainsCursor.getString(domainNameColumnIndex))
6037 // Close the domains cursor.
6038 domainsCursor.close()
6041 override fun updateFontSize(dialogFragment: DialogFragment) {
6043 val dialog = dialogFragment.dialog!!
6045 // Get a handle for the font size edit text.
6046 val fontSizeEditText = dialog.findViewById<EditText>(R.id.font_size_edittext)
6048 // Initialize the new font size variable with the current font size.
6049 var newFontSize = currentWebView!!.settings.textZoom
6051 // Get the font size from the edit text.
6053 newFontSize = fontSizeEditText.text.toString().toInt()
6054 } catch (exception: Exception) {
6055 // If the edit text does not contain a valid font size do nothing.
6058 // Apply the new font size.
6059 currentWebView!!.settings.textZoom = newFontSize
6062 private fun updatePrivacyIcons(runInvalidateOptionsMenu: Boolean) {
6063 // Only update the privacy icons if the options menu and the current WebView have already been populated.
6064 if ((optionsMenu != null) && (currentWebView != null)) {
6065 // Update the privacy icon.
6066 if (currentWebView!!.settings.javaScriptEnabled) // JavaScript is enabled.
6067 optionsPrivacyMenuItem.setIcon(R.drawable.javascript_enabled)
6068 else if (currentWebView!!.acceptCookies) // JavaScript is disabled but cookies are enabled.
6069 optionsPrivacyMenuItem.setIcon(R.drawable.warning)
6070 else // All the dangerous features are disabled.
6071 optionsPrivacyMenuItem.setIcon(R.drawable.privacy_mode)
6073 // Update the cookies icon.
6074 if (currentWebView!!.acceptCookies)
6075 optionsCookiesMenuItem.setIcon(R.drawable.cookies_enabled)
6077 optionsCookiesMenuItem.setIcon(R.drawable.cookies_disabled)
6079 // Update the refresh icon.
6080 if (optionsRefreshMenuItem.title == getString(R.string.refresh)) // The refresh icon is displayed.
6081 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled)
6082 else // The stop icon is displayed.
6083 optionsRefreshMenuItem.setIcon(R.drawable.close_blue)
6085 // `invalidateOptionsMenu()` calls `onPrepareOptionsMenu()` and redraws the icons in the app bar.
6086 if (runInvalidateOptionsMenu)
6087 invalidateOptionsMenu()