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.Log
57 import android.util.Patterns
58 import android.util.TypedValue
59 import android.view.ContextMenu
60 import android.view.GestureDetector
61 import android.view.KeyEvent
62 import android.view.Menu
63 import android.view.MenuItem
64 import android.view.MotionEvent
65 import android.view.View
66 import android.view.ViewGroup
67 import android.view.WindowManager
68 import android.view.inputmethod.InputMethodManager
69 import android.webkit.CookieManager
70 import android.webkit.HttpAuthHandler
71 import android.webkit.ValueCallback
72 import android.webkit.SslErrorHandler
73 import android.webkit.WebChromeClient
74 import android.webkit.WebResourceRequest
75 import android.webkit.WebResourceResponse
76 import android.webkit.WebSettings
77 import android.webkit.WebStorage
78 import android.webkit.WebView
79 import android.webkit.WebViewClient
80 import android.webkit.WebViewDatabase
81 import android.widget.AdapterView
82 import android.widget.ArrayAdapter
83 import android.widget.CheckBox
84 import android.widget.EditText
85 import android.widget.FrameLayout
86 import android.widget.ImageView
87 import android.widget.LinearLayout
88 import android.widget.ListView
89 import android.widget.ProgressBar
90 import android.widget.RadioButton
91 import android.widget.RelativeLayout
92 import android.widget.TextView
94 import androidx.activity.OnBackPressedCallback
95 import androidx.activity.result.contract.ActivityResultContracts
96 import androidx.appcompat.app.ActionBar
97 import androidx.appcompat.app.ActionBarDrawerToggle
98 import androidx.appcompat.app.AppCompatActivity
99 import androidx.appcompat.app.AppCompatDelegate
100 import androidx.appcompat.content.res.AppCompatResources
101 import androidx.appcompat.widget.Toolbar
102 import androidx.coordinatorlayout.widget.CoordinatorLayout
103 import androidx.core.view.GravityCompat
104 import androidx.cursoradapter.widget.CursorAdapter
105 import androidx.drawerlayout.widget.DrawerLayout
106 import androidx.fragment.app.DialogFragment
107 import androidx.preference.PreferenceManager
108 import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
109 import androidx.viewpager2.widget.ViewPager2
110 import androidx.webkit.WebSettingsCompat
111 import androidx.webkit.WebViewFeature
113 import com.google.android.material.appbar.AppBarLayout
114 import com.google.android.material.floatingactionbutton.FloatingActionButton
115 import com.google.android.material.navigation.NavigationView
116 import com.google.android.material.snackbar.Snackbar
117 import com.google.android.material.tabs.TabLayout
119 import com.stoutner.privacybrowser.R
120 import com.stoutner.privacybrowser.adapters.WebViewStateAdapter
121 import com.stoutner.privacybrowser.coroutines.GetHostIpAddressesCoroutine
122 import com.stoutner.privacybrowser.coroutines.PopulateFilterListsCoroutine
123 import com.stoutner.privacybrowser.coroutines.PrepareSaveDialogCoroutine
124 import com.stoutner.privacybrowser.coroutines.SaveUrlCoroutine
125 import com.stoutner.privacybrowser.coroutines.SaveWebpageImageCoroutine
126 import com.stoutner.privacybrowser.dataclasses.PendingDialogDataClass
127 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog
128 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog
129 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog
130 import com.stoutner.privacybrowser.dialogs.FontSizeDialog
131 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog
132 import com.stoutner.privacybrowser.dialogs.OpenDialog
133 import com.stoutner.privacybrowser.dialogs.PinnedMismatchDialog
134 import com.stoutner.privacybrowser.dialogs.ProxyNotInstalledDialog
135 import com.stoutner.privacybrowser.dialogs.SaveDialog
136 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog
137 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog
138 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog
139 import com.stoutner.privacybrowser.dialogs.WaitingForProxyDialog
140 import com.stoutner.privacybrowser.fragments.WebViewTabFragment
141 import com.stoutner.privacybrowser.helpers.BOOKMARK_NAME
142 import com.stoutner.privacybrowser.helpers.BOOKMARK_URL
143 import com.stoutner.privacybrowser.helpers.COOKIES
144 import com.stoutner.privacybrowser.helpers.DARK_THEME
145 import com.stoutner.privacybrowser.helpers.DISABLED
146 import com.stoutner.privacybrowser.helpers.DISPLAY_IMAGES
147 import com.stoutner.privacybrowser.helpers.DOMAIN_NAME
148 import com.stoutner.privacybrowser.helpers.ENABLE_DOM_STORAGE
149 import com.stoutner.privacybrowser.helpers.ENABLE_EASYLIST
150 import com.stoutner.privacybrowser.helpers.ENABLE_EASYPRIVACY
151 import com.stoutner.privacybrowser.helpers.ENABLE_FANBOYS_ANNOYANCE_LIST
152 import com.stoutner.privacybrowser.helpers.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST
153 import com.stoutner.privacybrowser.helpers.ENABLE_FORM_DATA
154 import com.stoutner.privacybrowser.helpers.ENABLE_JAVASCRIPT
155 import com.stoutner.privacybrowser.helpers.ENABLE_ULTRAPRIVACY
156 import com.stoutner.privacybrowser.helpers.ENABLED
157 import com.stoutner.privacybrowser.helpers.FAVORITE_ICON
158 import com.stoutner.privacybrowser.helpers.FOLDER_ID
159 import com.stoutner.privacybrowser.helpers.FONT_SIZE
160 import com.stoutner.privacybrowser.helpers.ID
161 import com.stoutner.privacybrowser.helpers.IP_ADDRESSES
162 import com.stoutner.privacybrowser.helpers.IS_FOLDER
163 import com.stoutner.privacybrowser.helpers.LIGHT_THEME
164 import com.stoutner.privacybrowser.helpers.PINNED_IP_ADDRESSES
165 import com.stoutner.privacybrowser.helpers.PINNED_SSL_CERTIFICATE
166 import com.stoutner.privacybrowser.helpers.REQUEST_ALLOWED
167 import com.stoutner.privacybrowser.helpers.REQUEST_BLOCKED
168 import com.stoutner.privacybrowser.helpers.REQUEST_DEFAULT
169 import com.stoutner.privacybrowser.helpers.REQUEST_THIRD_PARTY
170 import com.stoutner.privacybrowser.helpers.SSL_ISSUED_BY_COMMON_NAME
171 import com.stoutner.privacybrowser.helpers.SSL_ISSUED_BY_ORGANIZATION
172 import com.stoutner.privacybrowser.helpers.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT
173 import com.stoutner.privacybrowser.helpers.SSL_ISSUED_TO_COMMON_NAME
174 import com.stoutner.privacybrowser.helpers.SSL_ISSUED_TO_ORGANIZATION
175 import com.stoutner.privacybrowser.helpers.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT
176 import com.stoutner.privacybrowser.helpers.SWIPE_TO_REFRESH
177 import com.stoutner.privacybrowser.helpers.SYSTEM_DEFAULT
178 import com.stoutner.privacybrowser.helpers.WEBVIEW_THEME
179 import com.stoutner.privacybrowser.helpers.WIDE_VIEWPORT
180 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper
181 import com.stoutner.privacybrowser.helpers.CheckFilterListHelper
182 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper
183 import com.stoutner.privacybrowser.helpers.ProxyHelper
184 import com.stoutner.privacybrowser.helpers.SanitizeUrlHelper
185 import com.stoutner.privacybrowser.helpers.UrlHelper
186 import com.stoutner.privacybrowser.views.BLOCKED_REQUESTS
187 import com.stoutner.privacybrowser.views.EASYLIST
188 import com.stoutner.privacybrowser.views.EASYPRIVACY
189 import com.stoutner.privacybrowser.views.FANBOYS_ANNOYANCE_LIST
190 import com.stoutner.privacybrowser.views.FANBOYS_SOCIAL_BLOCKING_LIST
191 import com.stoutner.privacybrowser.views.THIRD_PARTY_REQUESTS
192 import com.stoutner.privacybrowser.views.ULTRAPRIVACY
193 import com.stoutner.privacybrowser.views.NestedScrollWebView
195 import kotlinx.coroutines.CoroutineScope
196 import kotlinx.coroutines.Dispatchers
197 import kotlinx.coroutines.launch
198 import kotlinx.coroutines.withContext
200 import java.io.ByteArrayInputStream
201 import java.io.ByteArrayOutputStream
203 import java.io.FileInputStream
204 import java.io.FileOutputStream
205 import java.io.IOException
206 import java.io.UnsupportedEncodingException
208 import java.net.MalformedURLException
210 import java.net.URLDecoder
211 import java.net.URLEncoder
213 import java.text.NumberFormat
215 import java.util.ArrayList
216 import java.util.Date
217 import java.util.concurrent.Executors
218 import kotlin.system.exitProcess
220 // Define the public constants
221 const val CURRENT_URL = "current_url"
222 const val DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0
223 const val DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2
224 const val DOMAINS_CUSTOM_USER_AGENT = 12
225 const val SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1
226 const val SETTINGS_CUSTOM_USER_AGENT = 11
227 const val UNRECOGNIZED_USER_AGENT = -1
229 // Define the private class constants.
230 private const val BOOKMARKS_DRAWER_PINNED = "bookmarks_drawer_pinned"
231 private const val PROXY_MODE = "proxy_mode"
232 private const val SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST = "saved_nested_scroll_webview_state_array_list"
233 private const val SAVED_STATE_ARRAY_LIST = "saved_state_array_list"
234 private const val SAVED_TAB_POSITION = "saved_tab_position"
235 private const val TEMPORARY_MHT_FILE = "temporary_mht_file"
237 class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener, FontSizeDialog.UpdateFontSizeListener,
238 NavigationView.OnNavigationItemSelectedListener, OpenDialog.OpenListener, PinnedMismatchDialog.PinnedMismatchListener, PopulateFilterListsCoroutine.PopulateFilterListsListener, SaveDialog.SaveListener,
239 UrlHistoryDialog.NavigateHistoryListener, WebViewTabFragment.NewTabListener {
242 // Define the public static variables.
243 var currentBookmarksFolderId = 0L
244 val executorService = Executors.newFixedThreadPool(4)!!
245 var orbotStatus = "unknown"
246 val pendingDialogsArrayList = ArrayList<PendingDialogDataClass>()
247 var proxyMode = ProxyHelper.NONE
248 var restartFromBookmarksActivity = false
249 var webViewStateAdapter: WebViewStateAdapter? = null
251 // Declare the public static variables.
252 lateinit var appBarLayout: AppBarLayout
255 // Declare the class variables.
256 private lateinit var appBar: ActionBar
257 private lateinit var checkFilterListHelper: CheckFilterListHelper
258 private lateinit var bookmarksCursorAdapter: CursorAdapter
259 private lateinit var bookmarksListView: ListView
260 private lateinit var bookmarksDrawerPinnedImageView: ImageView
261 private lateinit var bookmarksTitleTextView: TextView
262 private lateinit var coordinatorLayout: CoordinatorLayout
263 private lateinit var cookieManager: CookieManager
264 private lateinit var defaultFontSizeString: String
265 private lateinit var defaultUserAgentName: String
266 private lateinit var defaultWebViewTheme: String
267 private lateinit var domainsSettingsSet: MutableSet<String>
268 private lateinit var drawerLayout: DrawerLayout
269 private lateinit var easyList: ArrayList<List<Array<String>>>
270 private lateinit var easyPrivacy: ArrayList<List<Array<String>>>
271 private lateinit var fanboysAnnoyanceList: ArrayList<List<Array<String>>>
272 private lateinit var fanboysSocialList: ArrayList<List<Array<String>>>
273 private lateinit var fileChooserCallback: ValueCallback<Array<Uri>>
274 private lateinit var finalGrayColorSpan: ForegroundColorSpan
275 private lateinit var findOnPageCountTextView: TextView
276 private lateinit var findOnPageEditText: EditText
277 private lateinit var findOnPageLinearLayout: LinearLayout
278 private lateinit var fullScreenVideoFrameLayout: FrameLayout
279 private lateinit var initialGrayColorSpan: ForegroundColorSpan
280 private lateinit var navigationBackMenuItem: MenuItem
281 private lateinit var navigationForwardMenuItem: MenuItem
282 private lateinit var navigationHistoryMenuItem: MenuItem
283 private lateinit var navigationRequestsMenuItem: MenuItem
284 private lateinit var optionsAddOrEditDomainMenuItem: MenuItem
285 private lateinit var optionsBlockAllThirdPartyRequestsMenuItem: MenuItem
286 private lateinit var optionsClearCookiesMenuItem: MenuItem
287 private lateinit var optionsClearDataMenuItem: MenuItem
288 private lateinit var optionsClearDomStorageMenuItem: MenuItem
289 private lateinit var optionsClearFormDataMenuItem: MenuItem
290 private lateinit var optionsCookiesMenuItem: MenuItem
291 private lateinit var optionsDarkWebViewMenuItem: MenuItem
292 private lateinit var optionsDisplayImagesMenuItem: MenuItem
293 private lateinit var optionsDomStorageMenuItem: MenuItem
294 private lateinit var optionsEasyListMenuItem: MenuItem
295 private lateinit var optionsEasyPrivacyMenuItem: MenuItem
296 private lateinit var optionsFanboysAnnoyanceListMenuItem: MenuItem
297 private lateinit var optionsFanboysSocialBlockingListMenuItem: MenuItem
298 private lateinit var optionsFilterListsMenuItem: MenuItem
299 private lateinit var optionsFontSizeMenuItem: MenuItem
300 private lateinit var optionsPrivacyMenuItem: MenuItem
301 private lateinit var optionsProxyCustomMenuItem: MenuItem
302 private lateinit var optionsProxyI2pMenuItem: MenuItem
303 private lateinit var optionsProxyMenuItem: MenuItem
304 private lateinit var optionsProxyNoneMenuItem: MenuItem
305 private lateinit var optionsProxyTorMenuItem: MenuItem
306 private lateinit var optionsRefreshMenuItem: MenuItem
307 private lateinit var optionsSaveFormDataMenuItem: MenuItem
308 private lateinit var optionsSwipeToRefreshMenuItem: MenuItem
309 private lateinit var optionsUltraListMenuItem: MenuItem
310 private lateinit var optionsUltraPrivacyMenuItem: MenuItem
311 private lateinit var optionsUserAgentChromeOnAndroidMenuItem: MenuItem
312 private lateinit var optionsUserAgentChromeOnWindowsMenuItem: MenuItem
313 private lateinit var optionsUserAgentChromiumOnLinuxMenuItem: MenuItem
314 private lateinit var optionsUserAgentCustomMenuItem: MenuItem
315 private lateinit var optionsUserAgentEdgeOnWindowsMenuItem: MenuItem
316 private lateinit var optionsUserAgentFirefoxOnAndroidMenuItem: MenuItem
317 private lateinit var optionsUserAgentFirefoxOnLinuxMenuItem: MenuItem
318 private lateinit var optionsUserAgentFirefoxOnWindowsMenuItem: MenuItem
319 private lateinit var optionsUserAgentInternetExplorerOnWindowsMenuItem: MenuItem
320 private lateinit var optionsUserAgentMenuItem: MenuItem
321 private lateinit var optionsUserAgentPrivacyBrowserMenuItem: MenuItem
322 private lateinit var optionsUserAgentSafariOnIosMenuItem: MenuItem
323 private lateinit var optionsUserAgentSafariOnMacosMenuItem: MenuItem
324 private lateinit var optionsUserAgentWebViewDefaultMenuItem: MenuItem
325 private lateinit var optionsWideViewportMenuItem: MenuItem
326 private lateinit var proxyHelper: ProxyHelper
327 private lateinit var redColorSpan: ForegroundColorSpan
328 private lateinit var rootFrameLayout: FrameLayout
329 private lateinit var saveUrlString: String
330 private lateinit var searchURL: String
331 private lateinit var sharedPreferences: SharedPreferences
332 private lateinit var swipeRefreshLayout: SwipeRefreshLayout
333 private lateinit var tabLayout: TabLayout
334 private lateinit var tabsLinearLayout: LinearLayout
335 private lateinit var toolbar: Toolbar
336 private lateinit var webViewDefaultUserAgent: String
337 private lateinit var webViewThemeEntryValuesStringArray: Array<String>
338 private lateinit var webViewViewPager2: ViewPager2
339 private lateinit var ultraList: ArrayList<List<Array<String>>>
340 private lateinit var urlEditText: EditText
341 private lateinit var urlRelativeLayout: RelativeLayout
342 private lateinit var userAgentDataArray: Array<String>
343 private lateinit var userAgentNamesArray: ArrayAdapter<CharSequence>
345 // Define the class variables.
346 private var actionBarDrawerToggle: ActionBarDrawerToggle? = null
347 private var appBarHeight = 0
348 private var bookmarksCursor: Cursor? = null
349 private var bookmarksDatabaseHelper: BookmarksDatabaseHelper? = null
350 private var bookmarksDrawerPinned = false
351 private var bottomAppBar = false
352 private var currentWebView: NestedScrollWebView? = null
353 private var defaultBlockAllThirdPartyRequests = false
354 private var defaultCookies = false
355 private var defaultDisplayWebpageImages = true
356 private var defaultDomStorage = false
357 private var defaultEasyList = true
358 private var defaultEasyPrivacy = true
359 private var defaultFanboysAnnoyanceList = true
360 private var defaultFanboysSocialBlockingList = true
361 private var defaultFormData = false // Form data can be removed once the minimum API >= 26.
362 private var defaultProgressViewEndOffset = 0
363 private var defaultProgressViewStartOffset = 0
364 private var defaultJavaScript = false
365 private var defaultSwipeToRefresh = true
366 private var defaultUltraList = true
367 private var defaultUltraPrivacy = true
368 private var defaultWideViewport = true
369 private var displayAdditionalAppBarIcons = false
370 private var displayingFullScreenVideo = false
371 private var domainsDatabaseHelper: DomainsDatabaseHelper? = null
372 private var downloadWithExternalApp = false
373 private var fullScreenBrowsingModeEnabled = false
374 private var hideAppBar = false
375 private var inFullScreenBrowsingMode = false
376 private var incognitoModeEnabled = false
377 private var loadingNewIntent = false
378 private var objectAnimator = ObjectAnimator()
379 private var optionsMenu: Menu? = null
380 private var orbotStatusBroadcastReceiver: BroadcastReceiver? = null
381 private var reapplyAppSettingsOnRestart = false
382 private var reapplyDomainSettingsOnRestart = false
383 private var sanitizeAmpRedirects = false
384 private var sanitizeTrackingQueries = false
385 private var savedProxyMode: String? = null
386 private var savedNestedScrollWebViewStateArrayList: ArrayList<Bundle>? = null
387 private var savedStateArrayList: ArrayList<Bundle>? = null
388 private var savedTabPosition = 0
389 private var scrollAppBar = false
390 private var ultraPrivacy: ArrayList<List<Array<String>>>? = null
391 private var waitingForProxy = false
393 // Define the save webpage image activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
394 private val browseFileUploadActivityResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { activityResult ->
395 // Pass the file to the WebView.
396 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(activityResult.resultCode, activityResult.data))
399 // Define the save URL activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
400 private val saveUrlActivityResultLauncher = registerForActivityResult<String, Uri>(ActivityResultContracts.CreateDocument("*/*")) { fileUri ->
401 // Only save the URL if the file URI is not null, which happens if the user exited the file picker by pressing back.
402 if (fileUri != null) {
403 // Instantiate the save URL coroutine.
404 val saveUrlCoroutine = SaveUrlCoroutine()
407 saveUrlCoroutine.save(this, this, saveUrlString, fileUri, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
410 // Reset the save URL string.
414 // Define the save webpage archive activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
415 private val saveWebpageArchiveActivityResultLauncher = registerForActivityResult<String, Uri>(ActivityResultContracts.CreateDocument("multipart/related")) { fileUri ->
416 // Only save the webpage archive if the file URI is not null, which happens if the user exited the file picker by pressing back.
417 if (fileUri != null) {
418 // Initialize the file name string from the file URI last path segment.
419 var fileNameString = fileUri.lastPathSegment
421 // Query the exact file name if the API >= 26.
422 if (Build.VERSION.SDK_INT >= 26) {
423 // Get a cursor from the content resolver.
424 val contentResolverCursor = contentResolver.query(fileUri, null, null, null)!!
426 // Move to the fist row.
427 contentResolverCursor.moveToFirst()
429 // Get the file name from the cursor.
430 fileNameString = contentResolverCursor.getString(contentResolverCursor.getColumnIndexOrThrow(OpenableColumns.DISPLAY_NAME))
433 contentResolverCursor.close()
436 // Use a coroutine to save the file.
437 CoroutineScope(Dispatchers.Main).launch {
439 // Create the file on the IO thread.
440 withContext(Dispatchers.IO) {
441 // Create a temporary MHT file.
442 val temporaryMhtFile = File.createTempFile(TEMPORARY_MHT_FILE, ".mht", cacheDir)
444 // The WebView must be accessed from the main thread.
445 withContext(Dispatchers.Main) {
446 currentWebView!!.saveWebArchive(temporaryMhtFile.toString(), false) { callbackValue ->
447 if (callbackValue != null) { // The temporary MHT file was saved successfully.
449 // Create a temporary MHT file input stream.
450 val temporaryMhtFileInputStream = FileInputStream(temporaryMhtFile)
452 // Get an output stream for the save webpage file path.
453 val mhtOutputStream = contentResolver.openOutputStream(fileUri)!!
455 // Create a transfer byte array.
456 val transferByteArray = ByteArray(1024)
458 // Create an integer to track the number of bytes read.
461 // Copy the temporary MHT file input stream to the MHT output stream.
462 while (temporaryMhtFileInputStream.read(transferByteArray).also { bytesRead = it } > 0)
463 mhtOutputStream.write(transferByteArray, 0, bytesRead)
465 // Close the streams.
466 mhtOutputStream.close()
467 temporaryMhtFileInputStream.close()
469 // Display a snackbar.
470 Snackbar.make(currentWebView!!, getString(R.string.saved, fileNameString), Snackbar.LENGTH_SHORT).show()
471 } catch (exception: Exception) {
472 // Display snackbar with the exception.
473 Snackbar.make(currentWebView!!, getString(R.string.error_saving_file, fileNameString, exception), Snackbar.LENGTH_INDEFINITE).show()
475 // Delete the temporary MHT file.
476 temporaryMhtFile.delete()
478 } else { // There was an unspecified error while saving the temporary MHT file.
479 // Display a snackbar.
480 Snackbar.make(currentWebView!!, getString(R.string.error_saving_file, fileNameString, getString(R.string.unknown_error)), Snackbar.LENGTH_INDEFINITE).show()
485 } catch (ioException: IOException) {
486 // Display a snackbar with the IO exception.
487 Snackbar.make(currentWebView!!, getString(R.string.error_saving_file, fileNameString, ioException), Snackbar.LENGTH_INDEFINITE).show()
493 // Define the save webpage image activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
494 private val saveWebpageImageActivityResultLauncher = registerForActivityResult<String, Uri>(ActivityResultContracts.CreateDocument("image/png")) { fileUri ->
495 // Only save the webpage image if the file URI is not null, which happens if the user exited the file picker by pressing back.
496 if (fileUri != null) {
497 // Instantiate the save webpage image coroutine.
498 val saveWebpageImageCoroutine = SaveWebpageImageCoroutine()
500 // Save the webpage image.
501 saveWebpageImageCoroutine.save(this, fileUri, currentWebView!!)
505 override fun onCreate(savedInstanceState: Bundle?) {
506 // Run the default commands.
507 super.onCreate(savedInstanceState)
509 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
510 PreferenceManager.setDefaultValues(this, R.xml.preferences, false)
512 // Get a handle for the shared preferences.
513 sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
515 // Get the preferences.
516 val appTheme = sharedPreferences.getString(getString(R.string.app_theme_key), getString(R.string.app_theme_default_value))
517 val allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false)
518 bottomAppBar = sharedPreferences.getBoolean(getString(R.string.bottom_app_bar_key), false)
519 displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false)
521 // Get the theme entry values string array.
522 val appThemeEntryValuesStringArray = resources.getStringArray(R.array.app_theme_entry_values)
524 // Get the current theme status.
525 val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
527 // Set the app theme according to the preference. A switch statement cannot be used because the theme entry values string array is not a compile time constant.
528 if (appTheme == appThemeEntryValuesStringArray[1]) { // The light theme is selected.
529 // Apply the light theme.
530 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
531 } else if (appTheme == appThemeEntryValuesStringArray[2]) { // The dark theme is selected.
532 // Apply the dark theme.
533 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
534 } else { // The system default theme is selected.
535 if (Build.VERSION.SDK_INT >= 28) { // The system default theme is supported.
536 // Follow the system default theme.
537 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
538 } else { // The system default theme is not supported.
539 // Follow the battery saver mode.
540 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY)
544 // Do not continue if the app theme is different than the OS theme. The app always initially starts in the OS theme.
545 // If the user has specified the opposite theme should be used, the app will restart in that mode after the above `setDefaultNightMode()` code processes. However, the restart is delayed.
546 // If the filter list coroutine starts below it will continue to run during the restart, which leads to indeterminate behavior, with the system often not knowing how many tabs exist.
547 // See https://redmine.stoutner.com/issues/952.
548 if ((appTheme == appThemeEntryValuesStringArray[0]) || // The system default theme is used.
549 ((appTheme == appThemeEntryValuesStringArray[1]) && (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO)) || // The app is running in day theme as desired.
550 ((appTheme == appThemeEntryValuesStringArray[2]) && (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES))) { // The app is running in night theme as desired.
552 // Disable screenshots if not allowed.
553 if (!allowScreenshots) {
554 window.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
557 // Check to see if the activity has been restarted.
558 if (savedInstanceState != null) {
559 // Store the saved instance state variables. The deprecated `getParcelableArrayList` can be upgraded once the minimum API >= 33.
560 bookmarksDrawerPinned = savedInstanceState.getBoolean(BOOKMARKS_DRAWER_PINNED)
561 @Suppress("DEPRECATION")
562 savedStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_STATE_ARRAY_LIST)
563 @Suppress("DEPRECATION")
564 savedNestedScrollWebViewStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST)
565 savedTabPosition = savedInstanceState.getInt(SAVED_TAB_POSITION)
566 savedProxyMode = savedInstanceState.getString(PROXY_MODE)
569 // Enable the drawing of the entire webpage. This makes it possible to save a website image. This must be done before anything else happens with the WebView.
570 WebView.enableSlowWholeDocumentDraw()
572 // Set the content view according to the position of the app bar.
574 setContentView(R.layout.main_framelayout_bottom_appbar)
576 setContentView(R.layout.main_framelayout_top_appbar)
578 // Get handles for the views.
579 rootFrameLayout = findViewById(R.id.root_framelayout)
580 drawerLayout = findViewById(R.id.drawerlayout)
581 coordinatorLayout = findViewById(R.id.coordinatorlayout)
582 appBarLayout = findViewById(R.id.appbar_layout)
583 toolbar = findViewById(R.id.toolbar)
584 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout)
585 findOnPageEditText = findViewById(R.id.find_on_page_edittext)
586 findOnPageCountTextView = findViewById(R.id.find_on_page_count_textview)
587 tabsLinearLayout = findViewById(R.id.tabs_linearlayout)
588 tabLayout = findViewById(R.id.tablayout)
589 swipeRefreshLayout = findViewById(R.id.swiperefreshlayout)
590 webViewViewPager2 = findViewById(R.id.webview_viewpager2)
591 val navigationView = findViewById<NavigationView>(R.id.navigationview)
592 bookmarksListView = findViewById(R.id.bookmarks_drawer_listview)
593 bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview)
594 bookmarksDrawerPinnedImageView = findViewById(R.id.bookmarks_drawer_pinned_imageview)
595 fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout)
597 // Get a handle for the navigation menu.
598 val navigationMenu = navigationView.menu
600 // Get handles for the navigation menu items.
601 navigationBackMenuItem = navigationMenu.findItem(R.id.back)
602 navigationForwardMenuItem = navigationMenu.findItem(R.id.forward)
603 navigationHistoryMenuItem = navigationMenu.findItem(R.id.history)
604 navigationRequestsMenuItem = navigationMenu.findItem(R.id.requests)
606 // Listen for touches on the navigation menu.
607 navigationView.setNavigationItemSelectedListener(this)
609 // Set the support action bar.
610 setSupportActionBar(toolbar)
612 // Get a handle for the app bar.
613 appBar = supportActionBar!!
615 // Set the custom app bar layout, which shows the URL text bar.
616 appBar.setCustomView(R.layout.url_app_bar)
618 // Display the custom app bar layout.
619 appBar.displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM
621 // Get handles for the views in the URL app bar.
622 urlRelativeLayout = findViewById(R.id.url_relativelayout)
623 urlEditText = findViewById(R.id.url_edittext)
625 // Create the hamburger icon at the start of the AppBar.
626 actionBarDrawerToggle = ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer)
628 // Initially disable the sliding drawers. They will be enabled once the filter lists are loaded.
629 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
631 // Initially hide the user interface so that only the filter list loading screen is shown (if reloading).
632 drawerLayout.visibility = View.GONE
634 // Initialize the WebView state adapter.
635 webViewStateAdapter = WebViewStateAdapter(this)
637 // Set the pager adapter on the web view pager.
638 webViewViewPager2.adapter = webViewStateAdapter
640 // Store up to 100 tabs in memory.
641 webViewViewPager2.offscreenPageLimit = 100
643 // Disable swiping between pages in the view pager.
644 webViewViewPager2.isUserInputEnabled = false
646 // Get a handle for the cookie manager.
647 cookieManager = CookieManager.getInstance()
649 // Instantiate the helpers.
650 bookmarksDatabaseHelper = BookmarksDatabaseHelper(this)
651 domainsDatabaseHelper = DomainsDatabaseHelper(this)
652 proxyHelper = ProxyHelper()
654 // Update the bookmarks drawer pinned image view.
655 updateBookmarksDrawerPinnedImageView()
657 // Initialize the app.
660 // Apply the app settings from the shared preferences.
663 // Control what the system back command does.
664 val onBackPressedCallback: OnBackPressedCallback = object : OnBackPressedCallback(true) {
665 override fun handleOnBackPressed() {
666 // Process the different back options.
667 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
668 // Close the navigation drawer.
669 drawerLayout.closeDrawer(GravityCompat.START)
670 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)) { // The bookmarks drawer is open.
671 // close the bookmarks drawer.
672 drawerLayout.closeDrawer(GravityCompat.END)
673 } else if (displayingFullScreenVideo) { // A full screen video is shown.
674 // Exit the full screen video.
675 exitFullScreenVideo()
676 // It shouldn't be possible for the currentWebView to be null, but crash logs indicate it sometimes happens.
677 } else if (currentWebView != null && currentWebView!!.canGoBack()) { // There is at least one item in the current WebView history.
678 // Get the current web back forward list.
679 val webBackForwardList = currentWebView!!.copyBackForwardList()
681 // Get the previous entry URL.
682 val previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex - 1).url
684 // Apply the domain settings.
685 applyDomainSettings(currentWebView!!, previousUrl, resetTab = false, reloadWebsite = false, loadUrl = false)
688 currentWebView!!.goBack()
689 } else { // Close the current tab.
690 // A view is required because the method is also called by an XML `onClick`.
696 // Register the on back pressed callback.
697 onBackPressedDispatcher.addCallback(this, onBackPressedCallback)
699 // Instantiate the populate filter lists coroutine.
700 val populateFilterListsCoroutine = PopulateFilterListsCoroutine(this)
702 // Populate the filter lists.
703 populateFilterListsCoroutine.populateFilterLists(this)
707 public override fun onPostCreate(savedInstanceState: Bundle?) {
708 // Run the default commands.
709 super.onPostCreate(savedInstanceState)
711 // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished. This creates the navigation drawer icon.
712 // If the app is restarting to change the app theme the action bar drawer toggle will not yet be populated.
713 actionBarDrawerToggle?.syncState()
716 override fun onNewIntent(intent: Intent) {
717 // Run the default commands.
718 super.onNewIntent(intent)
720 // Get the information from the intent.
721 val intentAction = intent.action
722 val intentUriData = intent.data
723 val intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT)
725 // Determine if this is a web search.
726 val isWebSearch = (intentAction != null) && (intentAction == Intent.ACTION_WEB_SEARCH)
728 // Check to see if the app is being restarted from a saved state.
729 if (ultraPrivacy != null) { // The activity is not being restarted from a saved state.
730 // 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.
731 if ((intentUriData != null) || (intentStringExtra != null) || isWebSearch) {
732 // Exit the full screen video if it is displayed.
733 if (displayingFullScreenVideo) {
734 // Exit full screen video mode.
735 exitFullScreenVideo()
737 // Reload the current WebView. Otherwise, it can display entirely black.
738 currentWebView!!.reload()
742 val url = if (isWebSearch) { // The intent is a web search.
743 // Sanitize the search input and convert it to a search.
744 val encodedSearchString = try {
745 URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8")
746 } catch (exception: UnsupportedEncodingException) {
750 // Add the base search URL.
751 searchURL + encodedSearchString
752 } else { // The intent contains a URL in either the data or an extra.
753 intentUriData?.toString() ?: intentStringExtra
756 // Add a new tab if specified in the preferences.
757 if (sharedPreferences.getBoolean(getString(R.string.open_intents_in_new_tab_key), true)) { // Load the URL in a new tab.
758 // Set the loading new intent flag.
759 loadingNewIntent = true
762 addNewTab(url!!, true)
763 } else { // Load the URL in the current tab.
765 loadUrl(currentWebView!!, url!!)
768 // Close the navigation drawer if it is open.
769 if (drawerLayout.isDrawerVisible(GravityCompat.START))
770 drawerLayout.closeDrawer(GravityCompat.START)
772 // Close the bookmarks drawer if it is open.
773 if (drawerLayout.isDrawerVisible(GravityCompat.END))
774 drawerLayout.closeDrawer(GravityCompat.END)
776 } else { // The app has been restarted.
777 // If the new intent will open a new tab, set the saved tab position to be the size of the saved state array list.
778 // The tab position is 0 based, meaning the new tab will be the tab position that is restored.
779 if ((intentUriData != null) || (intentStringExtra != null) || isWebSearch)
780 savedTabPosition = savedStateArrayList!!.size
782 // Replace the intent that started the app with this one. This will load the tab after the others have been restored.
787 public override fun onRestart() {
788 // Run the default commands.
791 // Apply the app settings if returning from the Settings activity.
792 if (reapplyAppSettingsOnRestart) {
793 // Reset the reapply app settings on restart flag.
794 reapplyAppSettingsOnRestart = false
796 // Apply the app settings.
800 // Apply the domain settings if returning from the settings or domains activity.
801 if (reapplyDomainSettingsOnRestart) {
802 // Reset the reapply domain settings on restart flag.
803 reapplyDomainSettingsOnRestart = false
805 // Update the domains settings set.
806 updateDomainsSettingsSet()
808 // Reapply the domain settings for each tab.
809 for (i in 0 until webViewStateAdapter!!.itemCount) {
810 // Get the WebView tab fragment.
811 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
813 // Get the fragment view.
814 val fragmentView = webViewTabFragment.view
816 // Only reload the WebViews if they exist.
817 if (fragmentView != null) {
818 // Get the nested scroll WebView from the tab fragment.
819 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
821 // Reset the current domain name so the domain settings will be reapplied.
822 nestedScrollWebView.currentDomainName = ""
824 // Reapply the domain settings if the URL is not null, which happens for empty tabs when returning from settings.
825 if (nestedScrollWebView.url != null)
826 applyDomainSettings(nestedScrollWebView, nestedScrollWebView.url, resetTab = false, reloadWebsite = true, loadUrl = false)
831 // Update the bookmarks drawer if returning from the Bookmarks activity.
832 if (restartFromBookmarksActivity) {
833 // Reset the restart from bookmarks activity flag.
834 restartFromBookmarksActivity = false
836 // Close the bookmarks drawer.
837 drawerLayout.closeDrawer(GravityCompat.END)
839 // Reload the bookmarks drawer.
840 loadBookmarksFolder()
843 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
844 updatePrivacyIcons(true)
847 // `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.
848 public override fun onStart() {
849 // Run the default commands.
852 // 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.
853 if (webViewStateAdapter != null) {
854 for (i in 0 until webViewStateAdapter!!.itemCount) {
855 // Get the WebView tab fragment.
856 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
858 // Get the fragment view.
859 val fragmentView = webViewTabFragment.view
861 // Only resume the WebViews if they exist (they won't when the app is first created).
862 if (fragmentView != null) {
863 // Get the nested scroll WebView from the tab fragment.
864 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
866 // Resume the nested scroll WebView.
867 nestedScrollWebView.onResume()
872 // Resume the nested scroll WebView JavaScript timers. This is a global command that resumes JavaScript timers on all WebViews.
873 if (currentWebView != null)
874 currentWebView!!.resumeTimers()
876 // Reapply the proxy settings if the system is using a proxy. This redisplays the appropriate alert dialog.
877 if (proxyMode != ProxyHelper.NONE)
880 // Reapply any system UI flags.
881 if (displayingFullScreenVideo || inFullScreenBrowsingMode) { // The system is displaying a website or a video in full screen mode.
882 /* Hide the system bars.
883 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
884 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
885 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
886 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
889 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
890 @Suppress("DEPRECATION")
891 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
894 // Show any pending dialogs.
895 for (i in pendingDialogsArrayList.indices) {
896 // Get the pending dialog from the array list.
897 val (dialogFragment, tag) = pendingDialogsArrayList[i]
899 // Show the pending dialog.
900 dialogFragment.show(supportFragmentManager, tag)
903 // Clear the pending dialogs array list.
904 pendingDialogsArrayList.clear()
907 public override fun onSaveInstanceState(savedInstanceState: Bundle) {
908 // Run the default commands.
909 super.onSaveInstanceState(savedInstanceState)
911 // 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.
912 if (webViewStateAdapter != null) {
913 // Initialize the saved state array lists.
914 savedStateArrayList = ArrayList<Bundle>()
915 savedNestedScrollWebViewStateArrayList = ArrayList<Bundle>()
917 // Get the URLs from each tab.
918 for (i in 0 until webViewStateAdapter!!.itemCount) {
919 // Get the WebView tab fragment.
920 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
922 // Get the fragment view.
923 val fragmentView = webViewTabFragment.view
925 // Save the fragment state if it is not null.
926 if (fragmentView != null) {
927 // Get the nested scroll WebView from the tab fragment.
928 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
930 // Create the saved state bundle.
931 val savedStateBundle = Bundle()
933 // Get the current states.
934 nestedScrollWebView.saveState(savedStateBundle)
935 val savedNestedScrollWebViewStateBundle = nestedScrollWebView.saveNestedScrollWebViewState()
937 // Store the saved states in the array lists.
938 savedStateArrayList!!.add(savedStateBundle)
939 savedNestedScrollWebViewStateArrayList!!.add(savedNestedScrollWebViewStateBundle)
943 // Get the current tab position.
944 val currentTabPosition = tabLayout.selectedTabPosition
946 // Store the saved states in the bundle.
947 savedInstanceState.putBoolean(BOOKMARKS_DRAWER_PINNED, bookmarksDrawerPinned)
948 savedInstanceState.putString(PROXY_MODE, proxyMode)
949 savedInstanceState.putParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST, savedNestedScrollWebViewStateArrayList)
950 savedInstanceState.putParcelableArrayList(SAVED_STATE_ARRAY_LIST, savedStateArrayList)
951 savedInstanceState.putInt(SAVED_TAB_POSITION, currentTabPosition)
955 // `onStop()` runs after `onPause()`. It is used instead of `onPause()` so the commands are not called every time the screen is partially hidden.
956 public override fun onStop() {
957 // Run the default commands.
960 // 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.
961 if (webViewStateAdapter != null) {
962 // Pause each web view.
963 for (i in 0 until webViewStateAdapter!!.itemCount) {
964 // Get the WebView tab fragment.
965 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
967 // Get the fragment view.
968 val fragmentView = webViewTabFragment.view
970 // Only pause the WebViews if they exist (they won't when the app is first created).
971 if (fragmentView != null) {
972 // Get the nested scroll WebView from the tab fragment.
973 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
975 // Pause the nested scroll WebView.
976 nestedScrollWebView.onPause()
981 // Pause the WebView JavaScript timers. This is a global command that pauses JavaScript on all WebViews.
982 if (currentWebView != null)
983 currentWebView!!.pauseTimers()
986 public override fun onDestroy() {
987 // Unregister the orbot status broadcast receiver if it exists.
988 if (orbotStatusBroadcastReceiver != null) {
989 unregisterReceiver(orbotStatusBroadcastReceiver)
992 // Close the bookmarks cursor if it exists.
993 bookmarksCursor?.close()
995 // Close the databases if they exist.
996 bookmarksDatabaseHelper?.close()
997 domainsDatabaseHelper?.close()
999 // Run the default commands.
1003 override fun onConfigurationChanged(newConfig: Configuration) {
1004 // Run the default commands.
1005 super.onConfigurationChanged(newConfig)
1007 // Get the current page.
1008 val currentPage = webViewViewPager2.currentItem
1010 // Toggle the pages if there is more than one so that the view pager will recalculate their size.
1011 if (currentPage > 0) {
1012 // Switch to the previous page.
1013 webViewViewPager2.currentItem = (currentPage - 1)
1015 // Switch back to the current page after the view pager has quiesced.
1016 webViewViewPager2.post { webViewViewPager2.currentItem = currentPage }
1020 override fun onCreateOptionsMenu(menu: Menu): Boolean {
1021 // Inflate the menu. This adds items to the app bar if it is present.
1022 menuInflater.inflate(R.menu.webview_options_menu, menu)
1024 // Get handles for the menu items.
1025 optionsPrivacyMenuItem = menu.findItem(R.id.javascript)
1026 optionsRefreshMenuItem = menu.findItem(R.id.refresh)
1027 val optionsBookmarksMenuItem = menu.findItem(R.id.bookmarks)
1028 optionsCookiesMenuItem = menu.findItem(R.id.cookies)
1029 optionsDomStorageMenuItem = menu.findItem(R.id.dom_storage)
1030 optionsSaveFormDataMenuItem = menu.findItem(R.id.save_form_data) // Form data can be removed once the minimum API >= 26.
1031 optionsClearDataMenuItem = menu.findItem(R.id.clear_data)
1032 optionsClearCookiesMenuItem = menu.findItem(R.id.clear_cookies)
1033 optionsClearDomStorageMenuItem = menu.findItem(R.id.clear_dom_storage)
1034 optionsClearFormDataMenuItem = menu.findItem(R.id.clear_form_data) // Form data can be removed once the minimum API >= 26.
1035 optionsEasyListMenuItem = menu.findItem(R.id.easylist)
1036 optionsEasyPrivacyMenuItem = menu.findItem(R.id.easyprivacy)
1037 optionsFanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list)
1038 optionsFanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list)
1039 optionsFilterListsMenuItem = menu.findItem(R.id.filterlists)
1040 optionsUltraListMenuItem = menu.findItem(R.id.ultralist)
1041 optionsUltraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy)
1042 optionsBlockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests)
1043 optionsProxyMenuItem = menu.findItem(R.id.proxy)
1044 optionsProxyNoneMenuItem = menu.findItem(R.id.proxy_none)
1045 optionsProxyTorMenuItem = menu.findItem(R.id.proxy_tor)
1046 optionsProxyI2pMenuItem = menu.findItem(R.id.proxy_i2p)
1047 optionsProxyCustomMenuItem = menu.findItem(R.id.proxy_custom)
1048 optionsUserAgentMenuItem = menu.findItem(R.id.user_agent)
1049 optionsUserAgentPrivacyBrowserMenuItem = menu.findItem(R.id.user_agent_privacy_browser)
1050 optionsUserAgentWebViewDefaultMenuItem = menu.findItem(R.id.user_agent_webview_default)
1051 optionsUserAgentFirefoxOnAndroidMenuItem = menu.findItem(R.id.user_agent_firefox_on_android)
1052 optionsUserAgentChromeOnAndroidMenuItem = menu.findItem(R.id.user_agent_chrome_on_android)
1053 optionsUserAgentSafariOnIosMenuItem = menu.findItem(R.id.user_agent_safari_on_ios)
1054 optionsUserAgentFirefoxOnLinuxMenuItem = menu.findItem(R.id.user_agent_firefox_on_linux)
1055 optionsUserAgentChromiumOnLinuxMenuItem = menu.findItem(R.id.user_agent_chromium_on_linux)
1056 optionsUserAgentFirefoxOnWindowsMenuItem = menu.findItem(R.id.user_agent_firefox_on_windows)
1057 optionsUserAgentChromeOnWindowsMenuItem = menu.findItem(R.id.user_agent_chrome_on_windows)
1058 optionsUserAgentEdgeOnWindowsMenuItem = menu.findItem(R.id.user_agent_edge_on_windows)
1059 optionsUserAgentInternetExplorerOnWindowsMenuItem = menu.findItem(R.id.user_agent_internet_explorer_on_windows)
1060 optionsUserAgentSafariOnMacosMenuItem = menu.findItem(R.id.user_agent_safari_on_macos)
1061 optionsUserAgentCustomMenuItem = menu.findItem(R.id.user_agent_custom)
1062 optionsSwipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh)
1063 optionsWideViewportMenuItem = menu.findItem(R.id.wide_viewport)
1064 optionsDisplayImagesMenuItem = menu.findItem(R.id.display_images)
1065 optionsDarkWebViewMenuItem = menu.findItem(R.id.dark_webview)
1066 optionsFontSizeMenuItem = menu.findItem(R.id.font_size)
1067 optionsAddOrEditDomainMenuItem = menu.findItem(R.id.add_or_edit_domain)
1069 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1070 updatePrivacyIcons(false)
1072 // Only display the form data menu items if the API < 26.
1073 optionsSaveFormDataMenuItem.isVisible = Build.VERSION.SDK_INT < 26
1074 optionsClearFormDataMenuItem.isVisible = Build.VERSION.SDK_INT < 26
1076 // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
1077 optionsClearFormDataMenuItem.isEnabled = Build.VERSION.SDK_INT < 26
1079 // 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.
1080 if (displayAdditionalAppBarIcons) { // Display the additional icons.
1081 optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
1082 optionsBookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM)
1083 optionsCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM)
1084 } else { //Do not display the additional icons.
1085 optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER)
1086 optionsBookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER)
1087 optionsCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER)
1090 // Replace `Refresh` with `Stop` if a URL is already loading.
1091 if ((currentWebView != null) && (currentWebView!!.progress != 100)) {
1093 optionsRefreshMenuItem.setTitle(R.string.stop)
1095 // 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.
1096 if (displayAdditionalAppBarIcons)
1097 optionsRefreshMenuItem.setIcon(R.drawable.close_blue)
1100 // Store a handle for the options menu.
1107 override fun onPrepareOptionsMenu(menu: Menu): Boolean {
1108 // Initialize the current user agent string and the font size.
1109 var currentUserAgent = getString(R.string.user_agent_privacy_browser)
1112 // 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.
1113 if (currentWebView != null) {
1114 // Set the add or edit domain text.
1115 if (currentWebView!!.domainSettingsApplied)
1116 optionsAddOrEditDomainMenuItem.setTitle(R.string.edit_domain_settings)
1118 optionsAddOrEditDomainMenuItem.setTitle(R.string.add_domain_settings)
1120 // Get the current user agent from the WebView.
1121 currentUserAgent = currentWebView!!.settings.userAgentString
1123 // Get the current font size from the the WebView.
1124 fontSize = currentWebView!!.settings.textZoom
1126 // Set the status of the menu item checkboxes.
1127 optionsDomStorageMenuItem.isChecked = currentWebView!!.settings.domStorageEnabled
1128 @Suppress("DEPRECATION")
1129 optionsSaveFormDataMenuItem.isChecked = currentWebView!!.settings.saveFormData // Form data can be removed once the minimum API >= 26.
1130 optionsEasyListMenuItem.isChecked = currentWebView!!.easyListEnabled
1131 optionsEasyPrivacyMenuItem.isChecked = currentWebView!!.easyPrivacyEnabled
1132 optionsFanboysAnnoyanceListMenuItem.isChecked = currentWebView!!.fanboysAnnoyanceListEnabled
1133 optionsFanboysSocialBlockingListMenuItem.isChecked = currentWebView!!.fanboysSocialBlockingListEnabled
1134 optionsUltraListMenuItem.isChecked = currentWebView!!.ultraListEnabled
1135 optionsUltraPrivacyMenuItem.isChecked = currentWebView!!.ultraPrivacyEnabled
1136 optionsBlockAllThirdPartyRequestsMenuItem.isChecked = currentWebView!!.blockAllThirdPartyRequests
1137 optionsSwipeToRefreshMenuItem.isChecked = currentWebView!!.swipeToRefresh
1138 optionsWideViewportMenuItem.isChecked = currentWebView!!.settings.useWideViewPort
1139 optionsDisplayImagesMenuItem.isChecked = currentWebView!!.settings.loadsImagesAutomatically
1141 // Initialize the display names for the filter lists with the number of blocked requests.
1142 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + currentWebView!!.getRequestsCount(BLOCKED_REQUESTS)
1143 optionsEasyListMenuItem.title = currentWebView!!.getRequestsCount(EASYLIST).toString() + " - " + getString(R.string.easylist)
1144 optionsEasyPrivacyMenuItem.title = currentWebView!!.getRequestsCount(EASYPRIVACY).toString() + " - " + getString(R.string.easyprivacy)
1145 optionsFanboysAnnoyanceListMenuItem.title = currentWebView!!.getRequestsCount(FANBOYS_ANNOYANCE_LIST).toString() + " - " + getString(R.string.fanboys_annoyance_list)
1146 optionsFanboysSocialBlockingListMenuItem.title = currentWebView!!.getRequestsCount(FANBOYS_SOCIAL_BLOCKING_LIST).toString() + " - " + getString(R.string.fanboys_social_blocking_list)
1147 optionsUltraListMenuItem.title = currentWebView!!.getRequestsCount(com.stoutner.privacybrowser.views.ULTRALIST).toString() + " - " + getString(R.string.ultralist)
1148 optionsUltraPrivacyMenuItem.title = currentWebView!!.getRequestsCount(ULTRAPRIVACY).toString() + " - " + getString(R.string.ultraprivacy)
1149 optionsBlockAllThirdPartyRequestsMenuItem.title = currentWebView!!.getRequestsCount(THIRD_PARTY_REQUESTS).toString() + " - " + getString(R.string.block_all_third_party_requests)
1151 // Enable DOM Storage if JavaScript is enabled.
1152 optionsDomStorageMenuItem.isEnabled = currentWebView!!.settings.javaScriptEnabled
1154 // Get the current theme status.
1155 val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
1157 // Enable dark WebView if night mode is enabled.
1158 optionsDarkWebViewMenuItem.isEnabled = (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES)
1160 // Set the checkbox status for dark WebView if algorithmic darkening is supported.
1161 if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING))
1162 optionsDarkWebViewMenuItem.isChecked = WebSettingsCompat.isAlgorithmicDarkeningAllowed(currentWebView!!.settings)
1165 // Set the cookies menu item checked status.
1166 optionsCookiesMenuItem.isChecked = cookieManager.acceptCookie()
1168 // Enable Clear Cookies if there are any.
1169 optionsClearCookiesMenuItem.isEnabled = cookieManager.hasCookies()
1171 // 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`.
1172 val privateDataDirectoryString = applicationInfo.dataDir
1174 // Get the storage directories.
1175 val localStorageDirectory = File("$privateDataDirectoryString/app_webview/Local Storage/")
1176 val indexedDBDirectory = File("$privateDataDirectoryString/app_webview/IndexedDB")
1178 // Initialize the number of files counters.
1179 var localStorageDirectoryNumberOfFiles = 0
1180 var indexedDBDirectoryNumberOfFiles = 0
1182 // 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.
1183 if (localStorageDirectory.exists())
1184 localStorageDirectoryNumberOfFiles = (localStorageDirectory.list())?.size ?: 0
1186 // Get a count of the number of files in the IndexedDB directory. The list can be null, in which case a `0` is returned.
1187 if (indexedDBDirectory.exists())
1188 indexedDBDirectoryNumberOfFiles = (indexedDBDirectory.list())?.size ?: 0
1190 // Enable Clear DOM Storage if there is any.
1191 optionsClearDomStorageMenuItem.isEnabled = localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0
1193 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
1194 if (Build.VERSION.SDK_INT < 26) {
1195 // Get the WebView database.
1196 val webViewDatabase = WebViewDatabase.getInstance(this)
1198 // Enable the clear form data menu item if there is anything to clear.
1199 @Suppress("DEPRECATION")
1200 optionsClearFormDataMenuItem.isEnabled = webViewDatabase.hasFormData()
1203 // Enable Clear Data if any of the submenu items are enabled.
1204 optionsClearDataMenuItem.isEnabled = (optionsClearCookiesMenuItem.isEnabled || optionsClearDomStorageMenuItem.isEnabled || optionsClearFormDataMenuItem.isEnabled)
1206 // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
1207 optionsFanboysSocialBlockingListMenuItem.isEnabled = !optionsFanboysAnnoyanceListMenuItem.isChecked
1209 // Set the proxy title and check the applied proxy.
1211 ProxyHelper.NONE -> {
1212 // Set the proxy title.
1213 optionsProxyMenuItem.title = getString(R.string.proxy) + " - " + getString(R.string.proxy_none)
1215 // Check the proxy None radio button.
1216 optionsProxyNoneMenuItem.isChecked = true
1219 ProxyHelper.TOR -> {
1220 // Set the proxy title.
1221 optionsProxyMenuItem.title = getString(R.string.proxy) + " - " + getString(R.string.proxy_tor)
1223 // Check the proxy Tor radio button.
1224 optionsProxyTorMenuItem.isChecked = true
1227 ProxyHelper.I2P -> {
1228 // Set the proxy title.
1229 optionsProxyMenuItem.title = getString(R.string.proxy) + " - " + getString(R.string.proxy_i2p)
1231 // Check the proxy I2P radio button.
1232 optionsProxyI2pMenuItem.isChecked = true
1235 ProxyHelper.CUSTOM -> {
1236 // Set the proxy title.
1237 optionsProxyMenuItem.title = getString(R.string.proxy) + " - " + getString(R.string.proxy_custom)
1239 // Check the proxy Custom radio button.
1240 optionsProxyCustomMenuItem.isChecked = true
1244 // Select the current user agent menu item.
1245 when (currentUserAgent) {
1246 resources.getStringArray(R.array.user_agent_data)[0] -> { // Privacy Browser.
1247 // Update the user agent menu item title.
1248 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_privacy_browser)
1250 // Select the Privacy Browser radio box.
1251 optionsUserAgentPrivacyBrowserMenuItem.isChecked = true
1254 webViewDefaultUserAgent -> { // WebView Default.
1255 // Update the user agent menu item title.
1256 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_webview_default)
1258 // Select the WebView Default radio box.
1259 optionsUserAgentWebViewDefaultMenuItem.isChecked = true
1262 resources.getStringArray(R.array.user_agent_data)[2] -> { // Firefox on Android.
1263 // Update the user agent menu item title.
1264 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_android)
1266 // Select the Firefox on Android radio box.
1267 optionsUserAgentFirefoxOnAndroidMenuItem.isChecked = true
1270 resources.getStringArray(R.array.user_agent_data)[3] -> { // Chrome on Android.
1271 // Update the user agent menu item title.
1272 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_android)
1274 // Select the Chrome on Android radio box.
1275 optionsUserAgentChromeOnAndroidMenuItem.isChecked = true
1278 resources.getStringArray(R.array.user_agent_data)[4] -> { // Safari on iOS.
1279 // Update the user agent menu item title.
1280 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_ios)
1282 // Select the Safari on iOS radio box.
1283 optionsUserAgentSafariOnIosMenuItem.isChecked = true
1286 resources.getStringArray(R.array.user_agent_data)[5] -> { // Firefox on Linux.
1287 // Update the user agent menu item title.
1288 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_linux)
1290 // Select the Firefox on Linux radio box.
1291 optionsUserAgentFirefoxOnLinuxMenuItem.isChecked = true
1294 resources.getStringArray(R.array.user_agent_data)[6] -> { // Chromium on Linux.
1295 // Update the user agent menu item title.
1296 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chromium_on_linux)
1298 // Select the Chromium on Linux radio box.
1299 optionsUserAgentChromiumOnLinuxMenuItem.isChecked = true
1302 resources.getStringArray(R.array.user_agent_data)[7] -> { // Firefox on Windows.
1303 // Update the user agent menu item title.
1304 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_windows)
1306 // Select the Firefox on Windows radio box.
1307 optionsUserAgentFirefoxOnWindowsMenuItem.isChecked = true
1310 resources.getStringArray(R.array.user_agent_data)[8] -> { // Chrome on Windows.
1311 // Update the user agent menu item title.
1312 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_windows)
1314 // Select the Chrome on Windows radio box.
1315 optionsUserAgentChromeOnWindowsMenuItem.isChecked = true
1318 resources.getStringArray(R.array.user_agent_data)[9] -> { // Edge on Windows.
1319 // Update the user agent menu item title.
1320 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_edge_on_windows)
1322 // Select the Edge on Windows radio box.
1323 optionsUserAgentEdgeOnWindowsMenuItem.isChecked = true
1326 resources.getStringArray(R.array.user_agent_data)[10] -> { // Internet Explorer on Windows.
1327 // Update the user agent menu item title.
1328 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_internet_explorer_on_windows)
1330 // Select the Internet on Windows radio box.
1331 optionsUserAgentInternetExplorerOnWindowsMenuItem.isChecked = true
1334 resources.getStringArray(R.array.user_agent_data)[11] -> { // Safari on macOS.
1335 // Update the user agent menu item title.
1336 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_macos)
1338 // Select the Safari on macOS radio box.
1339 optionsUserAgentSafariOnMacosMenuItem.isChecked = true
1342 else -> { // Custom user agent.
1343 // Update the user agent menu item title.
1344 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_custom)
1346 // Select the Custom radio box.
1347 optionsUserAgentCustomMenuItem.isChecked = true
1351 // Set the font size title.
1352 optionsFontSizeMenuItem.title = getString(R.string.font_size) + " - " + fontSize + "%"
1354 // Run all the other default commands.
1355 super.onPrepareOptionsMenu(menu)
1357 // Display the menu.
1361 override fun onOptionsItemSelected(menuItem: MenuItem): Boolean {
1362 // Run the commands that correlate to the selected menu item.
1363 return when (menuItem.itemId) {
1364 R.id.javascript -> { // JavaScript.
1365 // Toggle the JavaScript status.
1366 currentWebView!!.settings.javaScriptEnabled = !currentWebView!!.settings.javaScriptEnabled
1368 // Update the privacy icon.
1369 updatePrivacyIcons(true)
1371 // Display a snackbar.
1372 if (currentWebView!!.settings.javaScriptEnabled) // JavaScrip is enabled.
1373 Snackbar.make(webViewViewPager2, R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show()
1374 else if (cookieManager.acceptCookie()) // JavaScript is disabled, but cookies are enabled.
1375 Snackbar.make(webViewViewPager2, R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show()
1376 else // Privacy mode.
1377 Snackbar.make(webViewViewPager2, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show()
1379 // Reload the current WebView.
1380 currentWebView!!.reload()
1382 // Consume the event.
1386 R.id.refresh -> { // Refresh.
1387 // Run the command that correlates to the current status of the menu item.
1388 if (menuItem.title == getString(R.string.refresh)) // The refresh button was pushed.
1389 currentWebView!!.reload()
1390 else // The stop button was pushed.
1391 currentWebView!!.stopLoading()
1393 // Consume the event.
1397 R.id.bookmarks -> { // Bookmarks.
1398 // Open the bookmarks drawer.
1399 drawerLayout.openDrawer(GravityCompat.END)
1401 // Consume the event.
1405 R.id.cookies -> { // Cookies.
1406 // Toggle the cookie status.
1407 cookieManager.setAcceptCookie(!cookieManager.acceptCookie())
1409 // Store the cookie status.
1410 currentWebView!!.acceptCookies = cookieManager.acceptCookie()
1412 // Update the menu checkbox.
1413 menuItem.isChecked = cookieManager.acceptCookie()
1415 // Update the privacy icon.
1416 updatePrivacyIcons(true)
1418 // Display a snackbar.
1419 if (cookieManager.acceptCookie()) // Cookies are enabled.
1420 Snackbar.make(webViewViewPager2, R.string.cookies_enabled, Snackbar.LENGTH_SHORT).show()
1421 else if (currentWebView!!.settings.javaScriptEnabled) // JavaScript is still enabled.
1422 Snackbar.make(webViewViewPager2, R.string.cookies_disabled, Snackbar.LENGTH_SHORT).show()
1423 else // Privacy mode.
1424 Snackbar.make(webViewViewPager2, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show()
1426 // Reload the current WebView.
1427 currentWebView!!.reload()
1429 // Consume the event.
1433 R.id.dom_storage -> { // DOM storage.
1434 // Toggle the DOM storage status.
1435 currentWebView!!.settings.domStorageEnabled = !currentWebView!!.settings.domStorageEnabled
1437 // Update the menu checkbox.
1438 menuItem.isChecked = currentWebView!!.settings.domStorageEnabled
1440 // Update the privacy icon.
1441 updatePrivacyIcons(true)
1443 // Display a snackbar.
1444 if (currentWebView!!.settings.domStorageEnabled)
1445 Snackbar.make(webViewViewPager2, R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show()
1447 Snackbar.make(webViewViewPager2, R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show()
1449 // Reload the current WebView.
1450 currentWebView!!.reload()
1452 // Consume the event.
1456 R.id.save_form_data -> { // Form data. This can be removed once the minimum API >= 26.
1457 // Switch the status of saveFormDataEnabled.
1458 @Suppress("DEPRECATION")
1459 currentWebView!!.settings.saveFormData = !currentWebView!!.settings.saveFormData
1461 // Update the menu checkbox.
1462 @Suppress("DEPRECATION")
1463 menuItem.isChecked = currentWebView!!.settings.saveFormData
1465 // Display a snackbar.
1466 @Suppress("DEPRECATION")
1467 if (currentWebView!!.settings.saveFormData)
1468 Snackbar.make(webViewViewPager2, R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show()
1470 Snackbar.make(webViewViewPager2, R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show()
1472 // Update the privacy icon.
1473 updatePrivacyIcons(true)
1475 // Reload the current WebView.
1476 currentWebView!!.reload()
1478 // Consume the event.
1482 R.id.clear_cookies -> { // Clear cookies.
1483 // Create a snackbar.
1484 Snackbar.make(webViewViewPager2, R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1485 .setAction(R.string.undo) {} // Everything will be handled by `onDismissed()` below.
1486 .addCallback(object : Snackbar.Callback() {
1487 override fun onDismissed(snackbar: Snackbar, event: Int) {
1488 if (event != DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1489 // Delete the cookies.
1490 cookieManager.removeAllCookies(null)
1496 // Consume the event.
1500 R.id.clear_dom_storage -> { // Clear DOM storage.
1501 // Create a snackbar.
1502 Snackbar.make(webViewViewPager2, R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1503 .setAction(R.string.undo) {} // Everything will be handled by `onDismissed()` below.
1504 .addCallback(object : Snackbar.Callback() {
1505 override fun onDismissed(snackbar: Snackbar, event: Int) {
1506 if (event != DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1507 // Get a handle for the web storage.
1508 val webStorage = WebStorage.getInstance()
1510 // Delete the DOM Storage.
1511 webStorage.deleteAllData()
1513 // Initialize a handler to manually delete the DOM storage files and directories.
1514 val deleteDomStorageHandler = Handler(Looper.getMainLooper())
1516 // Setup a runnable to manually delete the DOM storage files and directories.
1517 val deleteDomStorageRunnable = Runnable {
1519 // Get a handle for the runtime.
1520 val runtime = Runtime.getRuntime()
1522 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1523 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1524 val privateDataDirectoryString = applicationInfo.dataDir
1526 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1527 val deleteLocalStorageProcess = runtime.exec(arrayOf("rm", "-rf", "$privateDataDirectoryString/app_webview/Local Storage/"))
1529 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1530 val deleteIndexProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview/IndexedDB")
1531 val deleteQuotaManagerProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/QuotaManager")
1532 val deleteQuotaManagerJournalProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/QuotaManager-journal")
1533 val deleteDatabasesProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview/databases")
1535 // Wait for the processes to finish.
1536 deleteLocalStorageProcess.waitFor()
1537 deleteIndexProcess.waitFor()
1538 deleteQuotaManagerProcess.waitFor()
1539 deleteQuotaManagerJournalProcess.waitFor()
1540 deleteDatabasesProcess.waitFor()
1541 } catch (exception: Exception) {
1542 // Do nothing if an error is thrown.
1546 // Manually delete the DOM storage files after 200 milliseconds.
1547 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200)
1553 // Consume the event.
1557 R.id.clear_form_data -> { // Clear form data. This can be remove once the minimum API >= 26.
1558 // Create a snackbar.
1559 Snackbar.make(webViewViewPager2, R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1560 .setAction(R.string.undo) {} // Everything will be handled by `onDismissed()` below.
1561 .addCallback(object : Snackbar.Callback() {
1562 override fun onDismissed(snackbar: Snackbar, event: Int) {
1563 if (event != DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1564 // Get a handle for the webView database.
1565 val webViewDatabase = WebViewDatabase.getInstance(applicationContext)
1567 // Delete the form data.
1568 @Suppress("DEPRECATION")
1569 webViewDatabase.clearFormData()
1575 // Consume the event.
1579 R.id.easylist -> { // EasyList.
1580 // Toggle the EasyList status.
1581 currentWebView!!.easyListEnabled = !currentWebView!!.easyListEnabled
1583 // Update the menu checkbox.
1584 menuItem.isChecked = currentWebView!!.easyListEnabled
1586 // Reload the current WebView.
1587 currentWebView!!.reload()
1589 // Consume the event.
1593 R.id.easyprivacy -> { // EasyPrivacy.
1594 // Toggle the EasyPrivacy status.
1595 currentWebView!!.easyPrivacyEnabled = !currentWebView!!.easyPrivacyEnabled
1597 // Update the menu checkbox.
1598 menuItem.isChecked = currentWebView!!.easyPrivacyEnabled
1600 // Reload the current WebView.
1601 currentWebView!!.reload()
1603 // Consume the event.
1607 R.id.fanboys_annoyance_list -> { // Fanboy's Annoyance List.
1608 // Toggle Fanboy's Annoyance List status.
1609 currentWebView!!.fanboysAnnoyanceListEnabled = !currentWebView!!.fanboysAnnoyanceListEnabled
1611 // Update the menu checkbox.
1612 menuItem.isChecked = currentWebView!!.fanboysAnnoyanceListEnabled
1614 // Update the status of Fanboy's Social Blocking List.
1615 optionsFanboysSocialBlockingListMenuItem.isEnabled = !currentWebView!!.fanboysAnnoyanceListEnabled
1617 // Reload the current WebView.
1618 currentWebView!!.reload()
1620 // Consume the event.
1624 R.id.fanboys_social_blocking_list -> { // Fanboy's Social Blocking List.
1625 // Toggle Fanboy's Social Blocking List status.
1626 currentWebView!!.fanboysSocialBlockingListEnabled = !currentWebView!!.fanboysSocialBlockingListEnabled
1628 // Update the menu checkbox.
1629 menuItem.isChecked = currentWebView!!.fanboysSocialBlockingListEnabled
1631 // Reload the current WebView.
1632 currentWebView!!.reload()
1634 // Consume the event.
1638 R.id.ultralist -> { // UltraList.
1639 // Toggle the UltraList status.
1640 currentWebView!!.ultraListEnabled = !currentWebView!!.ultraListEnabled
1642 // Update the menu checkbox.
1643 menuItem.isChecked = currentWebView!!.ultraListEnabled
1645 // Reload the current WebView.
1646 currentWebView!!.reload()
1648 // Consume the event.
1652 R.id.ultraprivacy -> { // UltraPrivacy.
1653 // Toggle the UltraPrivacy status.
1654 currentWebView!!.ultraPrivacyEnabled = !currentWebView!!.ultraPrivacyEnabled
1656 // Update the menu checkbox.
1657 menuItem.isChecked = currentWebView!!.ultraPrivacyEnabled
1659 // Reload the current WebView.
1660 currentWebView!!.reload()
1662 // Consume the event.
1666 R.id.block_all_third_party_requests -> { // Block all third-party requests.
1667 //Toggle the third-party requests blocker status.
1668 currentWebView!!.blockAllThirdPartyRequests = !currentWebView!!.blockAllThirdPartyRequests
1670 // Update the menu checkbox.
1671 menuItem.isChecked = currentWebView!!.blockAllThirdPartyRequests
1673 // Reload the current WebView.
1674 currentWebView!!.reload()
1676 // Consume the event.
1680 R.id.proxy_none -> { // Proxy - None.
1681 // Update the proxy mode.
1682 proxyMode = ProxyHelper.NONE
1684 // Apply the proxy mode.
1687 // Consume the event.
1691 R.id.proxy_tor -> { // Proxy - Tor.
1692 // Update the proxy mode.
1693 proxyMode = ProxyHelper.TOR
1695 // Apply the proxy mode.
1698 // Consume the event.
1702 R.id.proxy_i2p -> { // Proxy - I2P.
1703 // Update the proxy mode.
1704 proxyMode = ProxyHelper.I2P
1706 // Apply the proxy mode.
1709 // Consume the event.
1713 R.id.proxy_custom -> { // Proxy - Custom.
1714 // Update the proxy mode.
1715 proxyMode = ProxyHelper.CUSTOM
1717 // Apply the proxy mode.
1720 // Consume the event.
1724 R.id.user_agent_privacy_browser -> { // User Agent - Privacy Browser.
1725 // Update the user agent.
1726 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[0]
1728 // Reload the current WebView.
1729 currentWebView!!.reload()
1731 // Consume the event.
1735 R.id.user_agent_webview_default -> { // User Agent - WebView Default.
1736 // Update the user agent.
1737 currentWebView!!.settings.userAgentString = ""
1739 // Reload the current WebView.
1740 currentWebView!!.reload()
1742 // Consume the event.
1746 R.id.user_agent_firefox_on_android -> { // User Agent - Firefox on Android.
1747 // Update the user agent.
1748 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[2]
1750 // Reload the current WebView.
1751 currentWebView!!.reload()
1753 // Consume the event.
1757 R.id.user_agent_chrome_on_android -> { // User Agent - Chrome on Android.
1758 // Update the user agent.
1759 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[3]
1761 // Reload the current WebView.
1762 currentWebView!!.reload()
1764 // Consume the event.
1768 R.id.user_agent_safari_on_ios -> { // User Agent - Safari on iOS.
1769 // Update the user agent.
1770 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[4]
1772 // Reload the current WebView.
1773 currentWebView!!.reload()
1775 // Consume the event.
1779 R.id.user_agent_firefox_on_linux -> { // User Agent - Firefox on Linux.
1780 // Update the user agent.
1781 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[5]
1783 // Reload the current WebView.
1784 currentWebView!!.reload()
1786 // Consume the event.
1790 R.id.user_agent_chromium_on_linux -> { // User Agent - Chromium on Linux.
1791 // Update the user agent.
1792 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[6]
1794 // Reload the current WebView.
1795 currentWebView!!.reload()
1797 // Consume the event.
1801 R.id.user_agent_firefox_on_windows -> { // User Agent - Firefox on Windows.
1802 // Update the user agent.
1803 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[7]
1805 // Reload the current WebView.
1806 currentWebView!!.reload()
1808 // Consume the event.
1812 R.id.user_agent_chrome_on_windows -> { // User Agent - Chrome on Windows.
1813 // Update the user agent.
1814 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[8]
1816 // Reload the current WebView.
1817 currentWebView!!.reload()
1819 // Consume the event.
1823 R.id.user_agent_edge_on_windows -> { // User Agent - Edge on Windows.
1824 // Update the user agent.
1825 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[9]
1827 // Reload the current WebView.
1828 currentWebView!!.reload()
1830 // Consume the event.
1834 R.id.user_agent_internet_explorer_on_windows -> { // User Agent - Internet Explorer on Windows.
1835 // Update the user agent.
1836 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[10]
1838 // Reload the current WebView.
1839 currentWebView!!.reload()
1841 // Consume the event.
1845 R.id.user_agent_safari_on_macos -> { // User Agent - Safari on macOS.
1846 // Update the user agent.
1847 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[11]
1849 // Reload the current WebView.
1850 currentWebView!!.reload()
1852 // Consume the event.
1856 R.id.user_agent_custom -> { // User Agent - Custom.
1857 // Update the user agent.
1858 currentWebView!!.settings.userAgentString = sharedPreferences.getString(getString(R.string.custom_user_agent_key), getString(R.string.custom_user_agent_default_value))
1860 // Reload the current WebView.
1861 currentWebView!!.reload()
1863 // Consume the event.
1867 R.id.font_size -> { // Font size.
1868 // Instantiate the font size dialog.
1869 val fontSizeDialogFragment: DialogFragment = FontSizeDialog.displayDialog(currentWebView!!.settings.textZoom)
1871 // Show the font size dialog.
1872 fontSizeDialogFragment.show(supportFragmentManager, getString(R.string.font_size))
1874 // Consume the event.
1878 R.id.swipe_to_refresh -> { // Swipe to refresh.
1879 // Toggle the stored status of swipe to refresh.
1880 currentWebView!!.swipeToRefresh = !currentWebView!!.swipeToRefresh
1882 // Update the swipe refresh layout.
1883 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.
1884 swipeRefreshLayout.isEnabled = currentWebView!!.scrollY == 0
1885 else // Swipe to refresh is disabled.
1886 swipeRefreshLayout.isEnabled = false
1888 // Consume the event.
1892 R.id.wide_viewport -> { // Wide viewport.
1893 // Toggle the viewport.
1894 currentWebView!!.settings.useWideViewPort = !currentWebView!!.settings.useWideViewPort
1896 // Consume the event.
1900 R.id.display_images -> { // Display images.
1901 // Toggle the displaying of images.
1902 if (currentWebView!!.settings.loadsImagesAutomatically) { // Images are currently loaded automatically.
1903 // Disable loading of images.
1904 currentWebView!!.settings.loadsImagesAutomatically = false
1906 // Reload the website to remove existing images.
1907 currentWebView!!.reload()
1908 } else { // Images are not currently loaded automatically.
1909 // Enable loading of images. Missing images will be loaded without the need for a reload.
1910 currentWebView!!.settings.loadsImagesAutomatically = true
1913 // Consume the event.
1917 R.id.dark_webview -> { // Dark WebView.
1918 // Toggle dark WebView if supported.
1919 if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING))
1920 WebSettingsCompat.setAlgorithmicDarkeningAllowed(currentWebView!!.settings, !WebSettingsCompat.isAlgorithmicDarkeningAllowed(currentWebView!!.settings)
1923 // Consume the event.
1927 R.id.find_on_page -> { // Find on page.
1928 // Set the minimum height of the find on page linear layout to match the toolbar.
1929 findOnPageLinearLayout.minimumHeight = toolbar.height
1931 // Hide the toolbar.
1932 toolbar.visibility = View.GONE
1934 // Show the find on page linear layout.
1935 findOnPageLinearLayout.visibility = View.VISIBLE
1937 // Display the keyboard. The app must wait 200 ms before running the command to work around a bug in Android.
1938 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1939 findOnPageEditText.postDelayed({
1940 // Set the focus on the find on page edit text.
1941 findOnPageEditText.requestFocus()
1943 // Get a handle for the input method manager.
1944 val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
1946 // Display the keyboard. `0` sets no input flags.
1947 inputMethodManager.showSoftInput(findOnPageEditText, 0)
1950 // Consume the event.
1954 R.id.print -> { // Print.
1955 // Get a print manager instance.
1956 val printManager = (getSystemService(PRINT_SERVICE) as PrintManager)
1958 // Create a print document adapter from the current WebView.
1959 val printDocumentAdapter = currentWebView!!.createPrintDocumentAdapter(getString(R.string.print))
1961 // Print the document.
1962 printManager.print(getString(R.string.privacy_browser_webpage), printDocumentAdapter, null)
1964 // Consume the event.
1968 R.id.save_url -> { // Save URL.
1969 // Check the download preference.
1970 if (downloadWithExternalApp) // Download with an external app.
1971 downloadUrlWithExternalApp(currentWebView!!.currentUrl)
1972 else // Handle the download inside of Privacy Browser. The dialog will be displayed once the file size and the content disposition have been acquired.
1973 PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, currentWebView!!.currentUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
1975 // Consume the event.
1979 R.id.save_archive -> {
1980 // Open the file picker with a default file name built from the current domain name.
1981 saveWebpageArchiveActivityResultLauncher.launch(currentWebView!!.currentDomainName + ".mht")
1983 // Consume the event.
1987 R.id.save_image -> { // Save image.
1988 // Open the file picker with a default file name built from the current domain name.
1989 saveWebpageImageActivityResultLauncher.launch(currentWebView!!.currentDomainName + ".png")
1991 // Consume the event.
1995 R.id.add_to_homescreen -> { // Add to homescreen.
1996 // Instantiate the create home screen shortcut dialog.
1997 val createHomeScreenShortcutDialogFragment: DialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView!!.title!!, currentWebView!!.url!!, currentWebView!!.getFavoriteIcon())
1999 // Show the create home screen shortcut dialog.
2000 createHomeScreenShortcutDialogFragment.show(supportFragmentManager, getString(R.string.create_shortcut))
2002 // Consume the event.
2006 R.id.view_source -> { // View source.
2007 // Create an intent to launch the view source activity.
2008 val viewSourceIntent = Intent(this, ViewSourceActivity::class.java)
2010 // Add the variables to the intent.
2011 viewSourceIntent.putExtra(CURRENT_URL, currentWebView!!.url)
2012 viewSourceIntent.putExtra(USER_AGENT, currentWebView!!.settings.userAgentString)
2015 startActivity(viewSourceIntent)
2017 // Consume the event.
2021 R.id.share_message -> { // Share a message.
2022 // Prepare the share string.
2023 val shareString = currentWebView!!.title + " – " + currentWebView!!.url
2025 // Create the share intent.
2026 val shareMessageIntent = Intent(Intent.ACTION_SEND)
2028 // Add the share string to the intent.
2029 shareMessageIntent.putExtra(Intent.EXTRA_TEXT, shareString)
2031 // Set the MIME type.
2032 shareMessageIntent.type = "text/plain"
2034 // Set the intent to open in a new task.
2035 shareMessageIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
2038 startActivity(Intent.createChooser(shareMessageIntent, getString(R.string.share_message)))
2040 // Consume the event.
2044 R.id.share_url -> { // Share URL.
2045 // Create the share intent.
2046 val shareUrlIntent = Intent(Intent.ACTION_SEND)
2048 // Add the URL to the intent.
2049 shareUrlIntent.putExtra(Intent.EXTRA_TEXT, currentWebView!!.url)
2051 // Add the title to the intent.
2052 shareUrlIntent.putExtra(Intent.EXTRA_SUBJECT, currentWebView!!.title)
2054 // Set the MIME type.
2055 shareUrlIntent.type = "text/plain"
2057 // Set the intent to open in a new task.
2058 shareUrlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
2061 startActivity(Intent.createChooser(shareUrlIntent, getString(R.string.share_url)))
2063 // Consume the event.
2067 R.id.open_with_app -> { // Open with app.
2068 // Open the URL with an outside app.
2069 openWithApp(currentWebView!!.url!!)
2071 // Consume the event.
2075 R.id.open_with_browser -> { // Open with browser.
2076 // Open the URL with an outside browser.
2077 openWithBrowser(currentWebView!!.url!!)
2079 // Consume the event.
2083 R.id.add_or_edit_domain -> { // Add or edit domain.
2084 // Reapply the domain settings on returning to `MainWebViewActivity`.
2085 reapplyDomainSettingsOnRestart = true
2087 // Check if domain settings are currently applied.
2088 if (currentWebView!!.domainSettingsApplied) { // Edit the current domain settings.
2089 // Create an intent to launch the domains activity.
2090 val domainsIntent = Intent(this, DomainsActivity::class.java)
2092 // Add the extra information to the intent.
2093 domainsIntent.putExtra(LOAD_DOMAIN, currentWebView!!.domainSettingsDatabaseId)
2094 domainsIntent.putExtra(CLOSE_ON_BACK, true)
2095 domainsIntent.putExtra(CURRENT_URL, currentWebView!!.url)
2096 domainsIntent.putExtra(CURRENT_IP_ADDRESSES, currentWebView!!.currentIpAddresses)
2098 // Get the current certificate.
2099 val sslCertificate = currentWebView!!.certificate
2101 // Check to see if the SSL certificate is populated.
2102 if (sslCertificate != null) {
2103 // Extract the certificate to strings.
2104 val issuedToCName = sslCertificate.issuedTo.cName
2105 val issuedToOName = sslCertificate.issuedTo.oName
2106 val issuedToUName = sslCertificate.issuedTo.uName
2107 val issuedByCName = sslCertificate.issuedBy.cName
2108 val issuedByOName = sslCertificate.issuedBy.oName
2109 val issuedByUName = sslCertificate.issuedBy.uName
2110 val startDateLong = sslCertificate.validNotBeforeDate.time
2111 val endDateLong = sslCertificate.validNotAfterDate.time
2113 // Add the certificate to the intent.
2114 domainsIntent.putExtra(SSL_ISSUED_TO_CNAME, issuedToCName)
2115 domainsIntent.putExtra(SSL_ISSUED_TO_ONAME, issuedToOName)
2116 domainsIntent.putExtra(SSL_ISSUED_TO_UNAME, issuedToUName)
2117 domainsIntent.putExtra(SSL_ISSUED_BY_CNAME, issuedByCName)
2118 domainsIntent.putExtra(SSL_ISSUED_BY_ONAME, issuedByOName)
2119 domainsIntent.putExtra(SSL_ISSUED_BY_UNAME, issuedByUName)
2120 domainsIntent.putExtra(SSL_START_DATE, startDateLong)
2121 domainsIntent.putExtra(SSL_END_DATE, endDateLong)
2125 startActivity(domainsIntent)
2126 } else { // Add a new domain.
2127 // Get the current URI.
2128 val currentUri = Uri.parse(currentWebView!!.url)
2130 // Get the current domain from the URI. Use an empty string if it is null.
2131 val currentDomain = currentUri.host?: ""
2133 // Create the domain and store the database ID.
2134 val newDomainDatabaseId = domainsDatabaseHelper!!.addDomain(currentDomain)
2136 // Create an intent to launch the domains activity.
2137 val domainsIntent = Intent(this, DomainsActivity::class.java)
2139 // Add the extra information to the intent.
2140 domainsIntent.putExtra(LOAD_DOMAIN, newDomainDatabaseId)
2141 domainsIntent.putExtra(CLOSE_ON_BACK, true)
2142 domainsIntent.putExtra(CURRENT_URL, currentWebView!!.url)
2143 domainsIntent.putExtra(CURRENT_IP_ADDRESSES, currentWebView!!.currentIpAddresses)
2145 // Get the current certificate.
2146 val sslCertificate = currentWebView!!.certificate
2148 // Check to see if the SSL certificate is populated.
2149 if (sslCertificate != null) {
2150 // Extract the certificate to strings.
2151 val issuedToCName = sslCertificate.issuedTo.cName
2152 val issuedToOName = sslCertificate.issuedTo.oName
2153 val issuedToUName = sslCertificate.issuedTo.uName
2154 val issuedByCName = sslCertificate.issuedBy.cName
2155 val issuedByOName = sslCertificate.issuedBy.oName
2156 val issuedByUName = sslCertificate.issuedBy.uName
2157 val startDateLong = sslCertificate.validNotBeforeDate.time
2158 val endDateLong = sslCertificate.validNotAfterDate.time
2160 // Add the certificate to the intent.
2161 domainsIntent.putExtra(SSL_ISSUED_TO_CNAME, issuedToCName)
2162 domainsIntent.putExtra(SSL_ISSUED_TO_ONAME, issuedToOName)
2163 domainsIntent.putExtra(SSL_ISSUED_TO_UNAME, issuedToUName)
2164 domainsIntent.putExtra(SSL_ISSUED_BY_CNAME, issuedByCName)
2165 domainsIntent.putExtra(SSL_ISSUED_BY_ONAME, issuedByOName)
2166 domainsIntent.putExtra(SSL_ISSUED_BY_UNAME, issuedByUName)
2167 domainsIntent.putExtra(SSL_START_DATE, startDateLong)
2168 domainsIntent.putExtra(SSL_END_DATE, endDateLong)
2172 startActivity(domainsIntent)
2175 // Consume the event.
2179 else -> { // There is no match with the options menu. Pass the event up to the parent method.
2180 // Don't consume the event.
2181 super.onOptionsItemSelected(menuItem)
2186 override fun onNavigationItemSelected(menuItem: MenuItem): Boolean {
2187 // Run the commands that correspond to the selected menu item.
2188 when (menuItem.itemId) {
2189 R.id.clear_and_exit -> { // Clear and exit.
2190 // Clear and exit Privacy Browser.
2194 R.id.home -> { // Home.
2195 // Load the homepage.
2196 loadUrl(currentWebView!!, sharedPreferences.getString(getString(R.string.homepage_key), getString(R.string.homepage_default_value))!!)
2199 R.id.back -> { // Back.
2200 // Check if the WebView can go back.
2201 if (currentWebView!!.canGoBack()) {
2202 // Get the current web back forward list.
2203 val webBackForwardList = currentWebView!!.copyBackForwardList()
2205 // Get the previous entry URL.
2206 val previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex - 1).url
2208 // Apply the domain settings.
2209 applyDomainSettings(currentWebView!!, previousUrl, resetTab = false, reloadWebsite = false, loadUrl = false)
2211 // Load the previous website in the history.
2212 currentWebView!!.goBack()
2216 R.id.forward -> { // Forward.
2217 // Check if the WebView can go forward.
2218 if (currentWebView!!.canGoForward()) {
2219 // Get the current web back forward list.
2220 val webBackForwardList = currentWebView!!.copyBackForwardList()
2222 // Get the next entry URL.
2223 val nextUrl = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex + 1).url
2225 // Apply the domain settings.
2226 applyDomainSettings(currentWebView!!, nextUrl, resetTab = false, reloadWebsite = false, loadUrl = false)
2228 // Load the next website in the history.
2229 currentWebView!!.goForward()
2233 R.id.history -> { // History.
2234 // Instantiate the URL history dialog.
2235 val urlHistoryDialogFragment: DialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView!!.webViewFragmentId)
2237 // Show the URL history dialog.
2238 urlHistoryDialogFragment.show(supportFragmentManager, getString(R.string.history))
2241 R.id.open -> { // Open.
2242 // Instantiate the open file dialog.
2243 val openDialogFragment: DialogFragment = OpenDialog()
2245 // Show the open file dialog.
2246 openDialogFragment.show(supportFragmentManager, getString(R.string.open))
2249 R.id.requests -> { // Requests.
2250 // Populate the resource requests.
2251 RequestsActivity.resourceRequests = currentWebView!!.getResourceRequests()
2253 // Create an intent to launch the Requests activity.
2254 val requestsIntent = Intent(this, RequestsActivity::class.java)
2256 // Add the block third-party requests status to the intent.
2257 requestsIntent.putExtra(BLOCK_ALL_THIRD_PARTY_REQUESTS, currentWebView!!.blockAllThirdPartyRequests)
2260 startActivity(requestsIntent)
2263 R.id.downloads -> { // Downloads.
2264 // Try the default system download manager.
2266 // Launch the default system Download Manager.
2267 val defaultDownloadManagerIntent = Intent(DownloadManager.ACTION_VIEW_DOWNLOADS)
2269 // Launch as a new task so that the download manager and Privacy Browser show as separate windows in the recent tasks list.
2270 defaultDownloadManagerIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2273 startActivity(defaultDownloadManagerIntent)
2274 } catch (defaultDownloadManagerException: Exception) { // The system download manager is not available.
2275 // Try a generic file manager.
2277 // Create a generic file manager intent.
2278 val genericFileManagerIntent = Intent(Intent.ACTION_VIEW)
2280 // Open the download directory.
2281 genericFileManagerIntent.setDataAndType(Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()), DocumentsContract.Document.MIME_TYPE_DIR)
2283 // Launch as a new task so that the file manager and Privacy Browser show as separate windows in the recent tasks list.
2284 genericFileManagerIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2287 startActivity(genericFileManagerIntent)
2288 } catch (genericFileManagerException: Exception) { // A generic file manager is not available.
2289 // Try an alternate file manager.
2291 // Create an alternate file manager intent.
2292 val alternateFileManagerIntent = Intent(Intent.ACTION_VIEW)
2294 // Open the download directory.
2295 alternateFileManagerIntent.setDataAndType(Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()), "resource/folder")
2297 // Launch as a new task so that the file manager and Privacy Browser show as separate windows in the recent tasks list.
2298 alternateFileManagerIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2300 // Open the alternate file manager.
2301 startActivity(alternateFileManagerIntent)
2302 } catch (alternateFileManagerException: Exception) {
2303 // Display a snackbar.
2304 Snackbar.make(currentWebView!!, R.string.no_file_manager_detected, Snackbar.LENGTH_INDEFINITE).show()
2310 R.id.domains -> { // Domains.
2311 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2312 reapplyDomainSettingsOnRestart = true
2314 // Create a domains activity intent.
2315 val domainsIntent = Intent(this, DomainsActivity::class.java)
2317 // Add the extra information to the intent.
2318 domainsIntent.putExtra(CURRENT_URL, currentWebView!!.url)
2319 domainsIntent.putExtra(CURRENT_IP_ADDRESSES, currentWebView!!.currentIpAddresses)
2321 // Get the current certificate.
2322 val sslCertificate = currentWebView!!.certificate
2324 // Check to see if the SSL certificate is populated.
2325 if (sslCertificate != null) {
2326 // Extract the certificate to strings.
2327 val issuedToCName = sslCertificate.issuedTo.cName
2328 val issuedToOName = sslCertificate.issuedTo.oName
2329 val issuedToUName = sslCertificate.issuedTo.uName
2330 val issuedByCName = sslCertificate.issuedBy.cName
2331 val issuedByOName = sslCertificate.issuedBy.oName
2332 val issuedByUName = sslCertificate.issuedBy.uName
2333 val startDateLong = sslCertificate.validNotBeforeDate.time
2334 val endDateLong = sslCertificate.validNotAfterDate.time
2336 // Add the certificate to the intent.
2337 domainsIntent.putExtra(SSL_ISSUED_TO_CNAME, issuedToCName)
2338 domainsIntent.putExtra(SSL_ISSUED_TO_ONAME, issuedToOName)
2339 domainsIntent.putExtra(SSL_ISSUED_TO_UNAME, issuedToUName)
2340 domainsIntent.putExtra(SSL_ISSUED_BY_CNAME, issuedByCName)
2341 domainsIntent.putExtra(SSL_ISSUED_BY_ONAME, issuedByOName)
2342 domainsIntent.putExtra(SSL_ISSUED_BY_UNAME, issuedByUName)
2343 domainsIntent.putExtra(SSL_START_DATE, startDateLong)
2344 domainsIntent.putExtra(SSL_END_DATE, endDateLong)
2348 startActivity(domainsIntent)
2351 R.id.settings -> { // Settings.
2352 // Set the reapply on restart flags.
2353 reapplyAppSettingsOnRestart = true
2354 reapplyDomainSettingsOnRestart = true
2356 // Create a settings intent.
2357 val settingsIntent = Intent(this, SettingsActivity::class.java)
2360 startActivity(settingsIntent)
2363 R.id.import_export -> { // Import/Export.
2364 // Create an intent to launch the import/export activity.
2365 val importExportIntent = Intent(this, ImportExportActivity::class.java)
2368 startActivity(importExportIntent)
2371 R.id.logcat -> { // Logcat.
2372 // Create an intent to launch the logcat activity.
2373 val logcatIntent = Intent(this, LogcatActivity::class.java)
2376 startActivity(logcatIntent)
2379 R.id.webview_devtools -> { // WebView DevTools.
2380 // Create a WebView DevTools intent.
2381 val webViewDevToolsIntent = Intent("com.android.webview.SHOW_DEV_UI")
2383 // Launch as a new task so that the WebView DevTools and Privacy Browser show as a separate windows in the recent tasks list.
2384 webViewDevToolsIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2387 startActivity(webViewDevToolsIntent)
2390 R.id.guide -> { // Guide.
2391 // Create an intent to launch the guide activity.
2392 val guideIntent = Intent(this, GuideActivity::class.java)
2395 startActivity(guideIntent)
2398 R.id.about -> { // About
2399 // Create an intent to launch the about activity.
2400 val aboutIntent = Intent(this, AboutActivity::class.java)
2402 // Create a string array for the filter list versions.
2403 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])
2405 // Add the filter list versions to the intent.
2406 aboutIntent.putExtra(FILTERLIST_VERSIONS, filterListVersions)
2409 startActivity(aboutIntent)
2413 // Close the navigation drawer.
2414 drawerLayout.closeDrawer(GravityCompat.START)
2420 override fun onCreateContextMenu(contextMenu: ContextMenu, view: View, contextMenuInfo: ContextMenu.ContextMenuInfo?) {
2421 // Get the hit test result.
2422 val hitTestResult = currentWebView!!.hitTestResult
2424 // Define the URL strings.
2425 val imageUrl: String?
2426 val linkUrl: String?
2428 // Get a handle for the clipboard manager.
2429 val clipboardManager = (getSystemService(CLIPBOARD_SERVICE) as ClipboardManager)
2431 // Process the link according to the type.
2432 when (hitTestResult.type) {
2433 // `SRC_ANCHOR_TYPE` is a link.
2434 WebView.HitTestResult.SRC_ANCHOR_TYPE -> {
2435 // Get the target URL.
2436 linkUrl = hitTestResult.extra!!
2438 // Set the target URL as the context menu title.
2439 contextMenu.setHeaderTitle(linkUrl)
2441 // Add an open in new tab entry.
2442 contextMenu.add(R.string.open_in_new_tab).setOnMenuItemClickListener {
2443 // Load the link URL in a new tab and move to it.
2444 addNewTab(linkUrl, true)
2446 // Consume the event.
2450 // Add an open in background entry.
2451 contextMenu.add(R.string.open_in_background).setOnMenuItemClickListener {
2452 // Load the link URL in a new tab but do not move to it.
2453 addNewTab(linkUrl, false)
2455 // Consume the event.
2459 // Add an open with app entry.
2460 contextMenu.add(R.string.open_with_app).setOnMenuItemClickListener {
2461 // Open the URL with another app.
2462 openWithApp(linkUrl)
2464 // Consume the event.
2468 // Add an open with browser entry.
2469 contextMenu.add(R.string.open_with_browser).setOnMenuItemClickListener {
2470 // Open the URL with another browser.
2471 openWithBrowser(linkUrl)
2473 // Consume the event.
2477 // Add a copy URL entry.
2478 contextMenu.add(R.string.copy_url).setOnMenuItemClickListener {
2479 // Save the link URL in a clip data.
2480 val srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl)
2482 // Set the clip data as the clipboard's primary clip.
2483 clipboardManager.setPrimaryClip(srcAnchorTypeClipData)
2485 // Consume the event.
2489 // Add a Save URL entry.
2490 contextMenu.add(R.string.save_url).setOnMenuItemClickListener {
2491 // Check the download preference.
2492 if (downloadWithExternalApp) // Download with an external app.
2493 downloadUrlWithExternalApp(linkUrl)
2494 else // Handle the download inside of Privacy Browser. The dialog will be displayed once the file size and the content disposition have been acquired.
2495 PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, linkUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
2497 // Consume the event.
2501 // Add an empty cancel entry, which by default closes the context menu.
2502 contextMenu.add(R.string.cancel)
2505 // `IMAGE_TYPE` is an image.
2506 WebView.HitTestResult.IMAGE_TYPE -> {
2507 // Get the image URL.
2508 imageUrl = hitTestResult.extra!!
2510 // Set the context menu title.
2511 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.
2512 contextMenu.setHeaderTitle(imageUrl.substring(0, 100))
2513 else // The image URL does not contain the full image data. Set the image URL as the title of the context menu.
2514 contextMenu.setHeaderTitle(imageUrl)
2516 // Add an open in new tab entry.
2517 contextMenu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener {
2518 // Load the image in a new tab.
2519 addNewTab(imageUrl, true)
2521 // Consume the event.
2525 // Add an open with app entry.
2526 contextMenu.add(R.string.open_with_app).setOnMenuItemClickListener {
2527 // Open the image URL with an external app.
2528 openWithApp(imageUrl)
2530 // Consume the event.
2534 // Add an open with browser entry.
2535 contextMenu.add(R.string.open_with_browser).setOnMenuItemClickListener {
2536 // Open the image URL with an external browser.
2537 openWithBrowser(imageUrl)
2539 // Consume the event.
2543 // Add a view image entry.
2544 contextMenu.add(R.string.view_image).setOnMenuItemClickListener {
2545 // Load the image in the current tab.
2546 loadUrl(currentWebView!!, imageUrl)
2548 // Consume the event.
2552 // Add a save image entry.
2553 contextMenu.add(R.string.save_image).setOnMenuItemClickListener {
2554 // Check the download preference.
2555 if (downloadWithExternalApp) { // Download with an external app.
2556 downloadUrlWithExternalApp(imageUrl)
2557 } else { // Handle the download inside of Privacy Browser. The dialog will be displayed once the file size and the content disposition have been acquired.
2558 PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, imageUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
2561 // Consume the event.
2565 // Add a copy URL entry.
2566 contextMenu.add(R.string.copy_url).setOnMenuItemClickListener {
2567 // Save the image URL in a clip data.
2568 val imageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl)
2570 // Set the clip data as the clipboard's primary clip.
2571 clipboardManager.setPrimaryClip(imageTypeClipData)
2573 // Consume the event.
2577 // Add an empty cancel entry, which by default closes the context menu.
2578 contextMenu.add(R.string.cancel)
2581 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2582 WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE -> {
2583 // Get the image URL.
2584 imageUrl = hitTestResult.extra!!
2586 // Instantiate a handler.
2587 val handler = Handler(Looper.getMainLooper())
2589 // Get a handle for the handler message.
2590 val message = handler.obtainMessage()
2592 // Request the image details from the last touched node be returned in the message.
2593 currentWebView!!.requestFocusNodeHref(message)
2595 // Get the link URL from the message data.
2596 linkUrl = message.data.getString("url")!!
2598 // Set the link URL as the title of the context menu.
2599 contextMenu.setHeaderTitle(linkUrl)
2601 // Add an open in new tab entry.
2602 contextMenu.add(R.string.open_in_new_tab).setOnMenuItemClickListener {
2603 // Load the link URL in a new tab and move to it.
2604 addNewTab(linkUrl, true)
2606 // Consume the event.
2610 // Add an open in background entry.
2611 contextMenu.add(R.string.open_in_background).setOnMenuItemClickListener {
2612 // Lod the link URL in a new tab but do not move to it.
2613 addNewTab(linkUrl, false)
2615 // Consume the event.
2619 // Add an open image in new tab entry.
2620 contextMenu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener {
2621 // Load the image in a new tab and move to it.
2622 addNewTab(imageUrl, true)
2624 // Consume the event.
2628 // Add an open with app entry.
2629 contextMenu.add(R.string.open_with_app).setOnMenuItemClickListener {
2630 // Open the link URL with an external app.
2631 openWithApp(linkUrl)
2633 // Consume the event.
2637 // Add an open with browser entry.
2638 contextMenu.add(R.string.open_with_browser).setOnMenuItemClickListener {
2639 // Open the link URL with an external browser.
2640 openWithBrowser(linkUrl)
2642 // Consume the event.
2646 // Add a view image entry.
2647 contextMenu.add(R.string.view_image).setOnMenuItemClickListener {
2648 // View the image in the current tab.
2649 loadUrl(currentWebView!!, imageUrl)
2651 // Consume the event.
2655 // Add a Save Image entry.
2656 contextMenu.add(R.string.save_image).setOnMenuItemClickListener {
2657 // Check the download preference.
2658 if (downloadWithExternalApp) // Download with an external app.
2659 downloadUrlWithExternalApp(imageUrl)
2660 else // Handle the download inside of Privacy Browser. The dialog will be displayed once the file size and the content disposition have been acquired.
2661 PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, imageUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
2663 // Consume the event.
2667 // Add a copy URL entry.
2668 contextMenu.add(R.string.copy_url).setOnMenuItemClickListener {
2669 // Save the link URL in a clip data.
2670 val srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl)
2672 // Set the clip data as the clipboard's primary clip.
2673 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData)
2675 // Consume the event.
2679 // Add a save URL entry.
2680 contextMenu.add(R.string.save_url).setOnMenuItemClickListener {
2681 // Check the download preference.
2682 if (downloadWithExternalApp) // Download with an external app.
2683 downloadUrlWithExternalApp(linkUrl)
2684 else // Handle the download inside of Privacy Browser. The dialog will be displayed once the file size and the content disposition have been acquired.
2685 PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, linkUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
2687 // Consume the event.
2691 // Add an empty cancel entry, which by default closes the context menu.
2692 contextMenu.add(R.string.cancel)
2695 WebView.HitTestResult.EMAIL_TYPE -> {
2696 // Get the target URL.
2697 linkUrl = hitTestResult.extra
2699 // Set the target URL as the title of the context menu.
2700 contextMenu.setHeaderTitle(linkUrl)
2702 // Add a write email entry.
2703 contextMenu.add(R.string.write_email).setOnMenuItemClickListener {
2704 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2705 val emailIntent = Intent(Intent.ACTION_SENDTO)
2707 // Parse the url and set it as the data for the intent.
2708 emailIntent.data = Uri.parse("mailto:$linkUrl")
2710 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2711 emailIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2715 startActivity(emailIntent)
2716 } catch (exception: ActivityNotFoundException) {
2717 // Display a snackbar.
2718 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
2721 // Consume the event.
2725 // Add a copy email address entry.
2726 contextMenu.add(R.string.copy_email_address).setOnMenuItemClickListener {
2727 // Save the email address in a clip data.
2728 val srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl)
2730 // Set the clip data as the clipboard's primary clip.
2731 clipboardManager.setPrimaryClip(srcEmailTypeClipData)
2733 // Consume the event.
2737 // Add an empty cancel entry, which by default closes the context menu.
2738 contextMenu.add(R.string.cancel)
2743 // The view parameter cannot be removed because it is called from the layout onClick.
2744 fun addTab(@Suppress("UNUSED_PARAMETER")view: View?) {
2745 // Add a new tab with a blank URL.
2749 private fun addNewTab(urlString: String, moveToTab: Boolean) {
2750 // Clear the focus from the URL edit text, so that it will be populated with the information from the new tab.
2751 urlEditText.clearFocus()
2753 // Get the new page number. The page numbers are 0 indexed, so the new page number will match the current count.
2754 val newTabNumber = tabLayout.tabCount
2757 tabLayout.addTab(tabLayout.newTab())
2760 val newTab = tabLayout.getTabAt(newTabNumber)!!
2762 // Set a custom view on the new tab.
2763 newTab.setCustomView(R.layout.tab_custom_view)
2765 // Add the new WebView page.
2766 webViewStateAdapter!!.addPage(newTabNumber, webViewViewPager2, urlString, moveToTab)
2768 // Show the app bar if it is at the bottom of the screen and the new tab is taking focus.
2769 if (bottomAppBar && moveToTab && appBarLayout.translationY != 0f) {
2770 // Animate the bottom app bar onto the screen.
2771 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0f)
2774 objectAnimator.start()
2778 private fun applyAppSettings() {
2779 // 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.
2780 defaultJavaScript = sharedPreferences.getBoolean(getString(R.string.javascript_key), false)
2781 defaultCookies = sharedPreferences.getBoolean(getString(R.string.cookies_key), false)
2782 defaultDomStorage = sharedPreferences.getBoolean(getString(R.string.dom_storage_key), false)
2783 defaultFormData = sharedPreferences.getBoolean(getString(R.string.save_form_data_key), false) // Form data can be removed once the minimum API >= 26.
2784 defaultEasyList = sharedPreferences.getBoolean(getString(R.string.easylist_key), true)
2785 defaultEasyPrivacy = sharedPreferences.getBoolean(getString(R.string.easyprivacy_key), true)
2786 defaultFanboysAnnoyanceList = sharedPreferences.getBoolean(getString(R.string.fanboys_annoyance_list_key), true)
2787 defaultFanboysSocialBlockingList = sharedPreferences.getBoolean(getString(R.string.fanboys_social_blocking_list_key), true)
2788 defaultUltraList = sharedPreferences.getBoolean(getString(R.string.ultralist_key), true)
2789 defaultUltraPrivacy = sharedPreferences.getBoolean(getString(R.string.ultraprivacy_key), true)
2790 defaultBlockAllThirdPartyRequests = sharedPreferences.getBoolean(getString(R.string.block_all_third_party_requests_key), false)
2791 defaultFontSizeString = sharedPreferences.getString(getString(R.string.font_size_key), getString(R.string.font_size_default_value))!!
2792 defaultUserAgentName = sharedPreferences.getString(getString(R.string.user_agent_key), getString(R.string.user_agent_default_value))!!
2793 defaultSwipeToRefresh = sharedPreferences.getBoolean(getString(R.string.swipe_to_refresh_key), true)
2794 defaultWebViewTheme = sharedPreferences.getString(getString(R.string.webview_theme_key), getString(R.string.webview_theme_default_value))!!
2795 defaultWideViewport = sharedPreferences.getBoolean(getString(R.string.wide_viewport_key), true)
2796 defaultDisplayWebpageImages = sharedPreferences.getBoolean(getString(R.string.display_webpage_images_key), true)
2798 // 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.
2799 webViewThemeEntryValuesStringArray = resources.getStringArray(R.array.webview_theme_entry_values)
2801 // 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.
2802 userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item)
2803 userAgentDataArray = resources.getStringArray(R.array.user_agent_data)
2805 // Store the values from the shared preferences in variables.
2806 incognitoModeEnabled = sharedPreferences.getBoolean(getString(R.string.incognito_mode_key), false)
2807 sanitizeTrackingQueries = sharedPreferences.getBoolean(getString(R.string.tracking_queries_key), true)
2808 sanitizeAmpRedirects = sharedPreferences.getBoolean(getString(R.string.amp_redirects_key), true)
2809 proxyMode = sharedPreferences.getString(getString(R.string.proxy_key), getString(R.string.proxy_default_value))!!
2810 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean(getString(R.string.full_screen_browsing_mode_key), false)
2811 hideAppBar = sharedPreferences.getBoolean(getString(R.string.hide_app_bar_key), true)
2812 downloadWithExternalApp = sharedPreferences.getBoolean(getString(R.string.download_with_external_app_key), false)
2813 scrollAppBar = sharedPreferences.getBoolean(getString(R.string.scroll_app_bar_key), true)
2815 // Apply the saved proxy mode if the app has been restarted.
2816 if (savedProxyMode != null) {
2817 // Apply the saved proxy mode.
2818 proxyMode = savedProxyMode!!
2820 // Reset the saved proxy mode.
2821 savedProxyMode = null
2824 // Get the search string.
2825 val searchString = sharedPreferences.getString(getString(R.string.search_key), getString(R.string.search_default_value))!!
2827 // Set the search string, using the custom search URL if specified.
2828 searchURL = if (searchString == getString(R.string.custom_url_item))
2829 sharedPreferences.getString(getString(R.string.search_custom_url_key), getString(R.string.search_custom_url_default_value))!!
2836 // Adjust the layout and scrolling parameters according to the position of the app bar.
2837 if (bottomAppBar) { // The app bar is on the bottom.
2839 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) { // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
2840 // Reset the WebView padding to fill the available space.
2841 swipeRefreshLayout.setPadding(0, 0, 0, 0)
2842 } else { // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
2843 // Move the WebView above the app bar layout.
2844 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
2846 // Show the app bar if it is scrolled off the screen.
2847 if (appBarLayout.translationY != 0f) {
2848 // Animate the bottom app bar onto the screen.
2849 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0f)
2852 objectAnimator.start()
2855 } else { // The app bar is on the top.
2856 // Get the current layout parameters. Using coordinator layout parameters allows the `setBehavior()` command and using app bar layout parameters allows the `setScrollFlags()` command.
2857 val swipeRefreshLayoutParams = swipeRefreshLayout.layoutParams as CoordinatorLayout.LayoutParams
2858 val toolbarLayoutParams = toolbar.layoutParams as AppBarLayout.LayoutParams
2859 val findOnPageLayoutParams = findOnPageLinearLayout.layoutParams as AppBarLayout.LayoutParams
2860 val tabsLayoutParams = tabsLinearLayout.layoutParams as AppBarLayout.LayoutParams
2862 // Add the scrolling behavior to the layout parameters.
2864 // Enable scrolling of the app bar.
2865 swipeRefreshLayoutParams.behavior = AppBarLayout.ScrollingViewBehavior()
2866 toolbarLayoutParams.scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS or AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP
2867 findOnPageLayoutParams.scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS or AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP
2868 tabsLayoutParams.scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS or AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP
2870 // Disable scrolling of the app bar.
2871 swipeRefreshLayoutParams.behavior = null
2872 toolbarLayoutParams.scrollFlags = 0
2873 findOnPageLayoutParams.scrollFlags = 0
2874 tabsLayoutParams.scrollFlags = 0
2876 // Expand the app bar if it is currently collapsed.
2877 appBarLayout.setExpanded(true)
2880 // Set the app bar scrolling for each WebView.
2881 for (i in 0 until webViewStateAdapter!!.itemCount) {
2882 // Get the WebView tab fragment.
2883 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
2885 // Get the fragment view.
2886 val fragmentView = webViewTabFragment.view
2888 // Only modify the WebViews if they exist.
2889 if (fragmentView != null) {
2890 // Get the nested scroll WebView from the tab fragment.
2891 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
2893 // Set the app bar scrolling.
2894 nestedScrollWebView.isNestedScrollingEnabled = scrollAppBar
2899 // Update the full screen browsing mode settings.
2900 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
2901 // Update the visibility of the app bar, which might have changed in the settings.
2903 // Hide the tab linear layout.
2904 tabsLinearLayout.visibility = View.GONE
2906 // Hide the app bar.
2909 // Show the tab linear layout.
2910 tabsLinearLayout.visibility = View.VISIBLE
2912 // Show the app bar.
2916 /* Hide the system bars.
2917 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2918 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
2919 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2920 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
2923 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
2924 @Suppress("DEPRECATION")
2925 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
2926 } else { // Privacy Browser is not in full screen browsing mode.
2927 // 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.
2928 inFullScreenBrowsingMode = false
2930 // Show the tab linear layout.
2931 tabsLinearLayout.visibility = View.VISIBLE
2933 // Show the app bar.
2936 // Remove the `SYSTEM_UI` flags from the root frame layout. The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
2937 @Suppress("DEPRECATION")
2938 rootFrameLayout.systemUiVisibility = 0
2942 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
2943 @SuppressLint("SetJavaScriptEnabled")
2944 private fun applyDomainSettings(nestedScrollWebView: NestedScrollWebView, url: String?, resetTab: Boolean, reloadWebsite: Boolean, loadUrl: Boolean) {
2945 // Store the current URL.
2946 nestedScrollWebView.currentUrl = url!!
2948 // Parse the URL into a URI.
2949 val uri = Uri.parse(url)
2951 // Extract the domain from the URI.
2952 var newHostName = uri.host
2954 // Strings don't like to be null.
2955 if (newHostName == null)
2958 // 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.
2959 if ((nestedScrollWebView.currentDomainName != newHostName) || (newHostName == "")) { // A new domain is being loaded.
2960 // Set the new host name as the current domain name.
2961 nestedScrollWebView.currentDomainName = newHostName
2963 // Reset the ignoring of pinned domain information.
2964 nestedScrollWebView.ignorePinnedDomainInformation = false
2966 // Clear any pinned SSL certificate or IP addresses.
2967 nestedScrollWebView.clearPinnedSslCertificate()
2968 nestedScrollWebView.pinnedIpAddresses = ""
2970 // Reset the favorite icon if specified.
2972 // Initialize the favorite icon.
2973 nestedScrollWebView.initializeFavoriteIcon()
2975 // Get the current page position.
2976 val currentPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
2978 // Get the corresponding tab.
2979 val tab = tabLayout.getTabAt(currentPagePosition)
2981 // Update the tab if it isn't null, which sometimes happens when restarting from the background.
2983 // Get the tab custom view.
2984 val tabCustomView = tab.customView!!
2986 // Get the tab views.
2987 val tabFavoriteIconImageView = tabCustomView.findViewById<ImageView>(R.id.favorite_icon_imageview)
2988 val tabTitleTextView = tabCustomView.findViewById<TextView>(R.id.title_textview)
2990 // Set the default favorite icon as the favorite icon for this tab.
2991 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nestedScrollWebView.getFavoriteIcon(), 64, 64, true))
2993 // Set the loading title text.
2994 tabTitleTextView.setText(R.string.loading)
2998 // Initialize the domain name in database variable.
2999 var domainNameInDatabase: String? = null
3001 // Check the hostname against the domain settings set.
3002 if (domainsSettingsSet.contains(newHostName)) { // The hostname is contained in the domain settings set.
3003 // Record the domain name in the database.
3004 domainNameInDatabase = newHostName
3006 // Set the domain settings applied tracker to true.
3007 nestedScrollWebView.domainSettingsApplied = true
3008 } else { // The hostname is not contained in the domain settings set.
3009 // Set the domain settings applied tracker to false.
3010 nestedScrollWebView.domainSettingsApplied = false
3013 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3014 while (!nestedScrollWebView.domainSettingsApplied && newHostName!!.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the hostname.
3015 if (domainsSettingsSet.contains("*.$newHostName")) { // Check the host name prepended by `*.`.
3016 // Set the domain settings applied tracker to true.
3017 nestedScrollWebView.domainSettingsApplied = true
3019 // Store the applied domain names as it appears in the database.
3020 domainNameInDatabase = "*.$newHostName"
3023 // Strip out the lowest subdomain of of the host name.
3024 newHostName = newHostName.substring(newHostName.indexOf(".") + 1)
3027 // Apply either the domain settings or the default settings.
3028 if (nestedScrollWebView.domainSettingsApplied) { // The url has custom domain settings.
3029 // Get a cursor for the current host.
3030 val currentDomainSettingsCursor = domainsDatabaseHelper!!.getCursorForDomainName(domainNameInDatabase!!)
3032 // Move to the first position.
3033 currentDomainSettingsCursor.moveToFirst()
3035 // Get the settings from the cursor.
3036 nestedScrollWebView.domainSettingsDatabaseId = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ID))
3037 val javaScriptInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_JAVASCRIPT))
3038 val cookiesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(COOKIES))
3039 val domStorageInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_DOM_STORAGE))
3040 val formDataInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_FORM_DATA)) // Form data can be removed once the minimum API >= 26.
3041 val easyListInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_EASYLIST))
3042 val easyPrivacyInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_EASYPRIVACY))
3043 val fanboysAnnoyanceListInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_FANBOYS_ANNOYANCE_LIST))
3044 val fanboysSocialBlockingListInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST))
3045 val ultraListInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.ULTRALIST))
3046 val ultraPrivacyInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_ULTRAPRIVACY))
3047 val blockAllThirdPartyRequestsInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.BLOCK_ALL_THIRD_PARTY_REQUESTS))
3048 val userAgentName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.USER_AGENT))
3049 val fontSize = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(FONT_SIZE))
3050 val swipeToRefreshInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(SWIPE_TO_REFRESH))
3051 val webViewThemeInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(WEBVIEW_THEME))
3052 val wideViewportInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(WIDE_VIEWPORT))
3053 val displayWebpageImagesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DISPLAY_IMAGES))
3054 val pinnedSslCertificate = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(PINNED_SSL_CERTIFICATE)) == 1)
3055 val pinnedSslIssuedToCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_TO_COMMON_NAME))
3056 val pinnedSslIssuedToOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_TO_ORGANIZATION))
3057 val pinnedSslIssuedToUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_TO_ORGANIZATIONAL_UNIT))
3058 val pinnedSslIssuedByCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_BY_COMMON_NAME))
3059 val pinnedSslIssuedByOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_BY_ORGANIZATION))
3060 val pinnedSslIssuedByUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_BY_ORGANIZATIONAL_UNIT))
3061 val pinnedSslStartDate = Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.SSL_START_DATE)))
3062 val pinnedSslEndDate = Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.SSL_END_DATE)))
3063 val pinnedIpAddresses = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(PINNED_IP_ADDRESSES)) == 1)
3064 val pinnedHostIpAddresses = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(IP_ADDRESSES))
3066 // Close the current host domain settings cursor.
3067 currentDomainSettingsCursor.close()
3069 // Set the JavaScript status.
3070 when (javaScriptInt) {
3071 SYSTEM_DEFAULT -> nestedScrollWebView.settings.javaScriptEnabled = defaultJavaScript
3072 ENABLED -> nestedScrollWebView.settings.javaScriptEnabled = true
3073 DISABLED -> nestedScrollWebView.settings.javaScriptEnabled = false
3076 // Store the cookies status.
3078 SYSTEM_DEFAULT -> nestedScrollWebView.acceptCookies = defaultCookies
3079 ENABLED -> nestedScrollWebView.acceptCookies = true
3080 DISABLED -> nestedScrollWebView.acceptCookies = false
3083 // Apply the cookies status.
3084 cookieManager.setAcceptCookie(nestedScrollWebView.acceptCookies)
3086 // Set the DOM storage status.
3087 when (domStorageInt) {
3088 SYSTEM_DEFAULT -> nestedScrollWebView.settings.domStorageEnabled = defaultDomStorage
3089 ENABLED -> nestedScrollWebView.settings.domStorageEnabled = true
3090 DISABLED -> nestedScrollWebView.settings.domStorageEnabled = false
3093 // Apply the form data setting if the API < 26.
3094 @Suppress("DEPRECATION")
3095 if (Build.VERSION.SDK_INT < 26) {
3096 // Set the form data status.
3097 when (formDataInt) {
3098 SYSTEM_DEFAULT -> nestedScrollWebView.settings.saveFormData = defaultFormData
3099 ENABLED -> nestedScrollWebView.settings.saveFormData = true
3100 DISABLED -> nestedScrollWebView.settings.saveFormData = false
3104 // Set the EasyList status.
3105 when (easyListInt) {
3106 SYSTEM_DEFAULT -> nestedScrollWebView.easyListEnabled = defaultEasyList
3107 ENABLED -> nestedScrollWebView.easyListEnabled = true
3108 DISABLED -> nestedScrollWebView.easyListEnabled = false
3111 // Set the EasyPrivacy status.
3112 when (easyPrivacyInt) {
3113 SYSTEM_DEFAULT -> nestedScrollWebView.easyPrivacyEnabled = defaultEasyPrivacy
3114 ENABLED -> nestedScrollWebView.easyPrivacyEnabled = true
3115 DISABLED -> nestedScrollWebView.easyPrivacyEnabled = false
3118 // Set the Fanboy's Annoyance List status.
3119 when (fanboysAnnoyanceListInt) {
3120 SYSTEM_DEFAULT -> nestedScrollWebView.fanboysAnnoyanceListEnabled = defaultFanboysAnnoyanceList
3121 ENABLED -> nestedScrollWebView.fanboysAnnoyanceListEnabled = true
3122 DISABLED -> nestedScrollWebView.fanboysAnnoyanceListEnabled = false
3125 // Set the Fanboy's Social Blocking List status.
3126 when (fanboysSocialBlockingListInt) {
3127 SYSTEM_DEFAULT -> nestedScrollWebView.fanboysSocialBlockingListEnabled = defaultFanboysSocialBlockingList
3128 ENABLED -> nestedScrollWebView.fanboysSocialBlockingListEnabled = true
3129 DISABLED -> nestedScrollWebView.fanboysSocialBlockingListEnabled = false
3132 // Set the UltraList status.
3133 when (ultraListInt) {
3134 SYSTEM_DEFAULT -> nestedScrollWebView.ultraListEnabled = defaultUltraList
3135 ENABLED -> nestedScrollWebView.ultraListEnabled = true
3136 DISABLED -> nestedScrollWebView.ultraListEnabled = false
3139 // Set the UltraPrivacy status.
3140 when (ultraPrivacyInt) {
3141 SYSTEM_DEFAULT -> nestedScrollWebView.ultraPrivacyEnabled = defaultUltraPrivacy
3142 ENABLED -> nestedScrollWebView.ultraPrivacyEnabled = true
3143 DISABLED -> nestedScrollWebView.ultraPrivacyEnabled = false
3146 // Set the block all third-party requests status.
3147 when (blockAllThirdPartyRequestsInt) {
3148 SYSTEM_DEFAULT -> nestedScrollWebView.blockAllThirdPartyRequests = defaultBlockAllThirdPartyRequests
3149 ENABLED -> nestedScrollWebView.blockAllThirdPartyRequests = true
3150 DISABLED -> nestedScrollWebView.blockAllThirdPartyRequests = false
3153 // Set the user agent.
3154 if (userAgentName == getString(R.string.system_default_user_agent)) { // Use the system default user agent.
3155 // Set the user agent according to the system default.
3156 when (val defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName)) {
3157 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3158 UNRECOGNIZED_USER_AGENT -> nestedScrollWebView.settings.userAgentString = defaultUserAgentName
3160 // Set the user agent to `""`, which uses the default value.
3161 SETTINGS_WEBVIEW_DEFAULT_USER_AGENT -> nestedScrollWebView.settings.userAgentString = ""
3163 // Set the default custom user agent.
3164 SETTINGS_CUSTOM_USER_AGENT -> nestedScrollWebView.settings.userAgentString =
3165 sharedPreferences.getString(getString(R.string.custom_user_agent_key), getString(R.string.custom_user_agent_default_value))
3167 // Get the user agent string from the user agent data array
3168 else -> nestedScrollWebView.settings.userAgentString = userAgentDataArray[defaultUserAgentArrayPosition]
3170 } else { // Set the user agent according to the stored name.
3171 // Set the user agent.
3172 when (val userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName)) {
3173 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3174 UNRECOGNIZED_USER_AGENT ->
3175 nestedScrollWebView.settings.userAgentString = userAgentName
3177 // Set the user agent to `""`, which uses the default value.
3178 SETTINGS_WEBVIEW_DEFAULT_USER_AGENT ->
3179 nestedScrollWebView.settings.userAgentString = ""
3181 // Get the user agent string from the user agent data array.
3183 nestedScrollWebView.settings.userAgentString = userAgentDataArray[userAgentArrayPosition]
3187 // Apply the font size.
3188 try { // Try the specified font size to see if it is valid.
3189 if (fontSize == 0) { // Apply the default font size.
3190 // Set the font size from the value in the app settings.
3191 nestedScrollWebView.settings.textZoom = defaultFontSizeString.toInt()
3192 } else { // Apply the font size from domain settings.
3193 nestedScrollWebView.settings.textZoom = fontSize
3195 } catch (exception: Exception) { // The specified font size is invalid
3196 // Set the font size to be 100%
3197 nestedScrollWebView.settings.textZoom = 100
3200 // Set swipe to refresh.
3201 when (swipeToRefreshInt) {
3203 // Store the swipe to refresh status in the nested scroll WebView.
3204 nestedScrollWebView.swipeToRefresh = defaultSwipeToRefresh
3206 // Update the swipe refresh layout.
3207 if (defaultSwipeToRefresh) { // Swipe to refresh is enabled.
3208 // 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).
3209 if (currentWebView != null) {
3210 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
3211 swipeRefreshLayout.isEnabled = (currentWebView!!.scrollY == 0)
3213 } else { // Swipe to refresh is disabled.
3214 // Disable the swipe refresh layout.
3215 swipeRefreshLayout.isEnabled = false
3220 // Store the swipe to refresh status in the nested scroll WebView.
3221 nestedScrollWebView.swipeToRefresh = true
3223 // 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).
3224 if (currentWebView != null) {
3225 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
3226 swipeRefreshLayout.isEnabled = (currentWebView!!.scrollY == 0)
3231 // Store the swipe to refresh status in the nested scroll WebView.
3232 nestedScrollWebView.swipeToRefresh = false
3234 // Disable swipe to refresh.
3235 swipeRefreshLayout.isEnabled = false
3239 // Set the WebView theme if algorithmic darkening is supported.
3240 if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {
3241 // Set the WebView theme.
3242 when (webViewThemeInt) {
3243 // Set the WebView theme.
3245 when (defaultWebViewTheme) {
3246 // The light theme is selected. Turn off algorithmic darkening.
3247 webViewThemeEntryValuesStringArray[1] -> WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
3249 // The dark theme is selected. Turn on algorithmic darkening.
3250 webViewThemeEntryValuesStringArray[2] -> WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
3252 // The system default theme is selected.
3254 // Get the current system theme status.
3255 val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
3257 // Set the algorithmic darkening according to the current system theme status.
3258 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, currentThemeStatus == Configuration.UI_MODE_NIGHT_YES)
3262 // Turn off algorithmic darkening.
3263 LIGHT_THEME -> WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
3265 // Turn on algorithmic darkening.
3266 DARK_THEME -> WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
3270 // Set the wide viewport status.
3271 when (wideViewportInt) {
3272 SYSTEM_DEFAULT -> nestedScrollWebView.settings.useWideViewPort = defaultWideViewport
3273 ENABLED -> nestedScrollWebView.settings.useWideViewPort = true
3274 DISABLED -> nestedScrollWebView.settings.useWideViewPort = false
3277 // Set the display webpage images status.
3278 when (displayWebpageImagesInt) {
3279 SYSTEM_DEFAULT -> nestedScrollWebView.settings.loadsImagesAutomatically = defaultDisplayWebpageImages
3280 ENABLED -> nestedScrollWebView.settings.loadsImagesAutomatically = true
3281 DISABLED -> nestedScrollWebView.settings.loadsImagesAutomatically = false
3284 // If there is a pinned SSL certificate, store it in the WebView.
3285 if (pinnedSslCertificate)
3286 nestedScrollWebView.setPinnedSslCertificate(pinnedSslIssuedToCName, pinnedSslIssuedToOName, pinnedSslIssuedToUName, pinnedSslIssuedByCName, pinnedSslIssuedByOName, pinnedSslIssuedByUName,
3287 pinnedSslStartDate, pinnedSslEndDate)
3289 // If there is a pinned IP address, store it in the WebView.
3290 if (pinnedIpAddresses)
3291 nestedScrollWebView.pinnedIpAddresses = pinnedHostIpAddresses
3293 // Set a background on the URL relative layout to indicate that custom domain settings are being used.
3294 urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.drawable.domain_settings_url_background)
3295 } else { // The new URL does not have custom domain settings. Load the defaults.
3296 // Store the values from the shared preferences.
3297 nestedScrollWebView.settings.javaScriptEnabled = defaultJavaScript
3298 nestedScrollWebView.acceptCookies = defaultCookies
3299 nestedScrollWebView.settings.domStorageEnabled = defaultDomStorage
3300 nestedScrollWebView.easyListEnabled = defaultEasyList
3301 nestedScrollWebView.easyPrivacyEnabled = defaultEasyPrivacy
3302 nestedScrollWebView.fanboysAnnoyanceListEnabled = defaultFanboysAnnoyanceList
3303 nestedScrollWebView.fanboysSocialBlockingListEnabled = defaultFanboysSocialBlockingList
3304 nestedScrollWebView.ultraListEnabled = defaultUltraList
3305 nestedScrollWebView.ultraPrivacyEnabled = defaultUltraPrivacy
3306 nestedScrollWebView.blockAllThirdPartyRequests = defaultBlockAllThirdPartyRequests
3308 // Apply the default cookie setting.
3309 cookieManager.setAcceptCookie(nestedScrollWebView.acceptCookies)
3311 // Apply the form data setting if the API < 26.
3312 if (Build.VERSION.SDK_INT < 26)
3313 @Suppress("DEPRECATION")
3314 nestedScrollWebView.settings.saveFormData = defaultFormData
3316 // Apply the default font size setting.
3318 // Try to set the font size from the value in the app settings.
3319 nestedScrollWebView.settings.textZoom = defaultFontSizeString.toInt()
3320 } catch (exception: Exception) {
3321 // If the app settings value is invalid, set the font size to 100%.
3322 nestedScrollWebView.settings.textZoom = 100
3325 // Store the swipe to refresh status in the nested scroll WebView.
3326 nestedScrollWebView.swipeToRefresh = defaultSwipeToRefresh
3328 // Update the swipe refresh layout.
3329 if (defaultSwipeToRefresh) { // Swipe to refresh is enabled.
3330 // 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).
3331 if (currentWebView != null) {
3332 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
3333 swipeRefreshLayout.isEnabled = currentWebView!!.scrollY == 0
3335 } else { // Swipe to refresh is disabled.
3336 // Disable the swipe refresh layout.
3337 swipeRefreshLayout.isEnabled = false
3340 // Reset the domain settings database ID.
3341 nestedScrollWebView.domainSettingsDatabaseId = -1
3343 // Set the user agent.
3344 when (val userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName)) {
3345 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3346 UNRECOGNIZED_USER_AGENT -> nestedScrollWebView.settings.userAgentString = defaultUserAgentName
3348 // Set the user agent to `""`, which uses the default value.
3349 SETTINGS_WEBVIEW_DEFAULT_USER_AGENT -> nestedScrollWebView.settings.userAgentString = ""
3351 // Set the default custom user agent.
3352 SETTINGS_CUSTOM_USER_AGENT -> nestedScrollWebView.settings.userAgentString =
3353 sharedPreferences.getString(getString(R.string.custom_user_agent_key), getString(R.string.custom_user_agent_default_value))
3355 // Get the user agent string from the user agent data array
3356 else -> nestedScrollWebView.settings.userAgentString = userAgentDataArray[userAgentArrayPosition]
3359 // Set the WebView theme if algorithmic darkening is supported.
3360 if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {
3361 // Set the WebView theme.
3362 when (defaultWebViewTheme) {
3363 // The light theme is selected. Turn off algorithmic darkening.
3364 webViewThemeEntryValuesStringArray[1] -> WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
3366 // The dark theme is selected. Turn on algorithmic darkening.
3367 webViewThemeEntryValuesStringArray[2] -> WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
3369 // The system default theme is selected. Get the current system theme status.
3371 // Get the current theme status.
3372 val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
3374 // Set the algorithmic darkening according to the current system theme status.
3375 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, currentThemeStatus == Configuration.UI_MODE_NIGHT_YES)
3380 // Set the viewport.
3381 nestedScrollWebView.settings.useWideViewPort = defaultWideViewport
3383 // Set the loading of webpage images.
3384 nestedScrollWebView.settings.loadsImagesAutomatically = defaultDisplayWebpageImages
3386 // Set a transparent background on the URL relative layout.
3387 urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.color.transparent)
3390 // Update the privacy icons.
3391 updatePrivacyIcons(true)
3394 // Reload the website if returning from the Domains activity.
3396 nestedScrollWebView.reload()
3398 // 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.
3400 nestedScrollWebView.loadUrl(url)
3403 private fun applyProxy(reloadWebViews: Boolean) {
3404 // Set the proxy according to the mode.
3405 proxyHelper.setProxy(applicationContext, appBarLayout, proxyMode)
3407 // Reset the waiting for proxy tracker.
3408 waitingForProxy = false
3412 ProxyHelper.NONE -> {
3413 // Initialize a color background typed value.
3414 val colorBackgroundTypedValue = TypedValue()
3416 // Get the color background from the theme.
3417 theme.resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true)
3419 // Get the color background int from the typed value.
3420 val colorBackgroundInt = colorBackgroundTypedValue.data
3422 // Set the default app bar layout background.
3423 appBarLayout.setBackgroundColor(colorBackgroundInt)
3426 ProxyHelper.TOR -> {
3427 // Set the app bar background to indicate proxying is enabled.
3428 appBarLayout.setBackgroundResource(R.color.blue_background)
3430 // Check to see if Orbot is installed.
3432 // Get the package manager.
3433 val packageManager = packageManager
3435 // 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.
3436 @Suppress("DEPRECATION")
3437 packageManager.getPackageInfo("org.torproject.android", 0)
3439 // Check to see if the proxy is ready.
3440 if (orbotStatus != ProxyHelper.ORBOT_STATUS_ON) { // Orbot is not ready.
3441 // Set the waiting for proxy status.
3442 waitingForProxy = true
3444 // Show the waiting for proxy dialog if it isn't already displayed.
3445 if (supportFragmentManager.findFragmentByTag(getString(R.string.waiting_for_proxy_dialog)) == null) {
3446 // Get a handle for the waiting for proxy alert dialog.
3447 val waitingForProxyDialogFragment = WaitingForProxyDialog()
3449 // Try to show the dialog. Sometimes the window is not yet active if returning from Settings.
3451 // Show the waiting for proxy alert dialog.
3452 waitingForProxyDialogFragment.show(supportFragmentManager, getString(R.string.waiting_for_proxy_dialog))
3453 } catch (waitingForTorException: Exception) {
3454 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
3455 pendingDialogsArrayList.add(PendingDialogDataClass(waitingForProxyDialogFragment, getString(R.string.waiting_for_proxy_dialog)))
3459 } catch (exception: PackageManager.NameNotFoundException) { // Orbot is not installed.
3460 // Show the Orbot not installed dialog if it is not already displayed.
3461 if (supportFragmentManager.findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
3462 // Get a handle for the Orbot not installed alert dialog.
3463 val orbotNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode)
3465 // Try to show the dialog. Sometimes the window is not yet active if returning from Settings.
3467 // Display the Orbot not installed alert dialog.
3468 orbotNotInstalledDialogFragment.show(supportFragmentManager, getString(R.string.proxy_not_installed_dialog))
3469 } catch (orbotNotInstalledException: Exception) {
3470 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
3471 pendingDialogsArrayList.add(PendingDialogDataClass(orbotNotInstalledDialogFragment, getString(R.string.proxy_not_installed_dialog)))
3477 ProxyHelper.I2P -> {
3478 // Set the app bar background to indicate proxying is enabled.
3479 appBarLayout.setBackgroundResource(R.color.blue_background)
3481 // Check to see if I2P is installed.
3483 // 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.
3484 // The deprecated method must be used until the minimum API >= 33.
3485 @Suppress("DEPRECATION")
3486 packageManager.getPackageInfo("net.i2p.android.router", 0)
3487 } catch (fdroidException: PackageManager.NameNotFoundException) { // The F-Droid flavor is not installed.
3489 // 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.
3490 // The deprecated method must be used until the minimum API >= 33.
3491 @Suppress("DEPRECATION")
3492 packageManager.getPackageInfo("net.i2p.android", 0)
3493 } catch (googlePlayException: PackageManager.NameNotFoundException) { // The Google Play flavor is not installed.
3494 // Sow the I2P not installed dialog if it is not already displayed.
3495 if (supportFragmentManager.findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
3496 // Get a handle for the waiting for proxy alert dialog.
3497 val i2pNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode)
3499 // Try to show the dialog. Sometimes the window is not yet active if returning from Settings.
3501 // Display the I2P not installed alert dialog.
3502 i2pNotInstalledDialogFragment.show(supportFragmentManager, getString(R.string.proxy_not_installed_dialog))
3503 } catch (i2pNotInstalledException: Exception) {
3504 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
3505 pendingDialogsArrayList.add(PendingDialogDataClass(i2pNotInstalledDialogFragment, getString(R.string.proxy_not_installed_dialog)))
3512 ProxyHelper.CUSTOM ->
3513 // Set the app bar background to indicate proxying is enabled.
3514 appBarLayout.setBackgroundResource(R.color.blue_background)
3517 // Reload the WebViews if requested and not waiting for the proxy.
3518 if (reloadWebViews && !waitingForProxy) {
3519 // Reload the WebViews.
3520 for (i in 0 until webViewStateAdapter!!.itemCount) {
3521 // Get the WebView tab fragment.
3522 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
3524 // Get the fragment view.
3525 val fragmentView = webViewTabFragment.view
3527 // Only reload the WebViews if they exist.
3528 if (fragmentView != null) {
3529 // Get the nested scroll WebView from the tab fragment.
3530 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
3532 // Reload the WebView.
3533 nestedScrollWebView.reload()
3539 // The view parameter cannot be removed because it is called from the layout onClick.
3540 fun bookmarksBack(@Suppress("UNUSED_PARAMETER")view: View?) {
3541 if (currentBookmarksFolderId == HOME_FOLDER_ID) { // The home folder is displayed.
3542 // close the bookmarks drawer.
3543 drawerLayout.closeDrawer(GravityCompat.END)
3544 } else { // A subfolder is displayed.
3545 // Set the former parent folder as the current folder.
3546 currentBookmarksFolderId = bookmarksDatabaseHelper!!.getParentFolderId(currentBookmarksFolderId)
3548 // Load the new folder.
3549 loadBookmarksFolder()
3553 private fun clearAndExit() {
3554 // Close the bookmarks cursor if it exists.
3555 bookmarksCursor?.close()
3557 // Close the databases helpers if they exist.
3558 bookmarksDatabaseHelper?.close()
3559 domainsDatabaseHelper?.close()
3561 // Get the status of the clear everything preference.
3562 val clearEverything = sharedPreferences.getBoolean(getString(R.string.clear_everything_key), true)
3564 // Get a handle for the runtime.
3565 val runtime = Runtime.getRuntime()
3567 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
3568 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
3569 val privateDataDirectoryString = applicationInfo.dataDir
3572 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_cookies_key), true)) {
3573 // Ass the cookie manager to delete all the cookies.
3574 cookieManager.removeAllCookies(null)
3576 // Ask the cookie manager to flush the cookie database.
3577 cookieManager.flush()
3579 // Manually delete the cookies database, as the cookie manager sometimes will not flush its changes to disk before system exit is run.
3581 // Two commands must be used because `Runtime.exec()` does not like `*`.
3582 val deleteCookiesProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/Cookies")
3583 val deleteCookiesJournalProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/Cookies-journal")
3585 // Wait until the processes have finished.
3586 deleteCookiesProcess.waitFor()
3587 deleteCookiesJournalProcess.waitFor()
3588 } catch (exception: Exception) {
3589 // Do nothing if an error is thrown.
3593 // Clear DOM storage.
3594 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_dom_storage_key), true)) {
3595 // Ask web storage to clear the DOM storage.
3596 WebStorage.getInstance().deleteAllData()
3598 // Manually delete the DOM storage files and directories, as web storage sometimes will not flush its changes to disk before system exit is run.
3600 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
3601 val deleteLocalStorageProcess = runtime.exec(arrayOf("rm", "-rf", "$privateDataDirectoryString/app_webview/Local Storage/"))
3603 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
3604 val deleteIndexProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview/IndexedDB")
3605 val deleteQuotaManagerProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/QuotaManager")
3606 val deleteQuotaManagerJournalProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/QuotaManager-journal")
3607 val deleteDatabaseProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview/databases")
3609 // Wait until the processes have finished.
3610 deleteLocalStorageProcess.waitFor()
3611 deleteIndexProcess.waitFor()
3612 deleteQuotaManagerProcess.waitFor()
3613 deleteQuotaManagerJournalProcess.waitFor()
3614 deleteDatabaseProcess.waitFor()
3615 } catch (exception: Exception) {
3616 // Do nothing if an error is thrown.
3620 // Clear form data if the API < 26.
3621 if (Build.VERSION.SDK_INT < 26 && (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_form_data_key), true))) {
3622 // Ask the WebView database to clear the form data.
3623 @Suppress("DEPRECATION")
3624 WebViewDatabase.getInstance(this).clearFormData()
3626 // Manually delete the form data database, as the WebView database sometimes will not flush its changes to disk before system exit is run.
3628 // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
3629 val deleteWebDataProcess = runtime.exec(arrayOf("rm", "-f", "$privateDataDirectoryString/app_webview/Web Data"))
3630 val deleteWebDataJournalProcess = runtime.exec(arrayOf("rm", "-f", "$privateDataDirectoryString/app_webview/Web Data-journal"))
3632 // Wait until the processes have finished.
3633 deleteWebDataProcess.waitFor()
3634 deleteWebDataJournalProcess.waitFor()
3635 } catch (exception: Exception) {
3636 // Do nothing if an error is thrown.
3640 // Clear the logcat.
3641 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_logcat_key), true)) {
3643 // Clear the logcat. `-c` clears the logcat. `-b all` clears all the buffers (instead of just crash, main, and system).
3644 val process = Runtime.getRuntime().exec("logcat -b all -c")
3646 // Wait for the process to finish.
3648 } catch (exception: IOException) {
3650 } catch (exception: InterruptedException) {
3656 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_cache_key), true)) {
3657 // Clear the cache from each WebView.
3658 for (i in 0 until webViewStateAdapter!!.itemCount) {
3659 // Get the WebView tab fragment.
3660 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
3662 // Get the WebView fragment view.
3663 val webViewFragmentView = webViewTabFragment.view
3665 // Only clear the cache if the WebView exists.
3666 if (webViewFragmentView != null) {
3667 // Get the nested scroll WebView from the tab fragment.
3668 val nestedScrollWebView = webViewFragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
3670 // Clear the cache for this WebView.
3671 nestedScrollWebView.clearCache(true)
3675 // Manually delete the cache directories.
3677 // Delete the main cache directory.
3678 val deleteCacheProcess = runtime.exec("rm -rf $privateDataDirectoryString/cache")
3680 // Delete the secondary `Service Worker` cache directory.
3681 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
3682 val deleteServiceWorkerProcess = runtime.exec(arrayOf("rm", "-rf", "$privateDataDirectoryString/app_webview/Default/Service Worker/"))
3684 // Wait until the processes have finished.
3685 deleteCacheProcess.waitFor()
3686 deleteServiceWorkerProcess.waitFor()
3687 } catch (exception: Exception) {
3688 // Do nothing if an error is thrown.
3692 // Wipe out each WebView.
3693 for (i in 0 until webViewStateAdapter!!.itemCount) {
3694 // Get the WebView tab fragment.
3695 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
3697 // Get the WebView frame layout.
3698 val webViewFrameLayout = webViewTabFragment.view as FrameLayout?
3700 // Only wipe out the WebView if it exists.
3701 if (webViewFrameLayout != null) {
3702 // Get the nested scroll WebView from the tab fragment.
3703 val nestedScrollWebView = webViewFrameLayout.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
3705 // Clear SSL certificate preferences for this WebView.
3706 nestedScrollWebView.clearSslPreferences()
3708 // Clear the back/forward history for this WebView.
3709 nestedScrollWebView.clearHistory()
3711 // Remove all the views from the frame layout.
3712 webViewFrameLayout.removeAllViews()
3714 // Destroy the internal state of the WebView.
3715 nestedScrollWebView.destroy()
3719 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
3720 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
3721 if (clearEverything) {
3723 // Delete the folder.
3724 val deleteAppWebviewProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview")
3726 // Wait until the process has finished.
3727 deleteAppWebviewProcess.waitFor()
3728 } catch (exception: Exception) {
3729 // Do nothing if an error is thrown.
3733 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
3734 finishAndRemoveTask()
3736 // Remove the terminated program from RAM. The status code is `0`.
3740 // The view parameter cannot be removed because it is called from the layout onClick.
3741 fun closeFindOnPage(@Suppress("UNUSED_PARAMETER")view: View?) {
3742 // Delete the contents of the find on page edit text.
3743 findOnPageEditText.text = null
3745 // Clear the highlighted phrases if the WebView is not null.
3746 currentWebView?.clearMatches()
3748 // Hide the find on page linear layout.
3749 findOnPageLinearLayout.visibility = View.GONE
3751 // Show the toolbar.
3752 toolbar.visibility = View.VISIBLE
3754 // Get a handle for the input method manager.
3755 val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
3757 // Hide the keyboard.
3758 inputMethodManager.hideSoftInputFromWindow(toolbar.windowToken, 0)
3761 // The view parameter cannot be removed because it is called from the layout onClick.
3762 fun closeTab(@Suppress("UNUSED_PARAMETER")view: View?) {
3763 // Run the command according to the number of tabs.
3764 if (tabLayout.tabCount > 1) { // There is more than one tab open.
3765 // Get the current tab number.
3766 val currentTabNumber = tabLayout.selectedTabPosition
3768 // Delete the current tab.
3769 tabLayout.removeTabAt(currentTabNumber)
3771 // 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,
3772 // meaning that the current WebView must be reset. Otherwise it will happen automatically as the selected tab number changes.
3773 if (webViewStateAdapter!!.deletePage(currentTabNumber, webViewViewPager2))
3774 setCurrentWebView(currentTabNumber)
3775 } else { // There is only one tab open.
3780 override fun createBookmark(dialogFragment: DialogFragment, favoriteIconBitmap: Bitmap) {
3782 val dialog = dialogFragment.dialog!!
3784 // Get the views from the dialog fragment.
3785 val createBookmarkNameEditText = dialog.findViewById<EditText>(R.id.create_bookmark_name_edittext)
3786 val createBookmarkUrlEditText = dialog.findViewById<EditText>(R.id.create_bookmark_url_edittext)
3788 // Extract the strings from the edit texts.
3789 val bookmarkNameString = createBookmarkNameEditText.text.toString()
3790 val bookmarkUrlString = createBookmarkUrlEditText.text.toString()
3792 // Create a favorite icon byte array output stream.
3793 val favoriteIconByteArrayOutputStream = ByteArrayOutputStream()
3795 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
3796 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream)
3798 // Convert the favorite icon byte array stream to a byte array.
3799 val favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray()
3801 // Display the new bookmark below the current items in the (0 indexed) list.
3802 val newBookmarkDisplayOrder = bookmarksListView.count
3804 // Create the bookmark.
3805 bookmarksDatabaseHelper!!.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolderId, newBookmarkDisplayOrder, favoriteIconByteArray)
3807 // Update the bookmarks cursor with the current contents of this folder.
3808 bookmarksCursor = bookmarksDatabaseHelper!!.getBookmarksByDisplayOrder(currentBookmarksFolderId)
3810 // Update the list view.
3811 bookmarksCursorAdapter.changeCursor(bookmarksCursor)
3813 // Scroll to the new bookmark.
3814 bookmarksListView.setSelection(newBookmarkDisplayOrder)
3817 override fun createBookmarkFolder(dialogFragment: DialogFragment, favoriteIconBitmap: Bitmap) {
3819 val dialog = dialogFragment.dialog!!
3821 // Get handles for the views in the dialog fragment.
3822 val folderNameEditText = dialog.findViewById<EditText>(R.id.folder_name_edittext)
3823 val defaultIconRadioButton = dialog.findViewById<RadioButton>(R.id.default_icon_radiobutton)
3824 val defaultIconImageView = dialog.findViewById<ImageView>(R.id.default_icon_imageview)
3826 // Get new folder name string.
3827 val folderNameString = folderNameEditText.text.toString()
3829 // Set the folder icon bitmap according to the dialog.
3830 val folderIconBitmap: Bitmap = if (defaultIconRadioButton.isChecked) { // Use the default folder icon.
3831 // Get the default folder icon drawable.
3832 val folderIconDrawable = defaultIconImageView.drawable
3834 // Convert the folder icon drawable to a bitmap drawable.
3835 val folderIconBitmapDrawable = folderIconDrawable as BitmapDrawable
3837 // Convert the folder icon bitmap drawable to a bitmap.
3838 folderIconBitmapDrawable.bitmap
3839 } else { // Use the WebView favorite icon.
3840 // Copy the favorite icon bitmap to the folder icon bitmap.
3844 // Create a folder icon byte array output stream.
3845 val folderIconByteArrayOutputStream = ByteArrayOutputStream()
3847 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
3848 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream)
3850 // Convert the folder icon byte array stream to a byte array.
3851 val folderIconByteArray = folderIconByteArrayOutputStream.toByteArray()
3853 // Move all the bookmarks down one in the display order.
3854 for (i in 0 until bookmarksListView.count) {
3855 // Get the bookmark database id.
3856 val databaseId = bookmarksListView.getItemIdAtPosition(i).toInt()
3858 // Move the bookmark down one slot.
3859 bookmarksDatabaseHelper!!.updateDisplayOrder(databaseId, i + 1)
3862 // Create the folder, which will be placed at the top of the list view.
3863 bookmarksDatabaseHelper!!.createFolder(folderNameString, currentBookmarksFolderId, folderIconByteArray)
3865 // Update the bookmarks cursor with the current contents of this folder.
3866 bookmarksCursor = bookmarksDatabaseHelper!!.getBookmarksByDisplayOrder(currentBookmarksFolderId)
3868 // Update the list view.
3869 bookmarksCursorAdapter.changeCursor(bookmarksCursor)
3871 // Scroll to the new folder.
3872 bookmarksListView.setSelection(0)
3875 private fun downloadUrlWithExternalApp(url: String) {
3876 // Create a download intent. Not specifying the action type will display the maximum number of options.
3877 val downloadIntent = Intent()
3879 // Set the URI and the mime type.
3880 downloadIntent.setDataAndType(Uri.parse(url), "text/html")
3882 // Flag the intent to open in a new task.
3883 downloadIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
3885 // Show the chooser.
3886 startActivity(Intent.createChooser(downloadIntent, getString(R.string.download_with_external_app)))
3889 private fun exitFullScreenVideo() {
3890 // Re-enable the screen timeout.
3891 fullScreenVideoFrameLayout.keepScreenOn = false
3893 // Unset the full screen video flag.
3894 displayingFullScreenVideo = false
3896 // Remove all the views from the full screen video frame layout.
3897 fullScreenVideoFrameLayout.removeAllViews()
3899 // Hide the full screen video frame layout.
3900 fullScreenVideoFrameLayout.visibility = View.GONE
3902 // Enable the sliding drawers.
3903 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED)
3905 // Show the coordinator layout.
3906 coordinatorLayout.visibility = View.VISIBLE
3908 // Apply the appropriate full screen mode flags.
3909 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
3910 // Hide the app bar if specified.
3912 // Hide the tab linear layout.
3913 tabsLinearLayout.visibility = View.GONE
3915 // Hide the app bar.
3919 /* Hide the system bars.
3920 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3921 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
3922 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3923 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3926 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
3927 @Suppress("DEPRECATION")
3928 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
3929 } else { // Switch to normal viewing mode.
3930 // Remove the `SYSTEM_UI` flags from the root frame layout. The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
3931 @Suppress("DEPRECATION")
3932 rootFrameLayout.systemUiVisibility = 0
3936 // The view parameter cannot be removed because it is called from the layout onClick.
3937 fun findNextOnPage(@Suppress("UNUSED_PARAMETER")view: View?) {
3938 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
3939 currentWebView!!.findNext(true)
3942 // The view parameter cannot be removed because it is called from the layout onClick.
3943 fun findPreviousOnPage(@Suppress("UNUSED_PARAMETER")view: View?) {
3944 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
3945 currentWebView!!.findNext(false)
3948 override fun finishedPopulatingFilterLists(combinedFilterLists: ArrayList<ArrayList<List<Array<String>>>>) {
3949 // Store the filter lists.
3950 easyList = combinedFilterLists[0]
3951 easyPrivacy = combinedFilterLists[1]
3952 fanboysAnnoyanceList = combinedFilterLists[2]
3953 fanboysSocialList = combinedFilterLists[3]
3954 ultraList = combinedFilterLists[4]
3955 ultraPrivacy = combinedFilterLists[5]
3957 // Check to see if the activity has been restarted with a saved state.
3958 if ((savedStateArrayList == null) || (savedStateArrayList!!.size == 0)) { // The activity has not been restarted or it was restarted on start to change the theme.
3959 // Add the first tab.
3960 addNewTab("", false)
3961 } else { // The activity has been restarted.
3962 // Restore each tab.
3963 for (i in savedStateArrayList!!.indices) {
3965 tabLayout.addTab(tabLayout.newTab())
3968 val newTab = tabLayout.getTabAt(i)!!
3970 // Set a custom view on the new tab.
3971 newTab.setCustomView(R.layout.tab_custom_view)
3973 // Add the new page.
3974 webViewStateAdapter!!.restorePage(savedStateArrayList!![i], savedNestedScrollWebViewStateArrayList!![i])
3977 // Reset the saved state variables.
3978 savedStateArrayList = null
3979 savedNestedScrollWebViewStateArrayList = null
3981 Log.i("Tab", "Saved tab position: $savedTabPosition")
3983 // Restore the selected tab position.
3984 if (savedTabPosition == 0) { // The first tab is selected.
3985 // Set the first page as the current WebView.
3986 setCurrentWebView(0)
3987 } else { // The first tab is not selected.
3988 // Switch to the page before the saved tab position.
3989 webViewViewPager2.post { webViewViewPager2.currentItem = (savedTabPosition - 1) }
3991 // Switch to the saved tab position.
3992 // This has to be done twice because, for some reason, if the above step is skipped there is some race condition where nothing happens and the first page is displayed.
3993 webViewViewPager2.post { webViewViewPager2.currentItem = savedTabPosition }
3996 // Get the intent that started the app.
3999 // Reset the intent. This prevents a duplicate tab from being created on restart.
4002 // Get the information from the intent.
4003 val intentAction = intent.action
4004 val intentUriData = intent.data
4005 val intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT)
4007 // Determine if this is a web search.
4008 val isWebSearch = (intentAction != null) && (intentAction == Intent.ACTION_WEB_SEARCH)
4010 // 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.
4011 if ((intentUriData != null) || (intentStringExtra != null) || isWebSearch) {
4012 // Get the URL string.
4013 val urlString = if (isWebSearch) { // The intent is a web search.
4014 // Sanitize the search input.
4015 val encodedSearchString: String = try {
4016 URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8")
4017 } catch (exception: UnsupportedEncodingException) {
4021 // Add the base search URL.
4022 searchURL + encodedSearchString
4023 } else { // The intent contains a URL formatted as a URI or a URL in the string extra.
4024 // Get the URL string.
4025 intentUriData?.toString() ?: intentStringExtra!!
4028 // Add a new tab if specified in the preferences.
4029 if (sharedPreferences.getBoolean(getString(R.string.open_intents_in_new_tab_key), true)) { // Load the URL in a new tab.
4030 // Set the loading new intent flag.
4031 loadingNewIntent = true
4034 addNewTab(urlString, true)
4035 } else { // Load the URL in the current tab.
4037 loadUrl(currentWebView!!, urlString)
4043 // Remove the warning that `OnTouchListener()` needs to override `performClick()`, as the only purpose of setting the `OnTouchListener()` is to make it do nothing.
4044 @SuppressLint("ClickableViewAccessibility")
4045 private fun initializeApp() {
4046 // Get a handle for the input method.
4047 val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
4049 // Initialize the color spans for highlighting the URLs.
4050 initialGrayColorSpan = ForegroundColorSpan(getColor(R.color.gray_500))
4051 finalGrayColorSpan = ForegroundColorSpan(getColor(R.color.gray_500))
4052 redColorSpan = ForegroundColorSpan(getColor(R.color.red_text))
4054 // Remove the formatting from the URL edit text when the user is editing the text.
4055 urlEditText.onFocusChangeListener = View.OnFocusChangeListener { _: View?, hasFocus: Boolean ->
4056 if (hasFocus) { // The user is editing the URL text box.
4057 // Remove the syntax highlighting.
4058 urlEditText.text.removeSpan(redColorSpan)
4059 urlEditText.text.removeSpan(initialGrayColorSpan)
4060 urlEditText.text.removeSpan(finalGrayColorSpan)
4061 } else { // The user has stopped editing the URL text box.
4062 // Move to the beginning of the string.
4063 urlEditText.setSelection(0)
4065 // Reapply the syntax highlighting.
4066 UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
4070 // Set the go button on the keyboard to load the URL in url text box.
4071 urlEditText.setOnKeyListener { _: View?, keyCode: Int, keyEvent: KeyEvent ->
4072 // If the event is a key-down event on the `enter` button, load the URL.
4073 if ((keyEvent.action == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The enter key was pressed.
4075 loadUrlFromTextBox()
4077 // Consume the event.
4078 return@setOnKeyListener true
4079 } else { // Some other key was pressed.
4080 // Do not consume the event.
4081 return@setOnKeyListener false
4085 // Create an Orbot status broadcast receiver.
4086 orbotStatusBroadcastReceiver = object : BroadcastReceiver() {
4087 override fun onReceive(context: Context, intent: Intent) {
4088 // Get the content of the status message.
4089 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS")!!
4091 // If Privacy Browser is waiting on the proxy, load the website now that Orbot is connected.
4092 if ((orbotStatus == ProxyHelper.ORBOT_STATUS_ON) && waitingForProxy) {
4093 // Reset the waiting for proxy status.
4094 waitingForProxy = false
4096 // Get a list of the current fragments.
4097 val fragmentList = supportFragmentManager.fragments
4099 // Check each fragment to see if it is a waiting for proxy dialog. Sometimes more than one is displayed.
4100 for (i in fragmentList.indices) {
4101 // Get the fragment tag.
4102 val fragmentTag = fragmentList[i].tag
4104 // Check to see if it is the waiting for proxy dialog.
4105 if (fragmentTag != null && fragmentTag == getString(R.string.waiting_for_proxy_dialog)) {
4106 // Dismiss the waiting for proxy dialog.
4107 (fragmentList[i] as DialogFragment).dismiss()
4111 // Reload existing URLs and load any URLs that are waiting for the proxy.
4112 for (i in 0 until webViewStateAdapter!!.itemCount) {
4113 // Get the WebView tab fragment.
4114 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
4116 // Get the fragment view.
4117 val fragmentView = webViewTabFragment.view
4119 // Only process the WebViews if they exist.
4120 if (fragmentView != null) {
4121 // Get the nested scroll WebView from the tab fragment.
4122 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
4124 // Get the waiting for proxy URL string.
4125 val waitingForProxyUrlString = nestedScrollWebView.waitingForProxyUrlString
4127 // Load the pending URL if it exists.
4128 if (waitingForProxyUrlString.isNotEmpty()) { // A URL is waiting to be loaded.
4130 loadUrl(nestedScrollWebView, waitingForProxyUrlString)
4132 // Reset the waiting for proxy URL string.
4133 nestedScrollWebView.waitingForProxyUrlString = ""
4134 } else { // No URL is waiting to be loaded.
4135 // Reload the existing URL.
4136 nestedScrollWebView.reload()
4144 // Register the Orbot status broadcast receiver.
4145 registerReceiver(orbotStatusBroadcastReceiver, IntentFilter("org.torproject.android.intent.action.STATUS"))
4147 // Get handles for views that need to be modified.
4148 val bookmarksHeaderLinearLayout = findViewById<LinearLayout>(R.id.bookmarks_header_linearlayout)
4149 val launchBookmarksActivityFab = findViewById<FloatingActionButton>(R.id.launch_bookmarks_activity_fab)
4150 val createBookmarkFolderFab = findViewById<FloatingActionButton>(R.id.create_bookmark_folder_fab)
4151 val createBookmarkFab = findViewById<FloatingActionButton>(R.id.create_bookmark_fab)
4153 // Update the WebView pager every time a tab is modified.
4154 webViewViewPager2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
4155 override fun onPageSelected(position: Int) {
4156 // Close the find on page bar if it is open.
4157 closeFindOnPage(null)
4159 // Set the current WebView.
4160 setCurrentWebView(position)
4162 // 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.
4163 if (tabLayout.selectedTabPosition != position) {
4164 // Wait until the new tab has been created.
4166 // Get a handle for the tab.
4167 val tab = tabLayout.getTabAt(position)!!
4176 // Handle tab selections.
4177 tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
4178 override fun onTabSelected(tab: TabLayout.Tab) {
4179 // Select the same page in the view pager.
4180 webViewViewPager2.currentItem = tab.position
4183 override fun onTabUnselected(tab: TabLayout.Tab) {}
4185 override fun onTabReselected(tab: TabLayout.Tab) {
4186 // Instantiate the View SSL Certificate dialog.
4187 val viewSslCertificateDialogFragment: DialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView!!.webViewFragmentId, currentWebView!!.getFavoriteIcon())
4189 // Display the View SSL Certificate dialog.
4190 viewSslCertificateDialogFragment.show(supportFragmentManager, getString(R.string.view_ssl_certificate))
4194 // Set a touch listener on the bookmarks header linear layout so that touches don't pass through to the button underneath.
4195 bookmarksHeaderLinearLayout.setOnTouchListener { _: View?, _: MotionEvent? -> true }
4197 // Set the launch bookmarks activity floating action button to launch the bookmarks activity.
4198 launchBookmarksActivityFab.setOnClickListener {
4199 // Get a copy of the favorite icon bitmap.
4200 val currentFavoriteIconBitmap = currentWebView!!.getFavoriteIcon()
4202 // Create a favorite icon byte array output stream.
4203 val currentFavoriteIconByteArrayOutputStream = ByteArrayOutputStream()
4205 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
4206 currentFavoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, currentFavoriteIconByteArrayOutputStream)
4208 // Convert the favorite icon byte array stream to a byte array.
4209 val currentFavoriteIconByteArray = currentFavoriteIconByteArrayOutputStream.toByteArray()
4211 // Create an intent to launch the bookmarks activity.
4212 val bookmarksIntent = Intent(applicationContext, BookmarksActivity::class.java)
4214 // Add the extra information to the intent.
4215 bookmarksIntent.putExtra(CURRENT_FOLDER_ID, currentBookmarksFolderId)
4216 bookmarksIntent.putExtra(CURRENT_TITLE, currentWebView!!.title)
4217 bookmarksIntent.putExtra(CURRENT_URL, currentWebView!!.url)
4218 bookmarksIntent.putExtra(CURRENT_FAVORITE_ICON_BYTE_ARRAY, currentFavoriteIconByteArray)
4221 startActivity(bookmarksIntent)
4224 // Set the create new bookmark folder floating action button to display an alert dialog.
4225 createBookmarkFolderFab.setOnClickListener {
4226 // Create a create bookmark folder dialog.
4227 val createBookmarkFolderDialog: DialogFragment = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView!!.getFavoriteIcon())
4229 // Show the create bookmark folder dialog.
4230 createBookmarkFolderDialog.show(supportFragmentManager, getString(R.string.create_folder))
4233 // Set the create new bookmark floating action button to display an alert dialog.
4234 createBookmarkFab.setOnClickListener {
4235 // Instantiate the create bookmark dialog.
4236 val createBookmarkDialog: DialogFragment = CreateBookmarkDialog.createBookmark(currentWebView!!.url!!, currentWebView!!.title!!, currentWebView!!.getFavoriteIcon())
4238 // Display the create bookmark dialog.
4239 createBookmarkDialog.show(supportFragmentManager, getString(R.string.create_bookmark))
4242 // Search for the string on the page whenever a character changes in the find on page edit text.
4243 findOnPageEditText.addTextChangedListener(object : TextWatcher {
4244 override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
4246 override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
4248 override fun afterTextChanged(s: Editable) {
4249 // 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.
4250 currentWebView?.findAllAsync(findOnPageEditText.text.toString())
4254 // Set the `check mark` button for the find on page edit text keyboard to close the soft keyboard.
4255 findOnPageEditText.setOnKeyListener { _: View?, keyCode: Int, keyEvent: KeyEvent ->
4256 if ((keyEvent.action == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
4257 // Hide the soft keyboard.
4258 inputMethodManager.hideSoftInputFromWindow(currentWebView!!.windowToken, 0)
4260 // Consume the event.
4261 return@setOnKeyListener true
4262 } else { // A different key was pressed.
4263 // Do not consume the event.
4264 return@setOnKeyListener false
4268 // Implement swipe to refresh.
4269 swipeRefreshLayout.setOnRefreshListener {
4270 // Reload the website.
4271 currentWebView!!.reload()
4274 // Store the default progress view offsets.
4275 defaultProgressViewStartOffset = swipeRefreshLayout.progressViewStartOffset
4276 defaultProgressViewEndOffset = swipeRefreshLayout.progressViewEndOffset
4278 // Set the refresh color scheme according to the theme.
4279 swipeRefreshLayout.setColorSchemeResources(R.color.blue_text)
4281 // Initialize a color background typed value.
4282 val colorBackgroundTypedValue = TypedValue()
4284 // Get the color background from the theme.
4285 theme.resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true)
4287 // Get the color background int from the typed value.
4288 val colorBackgroundInt = colorBackgroundTypedValue.data
4290 // Set the swipe refresh background color.
4291 swipeRefreshLayout.setProgressBackgroundColorSchemeColor(colorBackgroundInt)
4293 // Set the drawer titles, which identify the drawer layouts in accessibility mode.
4294 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer))
4295 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks))
4297 // Load the bookmarks folder.
4298 loadBookmarksFolder()
4300 // Handle clicks on bookmarks.
4301 bookmarksListView.onItemClickListener = AdapterView.OnItemClickListener { _: AdapterView<*>?, _: View?, _: Int, id: Long ->
4302 // Convert the id from long to int to match the format of the bookmarks database.
4303 val databaseId = id.toInt()
4305 // Get the bookmark cursor for this ID.
4306 val bookmarkCursor = bookmarksDatabaseHelper!!.getBookmark(databaseId)
4308 // Move the bookmark cursor to the first row.
4309 bookmarkCursor.moveToFirst()
4311 // Act upon the bookmark according to the type.
4312 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndexOrThrow(IS_FOLDER)) == 1) { // The selected bookmark is a folder.
4313 // Store the folder ID.
4314 currentBookmarksFolderId = bookmarkCursor.getLong(bookmarkCursor.getColumnIndexOrThrow(FOLDER_ID))
4316 // Load the new folder.
4317 loadBookmarksFolder()
4318 } else { // The selected bookmark is not a folder.
4319 // Load the bookmark URL.
4320 loadUrl(currentWebView!!, bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BOOKMARK_URL)))
4322 // Close the bookmarks drawer if it is not pinned.
4323 if (!bookmarksDrawerPinned)
4324 drawerLayout.closeDrawer(GravityCompat.END)
4327 // Close the cursor.
4328 bookmarkCursor.close()
4331 // Handle long-presses on bookmarks.
4332 bookmarksListView.onItemLongClickListener = AdapterView.OnItemLongClickListener { _: AdapterView<*>?, _: View?, _: Int, id: Long ->
4333 // Convert the database ID from `long` to `int`.
4334 val databaseId = id.toInt()
4336 // Run the commands associated with the type.
4337 if (bookmarksDatabaseHelper!!.isFolder(databaseId)) { // The bookmark is a folder.
4338 // Get the folder ID.
4339 val folderId = bookmarksDatabaseHelper!!.getFolderId(databaseId)
4341 // Get a cursor of all the bookmarks in the folder.
4342 val bookmarksCursor = bookmarksDatabaseHelper!!.getFolderBookmarks(folderId)
4344 // Move to the first entry in the cursor.
4345 bookmarksCursor.moveToFirst()
4347 // Open each bookmark
4348 for (i in 0 until bookmarksCursor.count) {
4349 // Load the bookmark in a new tab, moving to the tab for the first bookmark if the drawer is not pinned.
4350 addNewTab(bookmarksCursor.getString(bookmarksCursor.getColumnIndexOrThrow(BOOKMARK_URL)), !bookmarksDrawerPinned && (i == 0))
4352 // Move to the next bookmark.
4353 bookmarksCursor.moveToNext()
4356 // Close the cursor.
4357 bookmarksCursor.close()
4358 } else { // The bookmark is not a folder.
4359 // Get the bookmark cursor for this ID.
4360 val bookmarkCursor = bookmarksDatabaseHelper!!.getBookmark(databaseId)
4362 // Move the bookmark cursor to the first row.
4363 bookmarkCursor.moveToFirst()
4365 // Load the bookmark in a new tab and move to the tab if the drawer is not pinned.
4366 addNewTab(bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BOOKMARK_URL)), !bookmarksDrawerPinned)
4368 // Close the cursor.
4369 bookmarkCursor.close()
4372 // Close the bookmarks drawer if it is not pinned.
4373 if (!bookmarksDrawerPinned)
4374 drawerLayout.closeDrawer(GravityCompat.END)
4376 // Consume the event.
4380 // The drawer listener is used to update the navigation menu.
4381 drawerLayout.addDrawerListener(object : DrawerLayout.DrawerListener {
4382 override fun onDrawerSlide(drawerView: View, slideOffset: Float) {}
4384 override fun onDrawerOpened(drawerView: View) {}
4386 override fun onDrawerClosed(drawerView: View) {
4387 // Reset the drawer icon when the drawer is closed. Otherwise, it remains an arrow if the drawer is open when the app is restarted.
4388 actionBarDrawerToggle!!.syncState()
4391 override fun onDrawerStateChanged(newState: Int) {
4392 if (newState == DrawerLayout.STATE_SETTLING || newState == DrawerLayout.STATE_DRAGGING) { // A drawer is opening or closing.
4393 // Update the navigation menu items if the WebView is not null.
4394 if (currentWebView != null) {
4395 navigationBackMenuItem.isEnabled = currentWebView!!.canGoBack()
4396 navigationForwardMenuItem.isEnabled = currentWebView!!.canGoForward()
4397 navigationHistoryMenuItem.isEnabled = currentWebView!!.canGoBack() || currentWebView!!.canGoForward()
4398 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + currentWebView!!.getRequestsCount(BLOCKED_REQUESTS)
4400 // Hide the keyboard (if displayed).
4401 inputMethodManager.hideSoftInputFromWindow(currentWebView!!.windowToken, 0)
4404 // 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.
4405 urlEditText.clearFocus()
4407 // 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.
4408 // Clearing the focus from the WebView removes any text selection markers and context menus, which otherwise draw above the open drawers.
4409 currentWebView?.clearFocus()
4414 // Inflate a bare WebView to get the default user agent. It is not used to render content on the screen.
4415 @SuppressLint("InflateParams") val webViewLayout = layoutInflater.inflate(R.layout.bare_webview, null, false)
4417 // Get a handle for the WebView.
4418 val bareWebView = webViewLayout.findViewById<WebView>(R.id.bare_webview)
4420 // Store the default user agent.
4421 webViewDefaultUserAgent = bareWebView.settings.userAgentString
4423 // Destroy the bare WebView.
4424 bareWebView.destroy()
4426 // Update the domains settings set.
4427 updateDomainsSettingsSet()
4429 // Instantiate the check filter list helper.
4430 checkFilterListHelper = CheckFilterListHelper()
4433 @SuppressLint("ClickableViewAccessibility")
4434 override fun initializeWebView(nestedScrollWebView: NestedScrollWebView, pageNumber: Int, progressBar: ProgressBar, urlString: String, restoringState: Boolean) {
4435 // Get the WebView theme.
4436 val webViewTheme = sharedPreferences.getString(getString(R.string.webview_theme_key), getString(R.string.webview_theme_default_value))
4438 // Get the WebView theme entry values string array.
4439 val webViewThemeEntryValuesStringArray = resources.getStringArray(R.array.webview_theme_entry_values)
4441 // Set the WebView theme if algorithmic darkening is supported.
4442 if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {
4443 // Set the WebView them. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
4444 if (webViewTheme == webViewThemeEntryValuesStringArray[1]) { // The light theme is selected.
4445 // Turn off algorithmic darkening.
4446 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
4448 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
4449 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
4450 nestedScrollWebView.visibility = View.VISIBLE
4451 } else if (webViewTheme == webViewThemeEntryValuesStringArray[2]) { // The dark theme is selected.
4452 // Turn on algorithmic darkening.
4453 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
4454 } else { // The system default theme is selected.
4455 // Get the current theme status.
4456 val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
4458 // Set the algorithmic darkening according to the current system theme status.
4459 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) { // The system is in day mode.
4460 // Turn off algorithmic darkening.
4461 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
4463 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
4464 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
4465 nestedScrollWebView.visibility = View.VISIBLE
4466 } else { // The system is in night mode.
4467 // Turn on algorithmic darkening.
4468 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
4473 // Get a handle for the input method manager.
4474 val inputMethodManager = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
4476 // Set the app bar scrolling.
4477 nestedScrollWebView.isNestedScrollingEnabled = scrollAppBar
4479 // Allow pinch to zoom.
4480 nestedScrollWebView.settings.builtInZoomControls = true
4482 // Hide zoom controls.
4483 nestedScrollWebView.settings.displayZoomControls = false
4485 // Don't allow mixed content (HTTP and HTTPS) on the same website.
4486 nestedScrollWebView.settings.mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW
4488 // Set the WebView to load in overview mode (zoomed out to the maximum width).
4489 nestedScrollWebView.settings.loadWithOverviewMode = true
4491 // Explicitly disable geolocation.
4492 nestedScrollWebView.settings.setGeolocationEnabled(false)
4494 // Allow loading of file:// URLs. This is necessary for opening MHT web archives, which are copied into a temporary cache location.
4495 nestedScrollWebView.settings.allowFileAccess = true
4497 // Create a double-tap gesture detector to toggle full-screen mode.
4498 val doubleTapGestureDetector = GestureDetector(this, object : GestureDetector.SimpleOnGestureListener() {
4499 // Override `onDoubleTap()`. All other events are handled using the default settings.
4500 override fun onDoubleTap(motionEvent: MotionEvent): Boolean {
4501 return if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
4502 // Toggle the full screen browsing mode tracker.
4503 inFullScreenBrowsingMode = !inFullScreenBrowsingMode
4505 // Toggle the full screen browsing mode.
4506 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
4507 // Hide the app bar if specified.
4508 if (hideAppBar) { // App bar hiding is enabled.
4509 // Close the find on page bar if it is visible.
4510 closeFindOnPage(null)
4512 // Hide the tab linear layout.
4513 tabsLinearLayout.visibility = View.GONE
4515 // Hide the app bar.
4518 // Set layout and scrolling parameters according to the position of the app bar.
4519 if (bottomAppBar) { // The app bar is at the bottom.
4520 // Reset the WebView padding to fill the available space.
4521 swipeRefreshLayout.setPadding(0, 0, 0, 0)
4522 } else { // The app bar is at the top.
4523 // Check to see if the app bar is normally scrolled.
4524 if (scrollAppBar) { // The app bar is scrolled when it is displayed.
4525 // Get the swipe refresh layout parameters.
4526 val swipeRefreshLayoutParams = swipeRefreshLayout.layoutParams as CoordinatorLayout.LayoutParams
4528 // Remove the off-screen scrolling layout.
4529 swipeRefreshLayoutParams.behavior = null
4530 } else { // The app bar is not scrolled when it is displayed.
4531 // Remove the padding from the top of the swipe refresh layout.
4532 swipeRefreshLayout.setPadding(0, 0, 0, 0)
4534 // The swipe refresh circle must be moved above the now removed status bar location.
4535 swipeRefreshLayout.setProgressViewOffset(false, -200, defaultProgressViewEndOffset)
4538 } else { // App bar hiding is not enabled.
4539 // Adjust the UI for the bottom app bar.
4541 // Adjust the UI according to the scrolling of the app bar.
4543 // Reset the WebView padding to fill the available space.
4544 swipeRefreshLayout.setPadding(0, 0, 0, 0)
4546 // Move the WebView above the app bar layout.
4547 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
4552 /* Hide the system bars.
4553 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4554 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4555 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4556 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4559 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4560 @Suppress("DEPRECATION")
4561 rootFrameLayout.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
4562 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
4563 } else { // Switch to normal viewing mode.
4564 // Show the app bar if it was hidden.
4566 // Show the tab linear layout.
4567 tabsLinearLayout.visibility = View.VISIBLE
4569 // Show the app bar.
4573 // Set layout and scrolling parameters according to the position of the app bar.
4574 if (bottomAppBar) { // The app bar is at the bottom.
4577 // Reset the WebView padding to fill the available space.
4578 swipeRefreshLayout.setPadding(0, 0, 0, 0)
4580 // Move the WebView above the app bar layout.
4581 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
4583 } else { // The app bar is at the top.
4584 // Check to see if the app bar is normally scrolled.
4585 if (scrollAppBar) { // The app bar is scrolled when it is displayed.
4586 // Get the swipe refresh layout parameters.
4587 val swipeRefreshLayoutParams = swipeRefreshLayout.layoutParams as CoordinatorLayout.LayoutParams
4589 // Add the off-screen scrolling layout.
4590 swipeRefreshLayoutParams.behavior = AppBarLayout.ScrollingViewBehavior()
4591 } else { // The app bar is not scrolled when it is displayed.
4592 // The swipe refresh layout must be manually moved below the app bar layout.
4593 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0)
4595 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
4596 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight)
4600 // Remove the `SYSTEM_UI` flags from the root frame layout. The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4601 @Suppress("DEPRECATION")
4602 rootFrameLayout.systemUiVisibility = 0
4605 // Consume the double-tap.
4607 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
4613 override fun onFling(motionEvent1: MotionEvent, motionEvent2: MotionEvent, velocityX: Float, velocityY: Float): Boolean {
4614 // Scroll the bottom app bar if enabled.
4615 if (bottomAppBar && scrollAppBar && !objectAnimator.isRunning) {
4616 // Calculate the Y change.
4617 val motionY = motionEvent2.y - motionEvent1.y
4619 // Scroll the app bar if the change is greater than 50 pixels.
4621 // Animate the bottom app bar onto the screen.
4622 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0f)
4623 } else if (motionY < -50) {
4624 // Animate the bottom app bar off the screen.
4625 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", appBarLayout.height.toFloat())
4629 objectAnimator.start()
4632 // Do not consume the event.
4637 // Pass all touch events on the WebView through the double-tap gesture detector.
4638 nestedScrollWebView.setOnTouchListener { view: View, motionEvent: MotionEvent? ->
4639 // Call `performClick()` on the view, which is required for accessibility.
4642 // Check for double-taps.
4643 doubleTapGestureDetector.onTouchEvent(motionEvent!!)
4646 // Register the WebView for a context menu. This is used to see link targets and download images.
4647 registerForContextMenu(nestedScrollWebView)
4649 // Allow the downloading of files.
4650 nestedScrollWebView.setDownloadListener { downloadUrlString: String?, userAgent: String?, contentDisposition: String?, mimetype: String?, contentLength: Long ->
4651 // Check the download preference.
4652 if (downloadWithExternalApp) { // Download with an external app.
4653 downloadUrlWithExternalApp(downloadUrlString!!)
4654 } else { // Handle the download inside of Privacy Browser.
4655 // Define a formatted file size string.
4657 // Process the content length if it contains data.
4658 val formattedFileSizeString = if (contentLength > 0) { // The content length is greater than 0.
4659 // Format the content length as a string.
4660 NumberFormat.getInstance().format(contentLength) + " " + getString(R.string.bytes)
4661 } else { // The content length is not greater than 0.
4662 // Set the formatted file size string to be `unknown size`.
4663 getString(R.string.unknown_size)
4666 // Get the file name from the content disposition.
4667 val fileNameString = UrlHelper.getFileName(this, contentDisposition, mimetype, downloadUrlString!!)
4669 // Instantiate the save dialog.
4670 val saveDialogFragment = SaveDialog.saveUrl(downloadUrlString, fileNameString, formattedFileSizeString, userAgent!!, nestedScrollWebView.acceptCookies)
4672 // 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.
4674 // Show the save dialog.
4675 saveDialogFragment.show(supportFragmentManager, getString(R.string.save_dialog))
4676 } catch (exception: Exception) { // The dialog could not be shown.
4677 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
4678 pendingDialogsArrayList.add(PendingDialogDataClass(saveDialogFragment, getString(R.string.save_dialog)))
4683 // Update the find on page count.
4684 nestedScrollWebView.setFindListener { activeMatchOrdinal, numberOfMatches, isDoneCounting ->
4685 if (isDoneCounting && (numberOfMatches == 0)) { // There are no matches.
4686 // Set the find on page count text view to be `0/0`.
4687 findOnPageCountTextView.setText(R.string.zero_of_zero)
4688 } else if (isDoneCounting) { // There are matches.
4689 // The active match ordinal is zero-based.
4690 val activeMatch = activeMatchOrdinal + 1
4692 // Build the match string.
4693 val matchString = "$activeMatch/$numberOfMatches"
4695 // Update the find on page count text view.
4696 findOnPageCountTextView.text = matchString
4700 // Process scroll changes.
4701 nestedScrollWebView.setOnScrollChangeListener { _: View?, _: Int, _: Int, _: Int, _: Int ->
4702 // Set the swipe to refresh status.
4703 if (nestedScrollWebView.swipeToRefresh) // Only enable swipe to refresh if the WebView is scrolled to the top.
4704 swipeRefreshLayout.isEnabled = nestedScrollWebView.scrollY == 0
4705 else // Disable swipe to refresh.
4706 swipeRefreshLayout.isEnabled = false
4708 // Reinforce the system UI visibility flags if in full screen browsing mode.
4709 // This hides the status and navigation bars, which are displayed if other elements are shown, like dialog boxes, the options menu, or the keyboard.
4710 if (inFullScreenBrowsingMode) {
4711 /* Hide the system bars.
4712 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4713 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4714 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4715 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4718 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4719 @Suppress("DEPRECATION")
4720 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
4724 // Set the web chrome client.
4725 nestedScrollWebView.webChromeClient = object : WebChromeClient() {
4726 // Update the progress bar when a page is loading.
4727 override fun onProgressChanged(view: WebView, progress: Int) {
4728 // Update the progress bar.
4729 progressBar.progress = progress
4731 // Set the visibility of the progress bar.
4732 if (progress < 100) {
4733 // Show the progress bar.
4734 progressBar.visibility = View.VISIBLE
4736 // Hide the progress bar.
4737 progressBar.visibility = View.GONE
4739 //Stop the swipe to refresh indicator if it is running
4740 swipeRefreshLayout.isRefreshing = false
4742 // 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.
4743 nestedScrollWebView.visibility = View.VISIBLE
4747 // Set the favorite icon when it changes.
4748 override fun onReceivedIcon(view: WebView, icon: Bitmap) {
4749 // 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.
4750 // This prevents low resolution icons from replacing high resolution one.
4751 // The check for the visibility of the progress bar can possibly be removed once https://redmine.stoutner.com/issues/747 is fixed.
4752 if ((progressBar.visibility == View.GONE) && (icon.height > nestedScrollWebView.getFavoriteIconHeight())) {
4753 // Store the new favorite icon.
4754 nestedScrollWebView.setFavoriteIcon(icon)
4756 // Get the current page position.
4757 val currentPosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
4759 // Get the current tab.
4760 val tab = tabLayout.getTabAt(currentPosition)
4762 // Check to see if the tab has been populated.
4764 // Get the custom view from the tab.
4765 val tabView = tab.customView
4767 // Check to see if the custom tab view has been populated.
4768 if (tabView != null) {
4769 // Get the favorite icon image view from the tab.
4770 val tabFavoriteIconImageView = tabView.findViewById<ImageView>(R.id.favorite_icon_imageview)
4772 // Display the favorite icon in the tab.
4773 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true))
4779 // Save a copy of the title when it changes.
4780 override fun onReceivedTitle(view: WebView, title: String) {
4781 // Get the current page position.
4782 val currentPosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
4784 // Get the current tab.
4785 val tab = tabLayout.getTabAt(currentPosition)
4787 // Only populate the title text view if the tab has been fully created.
4789 // Get the custom view from the tab.
4790 val tabView = tab.customView
4792 // Only populate the title text view if the tab view has been fully populated.
4793 if (tabView != null) {
4794 // Get the title text view from the tab.
4795 val tabTitleTextView = tabView.findViewById<TextView>(R.id.title_textview)
4797 // Set the title according to the URL.
4798 if (title == "about:blank") {
4799 // Set the title to indicate a new tab.
4800 tabTitleTextView.setText(R.string.new_tab)
4802 // Set the title as the tab text.
4803 tabTitleTextView.text = title
4809 // Enter full screen video.
4810 override fun onShowCustomView(video: View, callback: CustomViewCallback) {
4811 // Set the full screen video flag.
4812 displayingFullScreenVideo = true
4814 // Hide the keyboard.
4815 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.windowToken, 0)
4817 // Hide the coordinator layout.
4818 coordinatorLayout.visibility = View.GONE
4820 /* Hide the system bars.
4821 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4822 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4823 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4824 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4827 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4828 @Suppress("DEPRECATION")
4829 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
4831 // Disable the sliding drawers.
4832 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
4834 // Add the video view to the full screen video frame layout.
4835 fullScreenVideoFrameLayout.addView(video)
4837 // Show the full screen video frame layout.
4838 fullScreenVideoFrameLayout.visibility = View.VISIBLE
4840 // Disable the screen timeout while the video is playing. YouTube does this automatically, but not all other videos do.
4841 fullScreenVideoFrameLayout.keepScreenOn = true
4844 // Exit full screen video.
4845 override fun onHideCustomView() {
4846 // Exit the full screen video.
4847 exitFullScreenVideo()
4851 override fun onShowFileChooser(webView: WebView, filePathCallback: ValueCallback<Array<Uri>>, fileChooserParams: FileChooserParams): Boolean {
4852 // Store the file path callback.
4853 fileChooserCallback = filePathCallback
4855 // Create an intent to open a chooser based on the file chooser parameters.
4856 val fileChooserIntent = fileChooserParams.createIntent()
4858 // Check to see if the file chooser intent resolves to an installed package.
4859 if (fileChooserIntent.resolveActivity(packageManager) != null) { // The file chooser intent is fine.
4860 // Launch the file chooser intent.
4861 browseFileUploadActivityResultLauncher.launch(fileChooserIntent)
4862 } else { // The file chooser intent will cause a crash.
4863 // Create a generic intent to open a chooser.
4864 val genericFileChooserIntent = Intent(Intent.ACTION_GET_CONTENT)
4866 // Request an openable file.
4867 genericFileChooserIntent.addCategory(Intent.CATEGORY_OPENABLE)
4869 // Set the file type to everything.
4870 genericFileChooserIntent.type = "*/*"
4872 // Launch the generic file chooser intent.
4873 browseFileUploadActivityResultLauncher.launch(genericFileChooserIntent)
4876 // Handle the event.
4880 nestedScrollWebView.webViewClient = object : WebViewClient() {
4881 // `shouldOverrideUrlLoading` makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
4882 override fun shouldOverrideUrlLoading(view: WebView, webResourceRequest: WebResourceRequest): Boolean {
4883 // Get the URL from the web resource request.
4884 var requestUrlString = webResourceRequest.url.toString()
4886 // Sanitize the url.
4887 requestUrlString = sanitizeUrl(requestUrlString)
4889 // Handle the URL according to the type.
4890 return if (requestUrlString.startsWith("http")) { // Load the URL in Privacy Browser.
4891 // Load the URL. By using `loadUrl()`, instead of `loadUrlFromBase()`, the Referer header will never be sent.
4892 loadUrl(nestedScrollWebView, requestUrlString)
4894 // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
4895 // Custom headers cannot be added if false is returned and the WebView handles the loading of the URL.
4897 } else if (requestUrlString.startsWith("mailto:")) { // Load the email address in an external email program.
4898 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
4899 val emailIntent = Intent(Intent.ACTION_SENDTO)
4901 // Parse the url and set it as the data for the intent.
4902 emailIntent.data = Uri.parse(requestUrlString)
4904 // Open the email program in a new task instead of as part of Privacy Browser.
4905 emailIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
4909 startActivity(emailIntent)
4910 } catch (exception: ActivityNotFoundException) {
4911 // Display a snackbar.
4912 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
4915 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
4917 } else if (requestUrlString.startsWith("tel:")) { // Load the phone number in the dialer.
4918 // Create a dial intent.
4919 val dialIntent = Intent(Intent.ACTION_DIAL)
4921 // Add the phone number to the intent.
4922 dialIntent.data = Uri.parse(requestUrlString)
4924 // Open the dialer in a new task instead of as part of Privacy Browser.
4925 dialIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
4929 startActivity(dialIntent)
4930 } catch (exception: ActivityNotFoundException) {
4931 // Display a snackbar.
4932 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
4935 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
4937 } else { // Load a system chooser to select an app that can handle the URL.
4938 // Create a generic intent to open an app.
4939 val genericIntent = Intent(Intent.ACTION_VIEW)
4941 // Add the URL to the intent.
4942 genericIntent.data = Uri.parse(requestUrlString)
4944 // List all apps that can handle the URL instead of just opening the first one.
4945 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE)
4947 // Open the app in a new task instead of as part of Privacy Browser.
4948 genericIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
4952 startActivity(genericIntent)
4953 } catch (exception: ActivityNotFoundException) {
4954 // Display a snackbar.
4955 Snackbar.make(nestedScrollWebView, getString(R.string.unrecognized_url, requestUrlString), Snackbar.LENGTH_SHORT).show()
4958 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
4963 // Check requests against the block lists.
4964 override fun shouldInterceptRequest(view: WebView, webResourceRequest: WebResourceRequest): WebResourceResponse? {
4966 val requestUrlString = webResourceRequest.url.toString()
4968 // Check to see if the resource request is for the main URL.
4969 if (requestUrlString == nestedScrollWebView.currentUrl) {
4970 // `return null` loads the resource request, which should never be blocked if it is the main URL.
4974 // 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.
4975 while (ultraPrivacy == null) {
4977 // Check to see if the filter lists have been populated after 100 ms.
4979 } catch (exception: InterruptedException) {
4984 // Create an empty web resource response to be used if the resource request is blocked.
4985 val emptyWebResourceResponse = WebResourceResponse("text/plain", "utf8", ByteArrayInputStream("".toByteArray()))
4987 // Initialize the variables.
4988 var allowListResultStringArray: Array<String>? = null
4989 var isThirdPartyRequest = false
4991 // Get the current URL. `.getUrl()` throws an error because operations on the WebView cannot be made from this thread.
4992 var currentBaseDomain = nestedScrollWebView.currentDomainName
4994 // Store a copy of the current domain for use in later requests.
4995 val currentDomain = currentBaseDomain
4997 // Get the request host name.
4998 var requestBaseDomain = webResourceRequest.url.host
5000 // Only check for third-party requests if the current base domain is not empty and the request domain is not null.
5001 if (currentBaseDomain.isNotEmpty() && (requestBaseDomain != null)) {
5002 // Determine the current base domain.
5003 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5004 // Remove the first subdomain.
5005 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1)
5008 // Determine the request base domain.
5009 while (requestBaseDomain!!.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5010 // Remove the first subdomain.
5011 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1)
5014 // Update the third party request tracker.
5015 isThirdPartyRequest = currentBaseDomain != requestBaseDomain
5018 // Get the current WebView page position.
5019 val webViewPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
5021 // Determine if the WebView is currently displayed.
5022 val webViewDisplayed = (webViewPagePosition == tabLayout.selectedTabPosition)
5024 // Block third-party requests if enabled.
5025 if (isThirdPartyRequest && nestedScrollWebView.blockAllThirdPartyRequests) {
5026 // Add the result to the resource requests.
5027 nestedScrollWebView.addResourceRequest(arrayOf(REQUEST_THIRD_PARTY, requestUrlString))
5029 // Increment the blocked requests counters.
5030 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5031 nestedScrollWebView.incrementRequestsCount(THIRD_PARTY_REQUESTS)
5033 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5034 if (webViewDisplayed) {
5035 // Updating the UI must be run from the UI thread.
5037 // Update the menu item titles.
5038 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5040 // Update the options menu if it has been populated.
5041 if (optionsMenu != null) {
5042 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5043 optionsBlockAllThirdPartyRequestsMenuItem.title =
5044 nestedScrollWebView.getRequestsCount(THIRD_PARTY_REQUESTS).toString() + " - " + getString(R.string.block_all_third_party_requests)
5049 // The resource request was blocked. Return an empty web resource response.
5050 return emptyWebResourceResponse
5053 // Check UltraList if it is enabled.
5054 if (nestedScrollWebView.ultraListEnabled) {
5055 // Check the URL against UltraList.
5056 val ultraListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, ultraList)
5058 // Process the UltraList results.
5059 if (ultraListResults[0] == REQUEST_BLOCKED) { // The resource request matched UltraList's block list.
5060 // Add the result to the resource requests.
5061 nestedScrollWebView.addResourceRequest(arrayOf(ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]))
5063 // Increment the blocked requests counters.
5064 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5065 nestedScrollWebView.incrementRequestsCount(com.stoutner.privacybrowser.views.ULTRALIST)
5067 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5068 if (webViewDisplayed) {
5069 // Updating the UI must be run from the UI thread.
5071 // Update the menu item titles.
5072 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5074 // Update the options menu if it has been populated.
5075 if (optionsMenu != null) {
5076 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5077 optionsUltraListMenuItem.title = nestedScrollWebView.getRequestsCount(com.stoutner.privacybrowser.views.ULTRALIST).toString() + " - " + getString(R.string.ultralist)
5082 // The resource request was blocked. Return an empty web resource response.
5083 return emptyWebResourceResponse
5084 } else if (ultraListResults[0] == REQUEST_ALLOWED) { // The resource request matched UltraList's allow list.
5085 // Add an allow list entry to the resource requests array.
5086 nestedScrollWebView.addResourceRequest(arrayOf(ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]))
5088 // The resource request has been allowed by UltraList. `return null` loads the requested resource.
5093 // Check UltraPrivacy if it is enabled.
5094 if (nestedScrollWebView.ultraPrivacyEnabled) {
5095 // Check the URL against UltraPrivacy.
5096 val ultraPrivacyResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, ultraPrivacy!!)
5098 // Process the UltraPrivacy results.
5099 if (ultraPrivacyResults[0] == REQUEST_BLOCKED) { // The resource request matched UltraPrivacy's block list.
5100 // Add the result to the resource requests.
5101 nestedScrollWebView.addResourceRequest(arrayOf(ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5102 ultraPrivacyResults[5]))
5104 // Increment the blocked requests counters.
5105 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5106 nestedScrollWebView.incrementRequestsCount(ULTRAPRIVACY)
5108 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5109 if (webViewDisplayed) {
5110 // Updating the UI must be run from the UI thread.
5112 // Update the menu item titles.
5113 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5115 // Update the options menu if it has been populated.
5116 if (optionsMenu != null) {
5117 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5118 optionsUltraPrivacyMenuItem.title = nestedScrollWebView.getRequestsCount(ULTRAPRIVACY).toString() + " - " + getString(R.string.ultraprivacy)
5123 // The resource request was blocked. Return an empty web resource response.
5124 return emptyWebResourceResponse
5125 } else if (ultraPrivacyResults[0] == REQUEST_ALLOWED) { // The resource request matched UltraPrivacy's allow list.
5126 // Add an allow list entry to the resource requests array.
5127 nestedScrollWebView.addResourceRequest(arrayOf(ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5128 ultraPrivacyResults[5]))
5130 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
5135 // Check EasyList if it is enabled.
5136 if (nestedScrollWebView.easyListEnabled) {
5137 // Check the URL against EasyList.
5138 val easyListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, easyList)
5140 // Process the EasyList results.
5141 if (easyListResults[0] == REQUEST_BLOCKED) { // The resource request matched EasyList's block list.
5142 // Add the result to the resource requests.
5143 nestedScrollWebView.addResourceRequest(arrayOf(easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]))
5145 // Increment the blocked requests counters.
5146 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5147 nestedScrollWebView.incrementRequestsCount(EASYLIST)
5149 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5150 if (webViewDisplayed) {
5151 // Updating the UI must be run from the UI thread.
5153 // Update the menu item titles.
5154 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5156 // Update the options menu if it has been populated.
5157 if (optionsMenu != null) {
5158 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5159 optionsEasyListMenuItem.title = nestedScrollWebView.getRequestsCount(EASYLIST).toString() + " - " + getString(R.string.easylist)
5164 // The resource request was blocked. Return an empty web resource response.
5165 return emptyWebResourceResponse
5166 } else if (easyListResults[0] == REQUEST_ALLOWED) { // The resource request matched EasyList's allow list.
5167 // Update the allow list result string array tracker.
5168 allowListResultStringArray = arrayOf(easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5])
5172 // Check EasyPrivacy if it is enabled.
5173 if (nestedScrollWebView.easyPrivacyEnabled) {
5174 // Check the URL against EasyPrivacy.
5175 val easyPrivacyResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, easyPrivacy)
5177 // Process the EasyPrivacy results.
5178 if (easyPrivacyResults[0] == REQUEST_BLOCKED) { // The resource request matched EasyPrivacy's block list.
5179 // Add the result to the resource requests.
5180 nestedScrollWebView.addResourceRequest(arrayOf(easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5]))
5182 // Increment the blocked requests counters.
5183 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5184 nestedScrollWebView.incrementRequestsCount(EASYPRIVACY)
5186 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5187 if (webViewDisplayed) {
5188 // Updating the UI must be run from the UI thread.
5190 // Update the menu item titles.
5191 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5193 // Update the options menu if it has been populated.
5194 if (optionsMenu != null) {
5195 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5196 optionsEasyPrivacyMenuItem.title = nestedScrollWebView.getRequestsCount(EASYPRIVACY).toString() + " - " + getString(R.string.easyprivacy)
5201 // The resource request was blocked. Return an empty web resource response.
5202 return emptyWebResourceResponse
5203 } else if (easyPrivacyResults[0] == REQUEST_ALLOWED) { // The resource request matched EasyPrivacy's allow list.
5204 // Update the allow list result string array tracker.
5205 allowListResultStringArray = arrayOf(easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5])
5209 // Check Fanboy’s Annoyance List if it is enabled.
5210 if (nestedScrollWebView.fanboysAnnoyanceListEnabled) {
5211 // Check the URL against Fanboy's Annoyance List.
5212 val fanboysAnnoyanceListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, fanboysAnnoyanceList)
5214 // Process the Fanboy's Annoyance List results.
5215 if (fanboysAnnoyanceListResults[0] == REQUEST_BLOCKED) { // The resource request matched Fanboy's Annoyance List's block list.
5216 // Add the result to the resource requests.
5217 nestedScrollWebView.addResourceRequest(arrayOf(fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5218 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]))
5220 // Increment the blocked requests counters.
5221 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5222 nestedScrollWebView.incrementRequestsCount(FANBOYS_ANNOYANCE_LIST)
5224 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5225 if (webViewDisplayed) {
5226 // Updating the UI must be run from the UI thread.
5228 // Update the menu item titles.
5229 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5231 // Update the options menu if it has been populated.
5232 if (optionsMenu != null) {
5233 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5234 optionsFanboysAnnoyanceListMenuItem.title = nestedScrollWebView.getRequestsCount(FANBOYS_ANNOYANCE_LIST).toString() + " - " + getString(R.string.fanboys_annoyance_list)
5239 // The resource request was blocked. Return an empty web resource response.
5240 return emptyWebResourceResponse
5241 } else if (fanboysAnnoyanceListResults[0] == REQUEST_ALLOWED) { // The resource request matched Fanboy's Annoyance List's allow list.
5242 // Update the allow list result string array tracker.
5243 allowListResultStringArray = arrayOf(fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5244 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5])
5246 } else if (nestedScrollWebView.fanboysSocialBlockingListEnabled) { // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
5247 // Check the URL against Fanboy's Annoyance List.
5248 val fanboysSocialListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, fanboysSocialList)
5250 // Process the Fanboy's Social Blocking List results.
5251 if (fanboysSocialListResults[0] == REQUEST_BLOCKED) { // The resource request matched Fanboy's Social Blocking List's block list.
5252 // Add the result to the resource requests.
5253 nestedScrollWebView.addResourceRequest(arrayOf(fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5254 fanboysSocialListResults[4], fanboysSocialListResults[5]))
5256 // Increment the blocked requests counters.
5257 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5258 nestedScrollWebView.incrementRequestsCount(FANBOYS_SOCIAL_BLOCKING_LIST)
5260 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5261 if (webViewDisplayed) {
5262 // Updating the UI must be run from the UI thread.
5264 // Update the menu item titles.
5265 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5267 // Update the options menu if it has been populated.
5268 if (optionsMenu != null) {
5269 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5270 optionsFanboysSocialBlockingListMenuItem.title =
5271 nestedScrollWebView.getRequestsCount(FANBOYS_SOCIAL_BLOCKING_LIST).toString() + " - " + getString(R.string.fanboys_social_blocking_list)
5276 // The resource request was blocked. Return an empty web resource response.
5277 return emptyWebResourceResponse
5278 } else if (fanboysSocialListResults[0] == REQUEST_ALLOWED) { // The resource request matched Fanboy's Social Blocking List's allow list.
5279 // Update the allow list result string array tracker.
5280 allowListResultStringArray = arrayOf(fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3], fanboysSocialListResults[4],
5281 fanboysSocialListResults[5])
5285 // Add the request to the log because it hasn't been processed by any of the previous checks.
5286 if (allowListResultStringArray != null) { // The request was processed by an allow list.
5287 nestedScrollWebView.addResourceRequest(allowListResultStringArray)
5288 } else { // The request didn't match any filter list entry. Log it as a default request.
5289 nestedScrollWebView.addResourceRequest(arrayOf(REQUEST_DEFAULT, requestUrlString))
5292 // The resource request has not been blocked. `return null` loads the requested resource.
5296 // Handle HTTP authentication requests.
5297 override fun onReceivedHttpAuthRequest(view: WebView, handler: HttpAuthHandler, host: String, realm: String) {
5298 // Store the handler.
5299 nestedScrollWebView.httpAuthHandler = handler
5301 // Instantiate an HTTP authentication dialog.
5302 val httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm, nestedScrollWebView.webViewFragmentId)
5304 // Show the HTTP authentication dialog.
5305 httpAuthenticationDialogFragment.show(supportFragmentManager, getString(R.string.http_authentication))
5308 override fun onPageStarted(webView: WebView, url: String, favicon: Bitmap?) {
5309 // Get the app bar layout height. This can't be done in `applyAppSettings()` because the app bar is not yet populated there.
5310 // 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.
5311 if (appBarLayout.height > 0)
5312 appBarHeight = appBarLayout.height
5314 // Set the padding and layout settings according to the position of the app bar.
5315 if (bottomAppBar) { // The app bar is on the bottom.
5317 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) { // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
5318 // Reset the WebView padding to fill the available space.
5319 swipeRefreshLayout.setPadding(0, 0, 0, 0)
5320 } else { // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
5321 // Move the WebView above the app bar layout.
5322 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
5324 } else { // The app bar is on the top.
5325 // 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.
5326 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) { // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
5327 // No padding is needed because it will automatically be placed below the app bar layout due to the scrolling layout behavior.
5328 swipeRefreshLayout.setPadding(0, 0, 0, 0)
5330 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5331 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10, defaultProgressViewEndOffset)
5332 } else { // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
5333 // The swipe refresh layout must be manually moved below the app bar layout.
5334 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0)
5336 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5337 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight)
5341 // Reset the list of resource requests.
5342 nestedScrollWebView.clearResourceRequests()
5344 // Reset the requests counters.
5345 nestedScrollWebView.resetRequestsCounters()
5347 // Get the current page position.
5348 val currentPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
5350 // Update the URL text bar if the page is currently selected and the URL edit text is not currently being edited.
5351 if ((tabLayout.selectedTabPosition == currentPagePosition) && !urlEditText.hasFocus()) {
5352 // Display the formatted URL text.
5353 urlEditText.setText(url)
5355 // Highlight the URL syntax.
5356 UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
5358 // Hide the keyboard.
5359 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.windowToken, 0)
5362 // Reset the list of host IP addresses.
5363 nestedScrollWebView.currentIpAddresses = ""
5365 // Get a URI for the current URL.
5366 val currentUri = Uri.parse(url)
5368 // Get the current domain name.
5369 val currentDomainName = currentUri.host
5371 // Get the IP addresses for the current domain.
5372 if (!currentDomainName.isNullOrEmpty())
5373 GetHostIpAddressesCoroutine.checkPinnedMismatch(currentDomainName, nestedScrollWebView, supportFragmentManager, getString(R.string.pinned_mismatch))
5375 // 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.)
5376 if ((optionsMenu != null) && (webView == currentWebView)) {
5378 optionsRefreshMenuItem.setTitle(R.string.stop)
5380 // Set the icon if it is displayed in the AppBar.
5381 if (displayAdditionalAppBarIcons)
5382 optionsRefreshMenuItem.setIcon(R.drawable.close_blue)
5386 override fun onPageFinished(webView: WebView, url: String) {
5387 // Flush any cookies to persistent storage. The cookie manager has become very lazy about flushing cookies in recent versions.
5388 if (nestedScrollWebView.acceptCookies)
5389 cookieManager.flush()
5391 // Update the Refresh menu item if the options menu has been created and the WebView is currently displayed.
5392 if (optionsMenu != null && (webView == currentWebView)) {
5393 // Reset the Refresh title.
5394 optionsRefreshMenuItem.setTitle(R.string.refresh)
5396 // Reset the icon if it is displayed in the app bar.
5397 if (displayAdditionalAppBarIcons)
5398 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled)
5401 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
5402 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
5403 val privateDataDirectoryString = applicationInfo.dataDir
5405 // Clear the cache, history, and logcat if Incognito Mode is enabled.
5406 if (incognitoModeEnabled) {
5407 // Clear the cache. `true` includes disk files.
5408 nestedScrollWebView.clearCache(true)
5410 // Clear the back/forward history.
5411 nestedScrollWebView.clearHistory()
5413 // Manually delete cache folders.
5415 // Delete the main cache directory.
5416 Runtime.getRuntime().exec("rm -rf $privateDataDirectoryString/cache")
5417 } catch (exception: IOException) {
5418 // Do nothing if an error is thrown.
5421 // Clear the logcat.
5423 // Clear the logcat. `-c` clears the logcat. `-b all` clears all the buffers (instead of just crash, main, and system).
5424 Runtime.getRuntime().exec("logcat -b all -c")
5425 } catch (exception: IOException) {
5430 // Clear the `Service Worker` directory.
5432 // A string array must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
5433 Runtime.getRuntime().exec(arrayOf("rm", "-rf", "$privateDataDirectoryString/app_webview/Default/Service Worker/"))
5434 } catch (exception: IOException) {
5438 // Get the current page position.
5439 val currentPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
5441 // 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.
5442 val currentUrl = nestedScrollWebView.url
5444 // Get the current tab.
5445 val tab = tabLayout.getTabAt(currentPagePosition)
5447 // Update the URL text bar if the page is currently selected and the user is not currently typing in the URL edit text.
5448 // Crash records show that, in some crazy way, it is possible for the current URL to be blank at this point.
5449 // Probably some sort of race condition when Privacy Browser is being resumed.
5450 if ((tabLayout.selectedTabPosition == currentPagePosition) && !urlEditText.hasFocus() && (currentUrl != null)) {
5451 // Check to see if the URL is `about:blank`.
5452 if (currentUrl == "about:blank") { // The WebView is blank.
5453 // Display the hint in the URL edit text.
5454 urlEditText.setText("")
5456 // Request focus for the URL text box.
5457 urlEditText.requestFocus()
5459 // Display the keyboard.
5460 inputMethodManager.showSoftInput(urlEditText, 0)
5462 // Apply the domain settings. This clears any settings from the previous domain.
5463 applyDomainSettings(nestedScrollWebView, "", resetTab = true, reloadWebsite = false, loadUrl = false)
5465 // Only populate the title text view if the tab has been fully created.
5467 // Get the custom view from the tab.
5468 val tabView = tab.customView!!
5470 // Get the title text view from the tab.
5471 val tabTitleTextView = tabView.findViewById<TextView>(R.id.title_textview)
5473 // Set the title as the tab text.
5474 tabTitleTextView.setText(R.string.new_tab)
5476 } else { // The WebView has loaded a webpage.
5477 // Update the URL edit text if it is not currently being edited.
5478 if (!urlEditText.hasFocus()) {
5479 // 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.
5480 val sanitizedUrl = sanitizeUrl(currentUrl)
5482 // Display the final URL. Getting the URL from the WebView instead of using the one provided by `onPageFinished()` makes websites like YouTube function correctly.
5483 urlEditText.setText(sanitizedUrl)
5485 // Highlight the URL syntax.
5486 UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
5489 // Only populate the title text view if the tab has been fully created.
5491 // Get the custom view from the tab.
5492 val tabView = tab.customView!!
5494 // Get the title text view from the tab.
5495 val tabTitleTextView = tabView.findViewById<TextView>(R.id.title_textview)
5497 // Set the title as the tab text. Sometimes `onReceivedTitle()` is not called, especially when navigating history.
5498 tabTitleTextView.text = nestedScrollWebView.title
5504 // Handle SSL Certificate errors. Suppress the lint warning that ignoring the error might be dangerous.
5505 @SuppressLint("WebViewClientOnReceivedSslError")
5506 override fun onReceivedSslError(view: WebView, handler: SslErrorHandler, error: SslError) {
5507 // Get the current website SSL certificate.
5508 val currentWebsiteSslCertificate = error.certificate
5510 // Extract the individual pieces of information from the current website SSL certificate.
5511 val currentWebsiteIssuedToCName = currentWebsiteSslCertificate.issuedTo.cName
5512 val currentWebsiteIssuedToOName = currentWebsiteSslCertificate.issuedTo.oName
5513 val currentWebsiteIssuedToUName = currentWebsiteSslCertificate.issuedTo.uName
5514 val currentWebsiteIssuedByCName = currentWebsiteSslCertificate.issuedBy.cName
5515 val currentWebsiteIssuedByOName = currentWebsiteSslCertificate.issuedBy.oName
5516 val currentWebsiteIssuedByUName = currentWebsiteSslCertificate.issuedBy.uName
5517 val currentWebsiteSslStartDate = currentWebsiteSslCertificate.validNotBeforeDate
5518 val currentWebsiteSslEndDate = currentWebsiteSslCertificate.validNotAfterDate
5520 // Get the pinned SSL certificate.
5521 val (pinnedSslCertificateStringArray, pinnedSslCertificateDateArray) = nestedScrollWebView.getPinnedSslCertificate()
5523 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
5524 if (nestedScrollWebView.hasPinnedSslCertificate() &&
5525 (currentWebsiteIssuedToCName == pinnedSslCertificateStringArray[0]) &&
5526 (currentWebsiteIssuedToOName == pinnedSslCertificateStringArray[1]) &&
5527 (currentWebsiteIssuedToUName == pinnedSslCertificateStringArray[2]) &&
5528 (currentWebsiteIssuedByCName == pinnedSslCertificateStringArray[3]) &&
5529 (currentWebsiteIssuedByOName == pinnedSslCertificateStringArray[4]) &&
5530 (currentWebsiteIssuedByUName == pinnedSslCertificateStringArray[5]) &&
5531 (currentWebsiteSslStartDate == pinnedSslCertificateDateArray[0]) &&
5532 (currentWebsiteSslEndDate == pinnedSslCertificateDateArray[1])) {
5534 // An SSL certificate is pinned and matches the current domain certificate. Proceed to the website without displaying an error.
5536 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
5537 // Store the SSL error handler.
5538 nestedScrollWebView.sslErrorHandler = handler
5540 // Instantiate an SSL certificate error alert dialog.
5541 val sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error, nestedScrollWebView.webViewFragmentId)
5543 // 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.
5545 // Show the SSL certificate error dialog.
5546 sslCertificateErrorDialogFragment.show(supportFragmentManager, getString(R.string.ssl_certificate_error))
5547 } catch (exception: Exception) {
5548 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
5549 pendingDialogsArrayList.add(PendingDialogDataClass(sslCertificateErrorDialogFragment, getString(R.string.ssl_certificate_error)))
5555 // Check to see if the state is being restored.
5556 if (restoringState) { // The state is being restored.
5557 // Resume the nested scroll WebView JavaScript timers.
5558 nestedScrollWebView.resumeTimers()
5559 } else if (pageNumber == 0) { // The first page is being loaded.
5560 // Set this nested scroll WebView as the current WebView.
5561 currentWebView = nestedScrollWebView
5563 // Get the intent that started the app.
5564 val launchingIntent = intent
5566 // Reset the intent. This prevents a duplicate tab from being created on restart.
5569 // Get the information from the intent.
5570 val launchingIntentAction = launchingIntent.action
5571 val launchingIntentUriData = launchingIntent.data
5572 val launchingIntentStringExtra = launchingIntent.getStringExtra(Intent.EXTRA_TEXT)
5574 // Parse the launching intent URL. Suppress the suggestions of using elvis expressions as they make the logic very difficult to follow.
5575 @Suppress("IfThenToElvis") val urlToLoadString = if ((launchingIntentAction != null) && (launchingIntentAction == Intent.ACTION_WEB_SEARCH)) { // The intent contains a search string.
5576 // Sanitize the search input and convert it to a search.
5577 val encodedSearchString = try {
5578 URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8")
5579 } catch (exception: UnsupportedEncodingException) {
5583 // Add the search URL to the encodedSearchString
5584 searchURL + encodedSearchString
5585 } else if (launchingIntentUriData != null) { // The launching intent contains a URL formatted as a URI.
5586 // Get the URL from the URI.
5587 launchingIntentUriData.toString()
5588 } else if (launchingIntentStringExtra != null) { // The launching intent contains text that might be a URL.
5589 // Get the URL from the string extra.
5590 launchingIntentStringExtra
5591 } else if (urlString != "") { // The activity has been restarted.
5592 // Load the saved URL.
5594 } else { // The is no saved URL and there is no URL in the intent.
5595 // Load the homepage.
5596 sharedPreferences.getString("homepage", getString(R.string.homepage_default_value))
5599 // Load the website if not waiting for the proxy.
5600 if (waitingForProxy) { // Store the URL to be loaded in the Nested Scroll WebView.
5601 nestedScrollWebView.waitingForProxyUrlString = urlToLoadString!!
5602 } else { // Load the URL.
5603 loadUrl(nestedScrollWebView, urlToLoadString!!)
5606 // 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.
5607 // 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.
5609 } else { // This is not the first tab.
5611 loadUrl(nestedScrollWebView, urlString)
5613 // Set the focus and display the keyboard if the URL is blank.
5614 if (urlString == "") {
5615 // Request focus for the URL text box.
5616 urlEditText.requestFocus()
5618 // Create a display keyboard handler.
5619 val displayKeyboardHandler = Handler(Looper.getMainLooper())
5621 // Create a display keyboard runnable.
5622 val displayKeyboardRunnable = Runnable {
5623 // Display the keyboard.
5624 inputMethodManager.showSoftInput(urlEditText, 0)
5627 // Display the keyboard after 100 milliseconds, which leaves enough time for the tab to transition.
5628 displayKeyboardHandler.postDelayed(displayKeyboardRunnable, 100)
5633 private fun loadBookmarksFolder() {
5634 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
5635 bookmarksCursor = bookmarksDatabaseHelper!!.getBookmarksByDisplayOrder(currentBookmarksFolderId)
5637 // Populate the bookmarks cursor adapter.
5638 bookmarksCursorAdapter = object : CursorAdapter(this, bookmarksCursor, false) {
5639 override fun newView(context: Context, cursor: Cursor, parent: ViewGroup): View {
5640 // Inflate the individual item layout.
5641 return layoutInflater.inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false)
5644 override fun bindView(view: View, context: Context, cursor: Cursor) {
5645 // Get handles for the views.
5646 val bookmarkFavoriteIcon = view.findViewById<ImageView>(R.id.bookmark_favorite_icon)
5647 val bookmarkNameTextView = view.findViewById<TextView>(R.id.bookmark_name)
5649 // Get the favorite icon byte array from the cursor.
5650 val favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndexOrThrow(FAVORITE_ICON))
5652 // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
5653 val favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.size)
5655 // Display the bitmap in the bookmark favorite icon.
5656 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap)
5658 // Display the bookmark name from the cursor in the bookmark name text view.
5659 bookmarkNameTextView.text = cursor.getString(cursor.getColumnIndexOrThrow(BOOKMARK_NAME))
5661 // Make the font bold for folders.
5662 if (cursor.getInt(cursor.getColumnIndexOrThrow(IS_FOLDER)) == 1)
5663 bookmarkNameTextView.typeface = Typeface.DEFAULT_BOLD
5664 else // Reset the font to default for normal bookmarks.
5665 bookmarkNameTextView.typeface = Typeface.DEFAULT
5669 // Populate the list view with the adapter.
5670 bookmarksListView.adapter = bookmarksCursorAdapter
5672 // Set the bookmarks drawer title.
5673 if (currentBookmarksFolderId == HOME_FOLDER_ID) // The current bookmarks folder is the home folder.
5674 bookmarksTitleTextView.setText(R.string.bookmarks)
5676 bookmarksTitleTextView.text = bookmarksDatabaseHelper!!.getFolderName(currentBookmarksFolderId)
5679 private fun loadUrl(nestedScrollWebView: NestedScrollWebView, url: String) {
5680 // Sanitize the URL.
5681 val urlString = sanitizeUrl(url)
5683 // Apply the domain settings and load the URL.
5684 applyDomainSettings(nestedScrollWebView, urlString, resetTab = true, reloadWebsite = false, loadUrl = true)
5687 private fun loadUrlFromTextBox() {
5688 // 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.
5689 var unformattedUrlString = urlEditText.text.toString().trim { it <= ' ' }
5691 // Create the formatted URL string.
5694 // Check to see if the unformatted URL string is a valid URL. Otherwise, convert it into a search.
5695 if (unformattedUrlString.startsWith("content://")) { // This is a content URL.
5696 // Load the entire content URL.
5697 urlString = unformattedUrlString
5698 } else if (Patterns.WEB_URL.matcher(unformattedUrlString).matches() || unformattedUrlString.startsWith("http://") || unformattedUrlString.startsWith("https://") ||
5699 unformattedUrlString.startsWith("file://")) { // This is a standard URL.
5701 // Add `https://` at the beginning if there is no protocol. Otherwise the app will segfault.
5702 if (!unformattedUrlString.startsWith("http") && !unformattedUrlString.startsWith("file://"))
5703 unformattedUrlString = "https://$unformattedUrlString"
5705 // Initialize the unformatted URL.
5706 var unformattedUrl: URL? = null
5708 // Convert the unformatted URL string to a URL.
5710 unformattedUrl = URL(unformattedUrlString)
5711 } catch (exception: MalformedURLException) {
5712 exception.printStackTrace()
5715 // Get the components of the URL.
5716 val scheme = unformattedUrl?.protocol
5717 val authority = unformattedUrl?.authority
5718 val path = unformattedUrl?.path
5719 val query = unformattedUrl?.query
5720 val fragment = unformattedUrl?.ref
5723 val uri = Uri.Builder()
5725 // Build the URI from the components of the URL.
5726 uri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment)
5728 // Decode the URI as a UTF-8 string in.
5730 urlString = URLDecoder.decode(uri.build().toString(), "UTF-8")
5731 } catch (exception: UnsupportedEncodingException) {
5732 // Do nothing. The formatted URL string will remain blank.
5734 } else if (unformattedUrlString.isNotEmpty()) { // This is not a URL, but rather a search string.
5735 // Sanitize the search input.
5736 val encodedSearchString = try {
5737 URLEncoder.encode(unformattedUrlString, "UTF-8")
5738 } catch (exception: UnsupportedEncodingException) {
5742 // Add the base search URL.
5743 urlString = searchURL + encodedSearchString
5746 // 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.
5747 urlEditText.clearFocus()
5750 loadUrl(currentWebView!!, urlString)
5753 override fun navigateHistory(url: String, steps: Int) {
5754 // Apply the domain settings.
5755 applyDomainSettings(currentWebView!!, url, resetTab = false, reloadWebsite = false, loadUrl = false)
5757 // Load the history entry.
5758 currentWebView!!.goBackOrForward(steps)
5761 override fun openFile(dialogFragment: DialogFragment) {
5763 val dialog = dialogFragment.dialog!!
5765 // Get handles for the views.
5766 val fileNameEditText = dialog.findViewById<EditText>(R.id.file_name_edittext)
5767 val mhtCheckBox = dialog.findViewById<CheckBox>(R.id.mht_checkbox)
5769 // Get the file path string.
5770 val openFilePath = fileNameEditText.text.toString()
5772 // Apply the domain settings. This resets the favorite icon and removes any domain settings.
5773 applyDomainSettings(currentWebView!!, openFilePath, resetTab = true, reloadWebsite = false, loadUrl = false)
5775 // Open the file according to the type.
5776 if (mhtCheckBox.isChecked) { // Force opening of an MHT file.
5778 // Get the MHT file input stream.
5779 val mhtFileInputStream = contentResolver.openInputStream(Uri.parse(openFilePath))
5781 // Create a temporary MHT file.
5782 val temporaryMhtFile = File.createTempFile(TEMPORARY_MHT_FILE, ".mht", cacheDir)
5784 // Get a file output stream for the temporary MHT file.
5785 val temporaryMhtFileOutputStream = FileOutputStream(temporaryMhtFile)
5787 // Create a transfer byte array.
5788 val transferByteArray = ByteArray(1024)
5790 // Create an integer to track the number of bytes read.
5793 // Copy the temporary MHT file input stream to the MHT output stream.
5794 while (mhtFileInputStream!!.read(transferByteArray).also { bytesRead = it } > 0)
5795 temporaryMhtFileOutputStream.write(transferByteArray, 0, bytesRead)
5797 // Flush the temporary MHT file output stream.
5798 temporaryMhtFileOutputStream.flush()
5800 // Close the streams.
5801 temporaryMhtFileOutputStream.close()
5802 mhtFileInputStream.close()
5804 // Load the temporary MHT file.
5805 currentWebView!!.loadUrl(temporaryMhtFile.toString())
5806 } catch (exception: Exception) {
5807 // Display a snackbar.
5808 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
5810 } else { // Let the WebView handle opening of the file.
5812 currentWebView!!.loadUrl(openFilePath)
5816 private fun openWithApp(url: String) {
5817 // Create an open with app intent with `ACTION_VIEW`.
5818 val openWithAppIntent = Intent(Intent.ACTION_VIEW)
5820 // Set the URI but not the MIME type. This should open all available apps.
5821 openWithAppIntent.data = Uri.parse(url)
5823 // Flag the intent to open in a new task.
5824 openWithAppIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
5828 // Show the chooser.
5829 startActivity(openWithAppIntent)
5830 } catch (exception: ActivityNotFoundException) { // There are no apps available to open the URL.
5831 // Show a snackbar with the error.
5832 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
5836 private fun openWithBrowser(url: String) {
5838 // Create an open with browser intent with `ACTION_VIEW`.
5839 val openWithBrowserIntent = Intent(Intent.ACTION_VIEW)
5841 // Set the URI and the MIME type. `"text/html"` should load browser options.
5842 openWithBrowserIntent.setDataAndType(Uri.parse(url), "text/html")
5844 // Flag the intent to open in a new task.
5845 openWithBrowserIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
5849 // Show the chooser.
5850 startActivity(openWithBrowserIntent)
5851 } catch (exception: ActivityNotFoundException) { // There are no browsers available to open the URL.
5852 // Show a snackbar with the error.
5853 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
5857 override fun pinnedErrorGoBack() {
5858 // Get the current web back forward list.
5859 val webBackForwardList = currentWebView!!.copyBackForwardList()
5861 // Get the previous entry URL.
5862 val previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex - 1).url
5864 // Apply the domain settings.
5865 applyDomainSettings(currentWebView!!, previousUrl, resetTab = false, reloadWebsite = false, loadUrl = false)
5868 currentWebView!!.goBack()
5871 private fun sanitizeUrl(urlString: String): String {
5872 // Initialize a sanitized URL string.
5873 var sanitizedUrlString = urlString
5875 // Sanitize tracking queries.
5876 if (sanitizeTrackingQueries)
5877 sanitizedUrlString = SanitizeUrlHelper.sanitizeTrackingQueries(sanitizedUrlString)
5879 // Sanitize AMP redirects.
5880 if (sanitizeAmpRedirects)
5881 sanitizedUrlString = SanitizeUrlHelper.sanitizeAmpRedirects(sanitizedUrlString)
5883 // Return the sanitized URL string.
5884 return sanitizedUrlString
5887 override fun saveUrl(originalUrlString: String, fileNameString: String, dialogFragment: DialogFragment) {
5888 // Store the URL. This will be used in the save URL activity result launcher.
5889 saveUrlString = if (originalUrlString.startsWith("data:")) {
5890 // Save the original URL.
5894 val dialog = dialogFragment.dialog!!
5896 // Get a handle for the dialog URL edit text.
5897 val dialogUrlEditText = dialog.findViewById<EditText>(R.id.url_edittext)
5899 // Get the URL from the edit text, which may have been modified.
5900 dialogUrlEditText.text.toString()
5903 // Open the file picker.
5904 saveUrlActivityResultLauncher.launch(fileNameString)
5907 private fun setCurrentWebView(pageNumber: Int) {
5908 // Stop the swipe to refresh indicator if it is running
5909 swipeRefreshLayout.isRefreshing = false
5911 // Get the WebView tab fragment.
5912 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(pageNumber)
5914 // Get the fragment view.
5915 val webViewFragmentView = webViewTabFragment.view
5917 // Set the current WebView if the fragment view is not null.
5918 if (webViewFragmentView != null) { // The fragment has been populated.
5919 // Store the current WebView.
5920 currentWebView = webViewFragmentView.findViewById(R.id.nestedscroll_webview)
5922 // Update the status of swipe to refresh.
5923 if (currentWebView!!.swipeToRefresh) { // Swipe to refresh is enabled.
5924 // Enable the swipe refresh layout if the WebView is scrolled all the way to the top. It is updated every time the scroll changes.
5925 swipeRefreshLayout.isEnabled = (currentWebView!!.scrollY == 0)
5926 } else { // Swipe to refresh is disabled.
5927 // Disable the swipe refresh layout.
5928 swipeRefreshLayout.isEnabled = false
5931 // Set the cookie status.
5932 cookieManager.setAcceptCookie(currentWebView!!.acceptCookies)
5934 // Update the privacy icons. `true` redraws the icons in the app bar.
5935 updatePrivacyIcons(true)
5937 // Get a handle for the input method manager.
5938 val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
5940 // Get the current URL.
5941 val urlString = currentWebView!!.url
5943 // Update the URL edit text if not loading a new intent. Otherwise, this will be handled by `onPageStarted()` (if called) and `onPageFinished()`.
5944 if (!loadingNewIntent) { // A new intent is not being loaded.
5945 if ((urlString == null) || (urlString == "about:blank")) { // The WebView is blank.
5946 // Display the hint in the URL edit text.
5947 urlEditText.setText("")
5949 // Request focus for the URL text box.
5950 urlEditText.requestFocus()
5952 // Display the keyboard.
5953 inputMethodManager.showSoftInput(urlEditText, 0)
5954 } else { // The WebView has a loaded URL.
5955 // Clear the focus from the URL text box.
5956 urlEditText.clearFocus()
5958 // Hide the soft keyboard.
5959 inputMethodManager.hideSoftInputFromWindow(currentWebView!!.windowToken, 0)
5961 // Display the current URL in the URL text box.
5962 urlEditText.setText(urlString)
5964 // Highlight the URL syntax.
5965 UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
5967 } else { // A new intent is being loaded.
5968 // Reset the loading new intent flag.
5969 loadingNewIntent = false
5972 // Set the background to indicate the domain settings status.
5973 if (currentWebView!!.domainSettingsApplied) {
5974 // Set a background on the URL relative layout to indicate that custom domain settings are being used.
5975 urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.drawable.domain_settings_url_background)
5977 // Remove any background on the URL relative layout.
5978 urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.color.transparent)
5980 } else if ((pageNumber == savedTabPosition) || (pageNumber >= (webViewStateAdapter!!.itemCount - 1))) { // The tab has not been populated yet.
5981 // Try again in 100 milliseconds if the app is being restored or the a new tab has been added (the last tab).
5982 // Create a handler to set the current WebView.
5983 val setCurrentWebViewHandler = Handler(Looper.getMainLooper())
5985 // Create a runnable to set the current WebView.
5986 val setCurrentWebWebRunnable = Runnable {
5987 // Set the current WebView.
5988 setCurrentWebView(pageNumber)
5991 // Try setting the current WebView again after 100 milliseconds.
5992 setCurrentWebViewHandler.postDelayed(setCurrentWebWebRunnable, 100)
5996 // The view parameter cannot be removed because it is called from the layout onClick.
5997 fun toggleBookmarksDrawerPinned(@Suppress("UNUSED_PARAMETER")view: View?) {
5998 // Toggle the bookmarks drawer pinned tracker.
5999 bookmarksDrawerPinned = !bookmarksDrawerPinned
6001 // Update the bookmarks drawer pinned image view.
6002 updateBookmarksDrawerPinnedImageView()
6005 private fun updateBookmarksDrawerPinnedImageView() {
6006 // Set the current icon.
6007 if (bookmarksDrawerPinned)
6008 bookmarksDrawerPinnedImageView.setImageResource(R.drawable.pin_selected)
6010 bookmarksDrawerPinnedImageView.setImageResource(R.drawable.pin)
6013 private fun updateDomainsSettingsSet() {
6014 // Reset the domains settings set.
6015 domainsSettingsSet = HashSet()
6017 // Get a domains cursor.
6018 val domainsCursor = domainsDatabaseHelper!!.domainNameCursorOrderedByDomain
6020 // Get the current count of domains.
6021 val domainsCount = domainsCursor.count
6023 // Get the domain name column index.
6024 val domainNameColumnIndex = domainsCursor.getColumnIndexOrThrow(DOMAIN_NAME)
6026 // Populate the domain settings set.
6027 for (i in 0 until domainsCount) {
6028 // Move the domains cursor to the current row.
6029 domainsCursor.moveToPosition(i)
6031 // Store the domain name in the domain settings set.
6032 domainsSettingsSet.add(domainsCursor.getString(domainNameColumnIndex))
6035 // Close the domains cursor.
6036 domainsCursor.close()
6039 override fun updateFontSize(dialogFragment: DialogFragment) {
6041 val dialog = dialogFragment.dialog!!
6043 // Get a handle for the font size edit text.
6044 val fontSizeEditText = dialog.findViewById<EditText>(R.id.font_size_edittext)
6046 // Initialize the new font size variable with the current font size.
6047 var newFontSize = currentWebView!!.settings.textZoom
6049 // Get the font size from the edit text.
6051 newFontSize = fontSizeEditText.text.toString().toInt()
6052 } catch (exception: Exception) {
6053 // If the edit text does not contain a valid font size do nothing.
6056 // Apply the new font size.
6057 currentWebView!!.settings.textZoom = newFontSize
6060 private fun updatePrivacyIcons(runInvalidateOptionsMenu: Boolean) {
6061 // Only update the privacy icons if the options menu and the current WebView have already been populated.
6062 if ((optionsMenu != null) && (currentWebView != null)) {
6063 // Update the privacy icon.
6064 if (currentWebView!!.settings.javaScriptEnabled) // JavaScript is enabled.
6065 optionsPrivacyMenuItem.setIcon(R.drawable.javascript_enabled)
6066 else if (currentWebView!!.acceptCookies) // JavaScript is disabled but cookies are enabled.
6067 optionsPrivacyMenuItem.setIcon(R.drawable.warning)
6068 else // All the dangerous features are disabled.
6069 optionsPrivacyMenuItem.setIcon(R.drawable.privacy_mode)
6071 // Update the cookies icon.
6072 if (currentWebView!!.acceptCookies)
6073 optionsCookiesMenuItem.setIcon(R.drawable.cookies_enabled)
6075 optionsCookiesMenuItem.setIcon(R.drawable.cookies_disabled)
6077 // Update the refresh icon.
6078 if (optionsRefreshMenuItem.title == getString(R.string.refresh)) // The refresh icon is displayed.
6079 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled)
6080 else // The stop icon is displayed.
6081 optionsRefreshMenuItem.setIcon(R.drawable.close_blue)
6083 // `invalidateOptionsMenu()` calls `onPrepareOptionsMenu()` and redraws the icons in the app bar.
6084 if (runInvalidateOptionsMenu)
6085 invalidateOptionsMenu()