2 * Copyright 2015-2023 Soren Stoutner <soren@stoutner.com>.
4 * Download cookie code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
6 * This file is part of Privacy Browser Android <https://www.stoutner.com/privacy-browser-android>.
8 * Privacy Browser Android is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
13 * Privacy Browser Android is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with Privacy Browser Android. If not, see <http://www.gnu.org/licenses/>.
22 package com.stoutner.privacybrowser.activities
24 import android.animation.ObjectAnimator
25 import android.annotation.SuppressLint
26 import android.app.DownloadManager
27 import android.app.SearchManager
28 import android.content.ActivityNotFoundException
29 import android.content.BroadcastReceiver
30 import android.content.ClipData
31 import android.content.ClipboardManager
32 import android.content.Context
33 import android.content.Intent
34 import android.content.IntentFilter
35 import android.content.SharedPreferences
36 import android.content.pm.PackageManager
37 import android.content.res.Configuration
38 import android.database.Cursor
39 import android.graphics.Bitmap
40 import android.graphics.BitmapFactory
41 import android.graphics.Typeface
42 import android.graphics.drawable.BitmapDrawable
43 import android.net.Uri
44 import android.net.http.SslError
45 import android.os.Build
46 import android.os.Bundle
47 import android.os.Environment
48 import android.os.Handler
49 import android.os.Looper
50 import android.print.PrintManager
51 import android.provider.DocumentsContract
52 import android.provider.OpenableColumns
53 import android.text.Editable
54 import android.text.TextWatcher
55 import android.text.style.ForegroundColorSpan
56 import android.util.Patterns
57 import android.util.TypedValue
58 import android.view.ContextMenu
59 import android.view.GestureDetector
60 import android.view.KeyEvent
61 import android.view.Menu
62 import android.view.MenuItem
63 import android.view.MotionEvent
64 import android.view.View
65 import android.view.ViewGroup
66 import android.view.WindowManager
67 import android.view.inputmethod.InputMethodManager
68 import android.webkit.CookieManager
69 import android.webkit.HttpAuthHandler
70 import android.webkit.ValueCallback
71 import android.webkit.SslErrorHandler
72 import android.webkit.WebChromeClient
73 import android.webkit.WebResourceRequest
74 import android.webkit.WebResourceResponse
75 import android.webkit.WebSettings
76 import android.webkit.WebStorage
77 import android.webkit.WebView
78 import android.webkit.WebViewClient
79 import android.webkit.WebViewDatabase
80 import android.widget.AdapterView
81 import android.widget.ArrayAdapter
82 import android.widget.CheckBox
83 import android.widget.EditText
84 import android.widget.FrameLayout
85 import android.widget.ImageView
86 import android.widget.LinearLayout
87 import android.widget.ListView
88 import android.widget.ProgressBar
89 import android.widget.RadioButton
90 import android.widget.RelativeLayout
91 import android.widget.TextView
93 import androidx.activity.OnBackPressedCallback
94 import androidx.activity.result.contract.ActivityResultContracts
95 import androidx.appcompat.app.ActionBar
96 import androidx.appcompat.app.ActionBarDrawerToggle
97 import androidx.appcompat.app.AppCompatActivity
98 import androidx.appcompat.app.AppCompatDelegate
99 import androidx.appcompat.content.res.AppCompatResources
100 import androidx.appcompat.widget.Toolbar
101 import androidx.coordinatorlayout.widget.CoordinatorLayout
102 import androidx.core.view.GravityCompat
103 import androidx.cursoradapter.widget.CursorAdapter
104 import androidx.drawerlayout.widget.DrawerLayout
105 import androidx.fragment.app.DialogFragment
106 import androidx.preference.PreferenceManager
107 import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
108 import androidx.viewpager2.widget.ViewPager2
109 import androidx.webkit.WebSettingsCompat
110 import androidx.webkit.WebViewFeature
112 import com.google.android.material.appbar.AppBarLayout
113 import com.google.android.material.floatingactionbutton.FloatingActionButton
114 import com.google.android.material.navigation.NavigationView
115 import com.google.android.material.snackbar.Snackbar
116 import com.google.android.material.tabs.TabLayout
118 import com.stoutner.privacybrowser.R
119 import com.stoutner.privacybrowser.adapters.WebViewStateAdapter
120 import com.stoutner.privacybrowser.coroutines.GetHostIpAddressesCoroutine
121 import com.stoutner.privacybrowser.coroutines.PopulateFilterListsCoroutine
122 import com.stoutner.privacybrowser.coroutines.PrepareSaveDialogCoroutine
123 import com.stoutner.privacybrowser.coroutines.SaveUrlCoroutine
124 import com.stoutner.privacybrowser.coroutines.SaveWebpageImageCoroutine
125 import com.stoutner.privacybrowser.dataclasses.PendingDialogDataClass
126 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog
127 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog
128 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog
129 import com.stoutner.privacybrowser.dialogs.FontSizeDialog
130 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog
131 import com.stoutner.privacybrowser.dialogs.OpenDialog
132 import com.stoutner.privacybrowser.dialogs.PinnedMismatchDialog
133 import com.stoutner.privacybrowser.dialogs.ProxyNotInstalledDialog
134 import com.stoutner.privacybrowser.dialogs.SaveDialog
135 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog
136 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog
137 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog
138 import com.stoutner.privacybrowser.dialogs.WaitingForProxyDialog
139 import com.stoutner.privacybrowser.fragments.WebViewTabFragment
140 import com.stoutner.privacybrowser.helpers.COOKIES
141 import com.stoutner.privacybrowser.helpers.DARK_THEME
142 import com.stoutner.privacybrowser.helpers.DISABLED
143 import com.stoutner.privacybrowser.helpers.DISPLAY_IMAGES
144 import com.stoutner.privacybrowser.helpers.DOMAIN_NAME
145 import com.stoutner.privacybrowser.helpers.ENABLE_DOM_STORAGE
146 import com.stoutner.privacybrowser.helpers.ENABLE_EASYLIST
147 import com.stoutner.privacybrowser.helpers.ENABLE_EASYPRIVACY
148 import com.stoutner.privacybrowser.helpers.ENABLE_FANBOYS_ANNOYANCE_LIST
149 import com.stoutner.privacybrowser.helpers.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST
150 import com.stoutner.privacybrowser.helpers.ENABLE_FORM_DATA
151 import com.stoutner.privacybrowser.helpers.ENABLE_JAVASCRIPT
152 import com.stoutner.privacybrowser.helpers.ENABLE_ULTRAPRIVACY
153 import com.stoutner.privacybrowser.helpers.ENABLED
154 import com.stoutner.privacybrowser.helpers.FONT_SIZE
155 import com.stoutner.privacybrowser.helpers.ID
156 import com.stoutner.privacybrowser.helpers.IP_ADDRESSES
157 import com.stoutner.privacybrowser.helpers.LIGHT_THEME
158 import com.stoutner.privacybrowser.helpers.PINNED_IP_ADDRESSES
159 import com.stoutner.privacybrowser.helpers.PINNED_SSL_CERTIFICATE
160 import com.stoutner.privacybrowser.helpers.REQUEST_ALLOWED
161 import com.stoutner.privacybrowser.helpers.REQUEST_BLOCKED
162 import com.stoutner.privacybrowser.helpers.REQUEST_DEFAULT
163 import com.stoutner.privacybrowser.helpers.REQUEST_THIRD_PARTY
164 import com.stoutner.privacybrowser.helpers.SSL_ISSUED_BY_COMMON_NAME
165 import com.stoutner.privacybrowser.helpers.SSL_ISSUED_BY_ORGANIZATION
166 import com.stoutner.privacybrowser.helpers.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT
167 import com.stoutner.privacybrowser.helpers.SSL_ISSUED_TO_COMMON_NAME
168 import com.stoutner.privacybrowser.helpers.SSL_ISSUED_TO_ORGANIZATION
169 import com.stoutner.privacybrowser.helpers.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT
170 import com.stoutner.privacybrowser.helpers.SWIPE_TO_REFRESH
171 import com.stoutner.privacybrowser.helpers.SYSTEM_DEFAULT
172 import com.stoutner.privacybrowser.helpers.WEBVIEW_THEME
173 import com.stoutner.privacybrowser.helpers.WIDE_VIEWPORT
174 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper
175 import com.stoutner.privacybrowser.helpers.CheckFilterListHelper
176 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper
177 import com.stoutner.privacybrowser.helpers.ProxyHelper
178 import com.stoutner.privacybrowser.helpers.SanitizeUrlHelper
179 import com.stoutner.privacybrowser.helpers.UrlHelper
180 import com.stoutner.privacybrowser.views.BLOCKED_REQUESTS
181 import com.stoutner.privacybrowser.views.EASYLIST
182 import com.stoutner.privacybrowser.views.EASYPRIVACY
183 import com.stoutner.privacybrowser.views.FANBOYS_ANNOYANCE_LIST
184 import com.stoutner.privacybrowser.views.FANBOYS_SOCIAL_BLOCKING_LIST
185 import com.stoutner.privacybrowser.views.THIRD_PARTY_REQUESTS
186 import com.stoutner.privacybrowser.views.ULTRAPRIVACY
187 import com.stoutner.privacybrowser.views.NestedScrollWebView
189 import kotlinx.coroutines.CoroutineScope
190 import kotlinx.coroutines.Dispatchers
191 import kotlinx.coroutines.launch
192 import kotlinx.coroutines.withContext
194 import java.io.ByteArrayInputStream
195 import java.io.ByteArrayOutputStream
197 import java.io.FileInputStream
198 import java.io.FileOutputStream
199 import java.io.IOException
200 import java.io.UnsupportedEncodingException
202 import java.net.MalformedURLException
204 import java.net.URLDecoder
205 import java.net.URLEncoder
207 import java.text.NumberFormat
209 import java.util.ArrayList
210 import java.util.Date
211 import java.util.concurrent.Executors
212 import kotlin.system.exitProcess
214 // Define the public constants
215 const val CURRENT_URL = "current_url"
216 const val DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0
217 const val DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2
218 const val DOMAINS_CUSTOM_USER_AGENT = 12
219 const val SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1
220 const val SETTINGS_CUSTOM_USER_AGENT = 11
221 const val UNRECOGNIZED_USER_AGENT = -1
223 // Define the private class constants.
224 private const val BOOKMARKS_DRAWER_PINNED = "bookmarks_drawer_pinned"
225 private const val PROXY_MODE = "proxy_mode"
226 private const val SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST = "saved_nested_scroll_webview_state_array_list"
227 private const val SAVED_STATE_ARRAY_LIST = "saved_state_array_list"
228 private const val SAVED_TAB_POSITION = "saved_tab_position"
229 private const val TEMPORARY_MHT_FILE = "temporary_mht_file"
231 class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener, FontSizeDialog.UpdateFontSizeListener,
232 NavigationView.OnNavigationItemSelectedListener, OpenDialog.OpenListener, PinnedMismatchDialog.PinnedMismatchListener, PopulateFilterListsCoroutine.PopulateFilterListsListener, SaveDialog.SaveListener,
233 UrlHistoryDialog.NavigateHistoryListener, WebViewTabFragment.NewTabListener {
236 // Define the public static variables.
237 var currentBookmarksFolder = ""
238 val executorService = Executors.newFixedThreadPool(4)!!
239 var orbotStatus = "unknown"
240 val pendingDialogsArrayList = ArrayList<PendingDialogDataClass>()
241 var proxyMode = ProxyHelper.NONE
242 var restartFromBookmarksActivity = false
243 var webViewStateAdapter: WebViewStateAdapter? = null
245 // Declare the public static variables.
246 lateinit var appBarLayout: AppBarLayout
249 // Declare the class variables.
250 private lateinit var appBar: ActionBar
251 private lateinit var checkFilterListHelper: CheckFilterListHelper
252 private lateinit var bookmarksCursorAdapter: CursorAdapter
253 private lateinit var bookmarksListView: ListView
254 private lateinit var bookmarksDrawerPinnedImageView: ImageView
255 private lateinit var bookmarksTitleTextView: TextView
256 private lateinit var coordinatorLayout: CoordinatorLayout
257 private lateinit var cookieManager: CookieManager
258 private lateinit var defaultFontSizeString: String
259 private lateinit var defaultUserAgentName: String
260 private lateinit var defaultWebViewTheme: String
261 private lateinit var domainsSettingsSet: MutableSet<String>
262 private lateinit var drawerLayout: DrawerLayout
263 private lateinit var easyList: ArrayList<List<Array<String>>>
264 private lateinit var easyPrivacy: ArrayList<List<Array<String>>>
265 private lateinit var fanboysAnnoyanceList: ArrayList<List<Array<String>>>
266 private lateinit var fanboysSocialList: ArrayList<List<Array<String>>>
267 private lateinit var fileChooserCallback: ValueCallback<Array<Uri>>
268 private lateinit var finalGrayColorSpan: ForegroundColorSpan
269 private lateinit var findOnPageCountTextView: TextView
270 private lateinit var findOnPageEditText: EditText
271 private lateinit var findOnPageLinearLayout: LinearLayout
272 private lateinit var fullScreenVideoFrameLayout: FrameLayout
273 private lateinit var initialGrayColorSpan: ForegroundColorSpan
274 private lateinit var navigationBackMenuItem: MenuItem
275 private lateinit var navigationForwardMenuItem: MenuItem
276 private lateinit var navigationHistoryMenuItem: MenuItem
277 private lateinit var navigationRequestsMenuItem: MenuItem
278 private lateinit var optionsAddOrEditDomainMenuItem: MenuItem
279 private lateinit var optionsBlockAllThirdPartyRequestsMenuItem: MenuItem
280 private lateinit var optionsClearCookiesMenuItem: MenuItem
281 private lateinit var optionsClearDataMenuItem: MenuItem
282 private lateinit var optionsClearDomStorageMenuItem: MenuItem
283 private lateinit var optionsClearFormDataMenuItem: MenuItem
284 private lateinit var optionsCookiesMenuItem: MenuItem
285 private lateinit var optionsDarkWebViewMenuItem: MenuItem
286 private lateinit var optionsDisplayImagesMenuItem: MenuItem
287 private lateinit var optionsDomStorageMenuItem: MenuItem
288 private lateinit var optionsEasyListMenuItem: MenuItem
289 private lateinit var optionsEasyPrivacyMenuItem: MenuItem
290 private lateinit var optionsFanboysAnnoyanceListMenuItem: MenuItem
291 private lateinit var optionsFanboysSocialBlockingListMenuItem: MenuItem
292 private lateinit var optionsFilterListsMenuItem: MenuItem
293 private lateinit var optionsFontSizeMenuItem: MenuItem
294 private lateinit var optionsPrivacyMenuItem: MenuItem
295 private lateinit var optionsProxyCustomMenuItem: MenuItem
296 private lateinit var optionsProxyI2pMenuItem: MenuItem
297 private lateinit var optionsProxyMenuItem: MenuItem
298 private lateinit var optionsProxyNoneMenuItem: MenuItem
299 private lateinit var optionsProxyTorMenuItem: MenuItem
300 private lateinit var optionsRefreshMenuItem: MenuItem
301 private lateinit var optionsSaveFormDataMenuItem: MenuItem
302 private lateinit var optionsSwipeToRefreshMenuItem: MenuItem
303 private lateinit var optionsUltraListMenuItem: MenuItem
304 private lateinit var optionsUltraPrivacyMenuItem: MenuItem
305 private lateinit var optionsUserAgentChromeOnAndroidMenuItem: MenuItem
306 private lateinit var optionsUserAgentChromeOnWindowsMenuItem: MenuItem
307 private lateinit var optionsUserAgentChromiumOnLinuxMenuItem: MenuItem
308 private lateinit var optionsUserAgentCustomMenuItem: MenuItem
309 private lateinit var optionsUserAgentEdgeOnWindowsMenuItem: MenuItem
310 private lateinit var optionsUserAgentFirefoxOnAndroidMenuItem: MenuItem
311 private lateinit var optionsUserAgentFirefoxOnLinuxMenuItem: MenuItem
312 private lateinit var optionsUserAgentFirefoxOnWindowsMenuItem: MenuItem
313 private lateinit var optionsUserAgentInternetExplorerOnWindowsMenuItem: MenuItem
314 private lateinit var optionsUserAgentMenuItem: MenuItem
315 private lateinit var optionsUserAgentPrivacyBrowserMenuItem: MenuItem
316 private lateinit var optionsUserAgentSafariOnIosMenuItem: MenuItem
317 private lateinit var optionsUserAgentSafariOnMacosMenuItem: MenuItem
318 private lateinit var optionsUserAgentWebViewDefaultMenuItem: MenuItem
319 private lateinit var optionsWideViewportMenuItem: MenuItem
320 private lateinit var proxyHelper: ProxyHelper
321 private lateinit var redColorSpan: ForegroundColorSpan
322 private lateinit var rootFrameLayout: FrameLayout
323 private lateinit var saveUrlString: String
324 private lateinit var searchURL: String
325 private lateinit var sharedPreferences: SharedPreferences
326 private lateinit var swipeRefreshLayout: SwipeRefreshLayout
327 private lateinit var tabLayout: TabLayout
328 private lateinit var tabsLinearLayout: LinearLayout
329 private lateinit var toolbar: Toolbar
330 private lateinit var webViewDefaultUserAgent: String
331 private lateinit var webViewThemeEntryValuesStringArray: Array<String>
332 private lateinit var webViewViewPager2: ViewPager2
333 private lateinit var ultraList: ArrayList<List<Array<String>>>
334 private lateinit var urlEditText: EditText
335 private lateinit var urlRelativeLayout: RelativeLayout
336 private lateinit var userAgentDataArray: Array<String>
337 private lateinit var userAgentNamesArray: ArrayAdapter<CharSequence>
339 // Define the class variables.
340 private var actionBarDrawerToggle: ActionBarDrawerToggle? = null
341 private var appBarHeight = 0
342 private var bookmarksCursor: Cursor? = null
343 private var bookmarksDatabaseHelper: BookmarksDatabaseHelper? = null
344 private var bookmarksDrawerPinned = false
345 private var bottomAppBar = false
346 private var currentWebView: NestedScrollWebView? = null
347 private var defaultBlockAllThirdPartyRequests = false
348 private var defaultCookies = false
349 private var defaultDisplayWebpageImages = true
350 private var defaultDomStorage = false
351 private var defaultEasyList = true
352 private var defaultEasyPrivacy = true
353 private var defaultFanboysAnnoyanceList = true
354 private var defaultFanboysSocialBlockingList = true
355 private var defaultFormData = false // Form data can be removed once the minimum API >= 26.
356 private var defaultProgressViewEndOffset = 0
357 private var defaultProgressViewStartOffset = 0
358 private var defaultJavaScript = false
359 private var defaultSwipeToRefresh = true
360 private var defaultUltraList = true
361 private var defaultUltraPrivacy = true
362 private var defaultWideViewport = true
363 private var displayAdditionalAppBarIcons = false
364 private var displayingFullScreenVideo = false
365 private var domainsDatabaseHelper: DomainsDatabaseHelper? = null
366 private var downloadWithExternalApp = false
367 private var fullScreenBrowsingModeEnabled = false
368 private var hideAppBar = false
369 private var inFullScreenBrowsingMode = false
370 private var incognitoModeEnabled = false
371 private var loadingNewIntent = false
372 private var objectAnimator = ObjectAnimator()
373 private var optionsMenu: Menu? = null
374 private var orbotStatusBroadcastReceiver: BroadcastReceiver? = null
375 private var reapplyAppSettingsOnRestart = false
376 private var reapplyDomainSettingsOnRestart = false
377 private var sanitizeAmpRedirects = false
378 private var sanitizeTrackingQueries = false
379 private var savedProxyMode: String? = null
380 private var savedNestedScrollWebViewStateArrayList: ArrayList<Bundle>? = null
381 private var savedStateArrayList: ArrayList<Bundle>? = null
382 private var savedTabPosition = 0
383 private var scrollAppBar = false
384 private var ultraPrivacy: ArrayList<List<Array<String>>>? = null
385 private var waitingForProxy = false
387 // Define the save webpage image activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
388 private val browseFileUploadActivityResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { activityResult ->
389 // Pass the file to the WebView.
390 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(activityResult.resultCode, activityResult.data))
393 // Define the save URL activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
394 private val saveUrlActivityResultLauncher = registerForActivityResult<String, Uri>(ActivityResultContracts.CreateDocument("*/*")) { fileUri ->
395 // Only save the URL if the file URI is not null, which happens if the user exited the file picker by pressing back.
396 if (fileUri != null) {
397 // Instantiate the save URL coroutine.
398 val saveUrlCoroutine = SaveUrlCoroutine()
401 saveUrlCoroutine.save(this, this, saveUrlString, fileUri, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
404 // Reset the save URL string.
408 // Define the save webpage archive activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
409 private val saveWebpageArchiveActivityResultLauncher = registerForActivityResult<String, Uri>(ActivityResultContracts.CreateDocument("multipart/related")) { fileUri ->
410 // Only save the webpage archive if the file URI is not null, which happens if the user exited the file picker by pressing back.
411 if (fileUri != null) {
412 // Initialize the file name string from the file URI last path segment.
413 var fileNameString = fileUri.lastPathSegment
415 // Query the exact file name if the API >= 26.
416 if (Build.VERSION.SDK_INT >= 26) {
417 // Get a cursor from the content resolver.
418 val contentResolverCursor = contentResolver.query(fileUri, null, null, null)!!
420 // Move to the fist row.
421 contentResolverCursor.moveToFirst()
423 // Get the file name from the cursor.
424 fileNameString = contentResolverCursor.getString(contentResolverCursor.getColumnIndexOrThrow(OpenableColumns.DISPLAY_NAME))
427 contentResolverCursor.close()
430 // Use a coroutine to save the file.
431 CoroutineScope(Dispatchers.Main).launch {
433 // Create the file on the IO thread.
434 withContext(Dispatchers.IO) {
435 // Create a temporary MHT file.
436 val temporaryMhtFile = File.createTempFile(TEMPORARY_MHT_FILE, ".mht", cacheDir)
438 // The WebView must be accessed from the main thread.
439 withContext(Dispatchers.Main) {
440 currentWebView!!.saveWebArchive(temporaryMhtFile.toString(), false) { callbackValue ->
441 if (callbackValue != null) { // The temporary MHT file was saved successfully.
443 // Create a temporary MHT file input stream.
444 val temporaryMhtFileInputStream = FileInputStream(temporaryMhtFile)
446 // Get an output stream for the save webpage file path.
447 val mhtOutputStream = contentResolver.openOutputStream(fileUri)!!
449 // Create a transfer byte array.
450 val transferByteArray = ByteArray(1024)
452 // Create an integer to track the number of bytes read.
455 // Copy the temporary MHT file input stream to the MHT output stream.
456 while (temporaryMhtFileInputStream.read(transferByteArray).also { bytesRead = it } > 0)
457 mhtOutputStream.write(transferByteArray, 0, bytesRead)
459 // Close the streams.
460 mhtOutputStream.close()
461 temporaryMhtFileInputStream.close()
463 // Display a snackbar.
464 Snackbar.make(currentWebView!!, getString(R.string.saved, fileNameString), Snackbar.LENGTH_SHORT).show()
465 } catch (exception: Exception) {
466 // Display snackbar with the exception.
467 Snackbar.make(currentWebView!!, getString(R.string.error_saving_file, fileNameString, exception), Snackbar.LENGTH_INDEFINITE).show()
469 // Delete the temporary MHT file.
470 temporaryMhtFile.delete()
472 } else { // There was an unspecified error while saving the temporary MHT file.
473 // Display a snackbar.
474 Snackbar.make(currentWebView!!, getString(R.string.error_saving_file, fileNameString, getString(R.string.unknown_error)), Snackbar.LENGTH_INDEFINITE).show()
479 } catch (ioException: IOException) {
480 // Display a snackbar with the IO exception.
481 Snackbar.make(currentWebView!!, getString(R.string.error_saving_file, fileNameString, ioException), Snackbar.LENGTH_INDEFINITE).show()
487 // Define the save webpage image activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
488 private val saveWebpageImageActivityResultLauncher = registerForActivityResult<String, Uri>(ActivityResultContracts.CreateDocument("image/png")) { fileUri ->
489 // Only save the webpage image if the file URI is not null, which happens if the user exited the file picker by pressing back.
490 if (fileUri != null) {
491 // Instantiate the save webpage image coroutine.
492 val saveWebpageImageCoroutine = SaveWebpageImageCoroutine()
494 // Save the webpage image.
495 saveWebpageImageCoroutine.save(this, fileUri, currentWebView!!)
499 override fun onCreate(savedInstanceState: Bundle?) {
500 // Run the default commands.
501 super.onCreate(savedInstanceState)
503 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
504 PreferenceManager.setDefaultValues(this, R.xml.preferences, false)
506 // Get a handle for the shared preferences.
507 sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
509 // Get the preferences.
510 val appTheme = sharedPreferences.getString(getString(R.string.app_theme_key), getString(R.string.app_theme_default_value))
511 val allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false)
512 bottomAppBar = sharedPreferences.getBoolean(getString(R.string.bottom_app_bar_key), false)
513 displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false)
515 // Get the theme entry values string array.
516 val appThemeEntryValuesStringArray = resources.getStringArray(R.array.app_theme_entry_values)
518 // Get the current theme status.
519 val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
521 // 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.
522 if (appTheme == appThemeEntryValuesStringArray[1]) { // The light theme is selected.
523 // Apply the light theme.
524 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
525 } else if (appTheme == appThemeEntryValuesStringArray[2]) { // The dark theme is selected.
526 // Apply the dark theme.
527 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
528 } else { // The system default theme is selected.
529 if (Build.VERSION.SDK_INT >= 28) { // The system default theme is supported.
530 // Follow the system default theme.
531 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
532 } else { // The system default theme is not supported.
533 // Follow the battery saver mode.
534 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY)
538 // Do not continue if the app theme is different than the OS theme. The app always initially starts in the OS theme.
539 // 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.
540 // 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.
541 // See https://redmine.stoutner.com/issues/952.
542 if ((appTheme == appThemeEntryValuesStringArray[0]) || // The system default theme is used.
543 ((appTheme == appThemeEntryValuesStringArray[1]) && (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO)) || // The app is running in day theme as desired.
544 ((appTheme == appThemeEntryValuesStringArray[2]) && (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES))) { // The app is running in night theme as desired.
546 // Disable screenshots if not allowed.
547 if (!allowScreenshots) {
548 window.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
551 // Check to see if the activity has been restarted.
552 if (savedInstanceState != null) {
553 // Store the saved instance state variables. The deprecated `getParcelableArrayList` can be upgraded once the minimum API >= 33.
554 bookmarksDrawerPinned = savedInstanceState.getBoolean(BOOKMARKS_DRAWER_PINNED)
555 @Suppress("DEPRECATION")
556 savedStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_STATE_ARRAY_LIST)
557 @Suppress("DEPRECATION")
558 savedNestedScrollWebViewStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST)
559 savedTabPosition = savedInstanceState.getInt(SAVED_TAB_POSITION)
560 savedProxyMode = savedInstanceState.getString(PROXY_MODE)
563 // 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.
564 WebView.enableSlowWholeDocumentDraw()
566 // Set the content view according to the position of the app bar.
568 setContentView(R.layout.main_framelayout_bottom_appbar)
570 setContentView(R.layout.main_framelayout_top_appbar)
572 // Get handles for the views.
573 rootFrameLayout = findViewById(R.id.root_framelayout)
574 drawerLayout = findViewById(R.id.drawerlayout)
575 coordinatorLayout = findViewById(R.id.coordinatorlayout)
576 appBarLayout = findViewById(R.id.appbar_layout)
577 toolbar = findViewById(R.id.toolbar)
578 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout)
579 findOnPageEditText = findViewById(R.id.find_on_page_edittext)
580 findOnPageCountTextView = findViewById(R.id.find_on_page_count_textview)
581 tabsLinearLayout = findViewById(R.id.tabs_linearlayout)
582 tabLayout = findViewById(R.id.tablayout)
583 swipeRefreshLayout = findViewById(R.id.swiperefreshlayout)
584 webViewViewPager2 = findViewById(R.id.webview_viewpager2)
585 val navigationView = findViewById<NavigationView>(R.id.navigationview)
586 bookmarksListView = findViewById(R.id.bookmarks_drawer_listview)
587 bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview)
588 bookmarksDrawerPinnedImageView = findViewById(R.id.bookmarks_drawer_pinned_imageview)
589 fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout)
591 // Get a handle for the navigation menu.
592 val navigationMenu = navigationView.menu
594 // Get handles for the navigation menu items.
595 navigationBackMenuItem = navigationMenu.findItem(R.id.back)
596 navigationForwardMenuItem = navigationMenu.findItem(R.id.forward)
597 navigationHistoryMenuItem = navigationMenu.findItem(R.id.history)
598 navigationRequestsMenuItem = navigationMenu.findItem(R.id.requests)
600 // Listen for touches on the navigation menu.
601 navigationView.setNavigationItemSelectedListener(this)
603 // Set the support action bar.
604 setSupportActionBar(toolbar)
606 // Get a handle for the app bar.
607 appBar = supportActionBar!!
609 // Set the custom app bar layout, which shows the URL text bar.
610 appBar.setCustomView(R.layout.url_app_bar)
612 // Display the custom app bar layout.
613 appBar.displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM
615 // Get handles for the views in the URL app bar.
616 urlRelativeLayout = findViewById(R.id.url_relativelayout)
617 urlEditText = findViewById(R.id.url_edittext)
619 // Create the hamburger icon at the start of the AppBar.
620 actionBarDrawerToggle = ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer)
622 // Initially disable the sliding drawers. They will be enabled once the filter lists are loaded.
623 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
625 // Initially hide the user interface so that only the filter list loading screen is shown (if reloading).
626 drawerLayout.visibility = View.GONE
628 // Initialize the WebView state adapter.
629 webViewStateAdapter = WebViewStateAdapter(this)
631 // Set the pager adapter on the web view pager.
632 webViewViewPager2.adapter = webViewStateAdapter
634 // Store up to 100 tabs in memory.
635 webViewViewPager2.offscreenPageLimit = 100
637 // Disable swiping between pages in the view pager.
638 webViewViewPager2.isUserInputEnabled = false
640 // Get a handle for the cookie manager.
641 cookieManager = CookieManager.getInstance()
643 // Instantiate the helpers.
644 bookmarksDatabaseHelper = BookmarksDatabaseHelper(this)
645 domainsDatabaseHelper = DomainsDatabaseHelper(this)
646 proxyHelper = ProxyHelper()
648 // Update the bookmarks drawer pinned image view.
649 updateBookmarksDrawerPinnedImageView()
651 // Initialize the app.
654 // Apply the app settings from the shared preferences.
657 // Control what the system back command does.
658 val onBackPressedCallback: OnBackPressedCallback = object : OnBackPressedCallback(true) {
659 override fun handleOnBackPressed() {
660 // Process the different back options.
661 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
662 // Close the navigation drawer.
663 drawerLayout.closeDrawer(GravityCompat.START)
664 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)) { // The bookmarks drawer is open.
665 // close the bookmarks drawer.
666 drawerLayout.closeDrawer(GravityCompat.END)
667 } else if (displayingFullScreenVideo) { // A full screen video is shown.
668 // Exit the full screen video.
669 exitFullScreenVideo()
670 // It shouldn't be possible for the currentWebView to be null, but crash logs indicate it sometimes happens.
671 } else if (currentWebView != null && currentWebView!!.canGoBack()) { // There is at least one item in the current WebView history.
672 // Get the current web back forward list.
673 val webBackForwardList = currentWebView!!.copyBackForwardList()
675 // Get the previous entry URL.
676 val previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex - 1).url
678 // Apply the domain settings.
679 applyDomainSettings(currentWebView!!, previousUrl, resetTab = false, reloadWebsite = false, loadUrl = false)
682 currentWebView!!.goBack()
683 } else { // Close the current tab.
684 // A view is required because the method is also called by an XML `onClick`.
690 // Register the on back pressed callback.
691 onBackPressedDispatcher.addCallback(this, onBackPressedCallback)
693 // Instantiate the populate filter lists coroutine.
694 val populateFilterListsCoroutine = PopulateFilterListsCoroutine(this)
696 // Populate the filter lists.
697 populateFilterListsCoroutine.populateFilterLists(this)
701 public override fun onPostCreate(savedInstanceState: Bundle?) {
702 // Run the default commands.
703 super.onPostCreate(savedInstanceState)
705 // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished. This creates the navigation drawer icon.
706 // If the app is restarting to change the app theme the action bar drawer toggle will not yet be populated.
707 actionBarDrawerToggle?.syncState()
710 override fun onNewIntent(intent: Intent) {
711 // Run the default commands.
712 super.onNewIntent(intent)
714 // Get the information from the intent.
715 val intentAction = intent.action
716 val intentUriData = intent.data
717 val intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT)
719 // Determine if this is a web search.
720 val isWebSearch = (intentAction != null) && (intentAction == Intent.ACTION_WEB_SEARCH)
722 // Check to see if the app is being restarted from a saved state.
723 if (ultraPrivacy != null) { // The activity is not being restarted from a saved state.
724 // 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.
725 if ((intentUriData != null) || (intentStringExtra != null) || isWebSearch) {
726 // Exit the full screen video if it is displayed.
727 if (displayingFullScreenVideo) {
728 // Exit full screen video mode.
729 exitFullScreenVideo()
731 // Reload the current WebView. Otherwise, it can display entirely black.
732 currentWebView!!.reload()
736 val url = if (isWebSearch) { // The intent is a web search.
737 // Sanitize the search input and convert it to a search.
738 val encodedSearchString = try {
739 URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8")
740 } catch (exception: UnsupportedEncodingException) {
744 // Add the base search URL.
745 searchURL + encodedSearchString
746 } else { // The intent contains a URL in either the data or an extra.
747 intentUriData?.toString() ?: intentStringExtra
750 // Add a new tab if specified in the preferences.
751 if (sharedPreferences.getBoolean(getString(R.string.open_intents_in_new_tab_key), true)) { // Load the URL in a new tab.
752 // Set the loading new intent flag.
753 loadingNewIntent = true
756 addNewTab(url!!, true)
757 } else { // Load the URL in the current tab.
759 loadUrl(currentWebView!!, url!!)
762 // Close the navigation drawer if it is open.
763 if (drawerLayout.isDrawerVisible(GravityCompat.START))
764 drawerLayout.closeDrawer(GravityCompat.START)
766 // Close the bookmarks drawer if it is open.
767 if (drawerLayout.isDrawerVisible(GravityCompat.END))
768 drawerLayout.closeDrawer(GravityCompat.END)
770 } else { // The app has been restarted.
771 // If the new intent will open a new tab, set the saved tab position to be the size of the saved state array list.
772 // The tab position is 0 based, meaning the at the new tab will be the tab position that is restored.
773 if ((intentUriData != null) || (intentStringExtra != null) || isWebSearch)
774 savedTabPosition = savedStateArrayList!!.size
776 // Replace the intent that started the app with this one. This will load the tab after the others have been restored.
781 public override fun onRestart() {
782 // Run the default commands.
785 // Apply the app settings if returning from the Settings activity.
786 if (reapplyAppSettingsOnRestart) {
787 // Reset the reapply app settings on restart flag.
788 reapplyAppSettingsOnRestart = false
790 // Apply the app settings.
794 // Apply the domain settings if returning from the settings or domains activity.
795 if (reapplyDomainSettingsOnRestart) {
796 // Reset the reapply domain settings on restart flag.
797 reapplyDomainSettingsOnRestart = false
799 // Update the domains settings set.
800 updateDomainsSettingsSet()
802 // Reapply the domain settings for each tab.
803 for (i in 0 until webViewStateAdapter!!.itemCount) {
804 // Get the WebView tab fragment.
805 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
807 // Get the fragment view.
808 val fragmentView = webViewTabFragment.view
810 // Only reload the WebViews if they exist.
811 if (fragmentView != null) {
812 // Get the nested scroll WebView from the tab fragment.
813 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
815 // Reset the current domain name so the domain settings will be reapplied.
816 nestedScrollWebView.currentDomainName = ""
818 // Reapply the domain settings if the URL is not null, which happens for empty tabs when returning from settings.
819 if (nestedScrollWebView.url != null)
820 applyDomainSettings(nestedScrollWebView, nestedScrollWebView.url, resetTab = false, reloadWebsite = true, loadUrl = false)
825 // Update the bookmarks drawer if returning from the Bookmarks activity.
826 if (restartFromBookmarksActivity) {
827 // Reset the restart from bookmarks activity flag.
828 restartFromBookmarksActivity = false
830 // Close the bookmarks drawer.
831 drawerLayout.closeDrawer(GravityCompat.END)
833 // Reload the bookmarks drawer.
834 loadBookmarksFolder()
837 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
838 updatePrivacyIcons(true)
841 // `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.
842 public override fun onStart() {
843 // Run the default commands.
846 // 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.
847 if (webViewStateAdapter != null) {
848 for (i in 0 until webViewStateAdapter!!.itemCount) {
849 // Get the WebView tab fragment.
850 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
852 // Get the fragment view.
853 val fragmentView = webViewTabFragment.view
855 // Only resume the WebViews if they exist (they won't when the app is first created).
856 if (fragmentView != null) {
857 // Get the nested scroll WebView from the tab fragment.
858 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
860 // Resume the nested scroll WebView.
861 nestedScrollWebView.onResume()
866 // Resume the nested scroll WebView JavaScript timers. This is a global command that resumes JavaScript timers on all WebViews.
867 if (currentWebView != null)
868 currentWebView!!.resumeTimers()
870 // Reapply the proxy settings if the system is using a proxy. This redisplays the appropriate alert dialog.
871 if (proxyMode != ProxyHelper.NONE)
874 // Reapply any system UI flags.
875 if (displayingFullScreenVideo || inFullScreenBrowsingMode) { // The system is displaying a website or a video in full screen mode.
876 /* Hide the system bars.
877 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
878 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
879 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
880 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
883 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
884 @Suppress("DEPRECATION")
885 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
888 // Show any pending dialogs.
889 for (i in pendingDialogsArrayList.indices) {
890 // Get the pending dialog from the array list.
891 val (dialogFragment, tag) = pendingDialogsArrayList[i]
893 // Show the pending dialog.
894 dialogFragment.show(supportFragmentManager, tag)
897 // Clear the pending dialogs array list.
898 pendingDialogsArrayList.clear()
901 public override fun onSaveInstanceState(savedInstanceState: Bundle) {
902 // Run the default commands.
903 super.onSaveInstanceState(savedInstanceState)
905 // 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.
906 if (webViewStateAdapter != null) {
907 // Initialize the saved state array lists.
908 savedStateArrayList = ArrayList<Bundle>()
909 savedNestedScrollWebViewStateArrayList = ArrayList<Bundle>()
911 // Get the URLs from each tab.
912 for (i in 0 until webViewStateAdapter!!.itemCount) {
913 // Get the WebView tab fragment.
914 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
916 // Get the fragment view.
917 val fragmentView = webViewTabFragment.view
919 // Save the fragment state if it is not null.
920 if (fragmentView != null) {
921 // Get the nested scroll WebView from the tab fragment.
922 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
924 // Create the saved state bundle.
925 val savedStateBundle = Bundle()
927 // Get the current states.
928 nestedScrollWebView.saveState(savedStateBundle)
929 val savedNestedScrollWebViewStateBundle = nestedScrollWebView.saveNestedScrollWebViewState()
931 // Store the saved states in the array lists.
932 savedStateArrayList!!.add(savedStateBundle)
933 savedNestedScrollWebViewStateArrayList!!.add(savedNestedScrollWebViewStateBundle)
937 // Get the current tab position.
938 val currentTabPosition = tabLayout.selectedTabPosition
940 // Store the saved states in the bundle.
941 savedInstanceState.putBoolean(BOOKMARKS_DRAWER_PINNED, bookmarksDrawerPinned)
942 savedInstanceState.putString(PROXY_MODE, proxyMode)
943 savedInstanceState.putParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST, savedNestedScrollWebViewStateArrayList)
944 savedInstanceState.putParcelableArrayList(SAVED_STATE_ARRAY_LIST, savedStateArrayList)
945 savedInstanceState.putInt(SAVED_TAB_POSITION, currentTabPosition)
949 // `onStop()` runs after `onPause()`. It is used instead of `onPause()` so the commands are not called every time the screen is partially hidden.
950 public override fun onStop() {
951 // Run the default commands.
954 // 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.
955 if (webViewStateAdapter != null) {
956 // Pause each web view.
957 for (i in 0 until webViewStateAdapter!!.itemCount) {
958 // Get the WebView tab fragment.
959 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
961 // Get the fragment view.
962 val fragmentView = webViewTabFragment.view
964 // Only pause the WebViews if they exist (they won't when the app is first created).
965 if (fragmentView != null) {
966 // Get the nested scroll WebView from the tab fragment.
967 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
969 // Pause the nested scroll WebView.
970 nestedScrollWebView.onPause()
975 // Pause the WebView JavaScript timers. This is a global command that pauses JavaScript on all WebViews.
976 if (currentWebView != null)
977 currentWebView!!.pauseTimers()
980 public override fun onDestroy() {
981 // Unregister the orbot status broadcast receiver if it exists.
982 if (orbotStatusBroadcastReceiver != null) {
983 unregisterReceiver(orbotStatusBroadcastReceiver)
986 // Close the bookmarks cursor if it exists.
987 bookmarksCursor?.close()
989 // Close the databases if they exist.
990 bookmarksDatabaseHelper?.close()
991 domainsDatabaseHelper?.close()
993 // Run the default commands.
997 override fun onCreateOptionsMenu(menu: Menu): Boolean {
998 // Inflate the menu. This adds items to the app bar if it is present.
999 menuInflater.inflate(R.menu.webview_options_menu, menu)
1001 // Get handles for the menu items.
1002 optionsPrivacyMenuItem = menu.findItem(R.id.javascript)
1003 optionsRefreshMenuItem = menu.findItem(R.id.refresh)
1004 val optionsBookmarksMenuItem = menu.findItem(R.id.bookmarks)
1005 optionsCookiesMenuItem = menu.findItem(R.id.cookies)
1006 optionsDomStorageMenuItem = menu.findItem(R.id.dom_storage)
1007 optionsSaveFormDataMenuItem = menu.findItem(R.id.save_form_data) // Form data can be removed once the minimum API >= 26.
1008 optionsClearDataMenuItem = menu.findItem(R.id.clear_data)
1009 optionsClearCookiesMenuItem = menu.findItem(R.id.clear_cookies)
1010 optionsClearDomStorageMenuItem = menu.findItem(R.id.clear_dom_storage)
1011 optionsClearFormDataMenuItem = menu.findItem(R.id.clear_form_data) // Form data can be removed once the minimum API >= 26.
1012 optionsEasyListMenuItem = menu.findItem(R.id.easylist)
1013 optionsEasyPrivacyMenuItem = menu.findItem(R.id.easyprivacy)
1014 optionsFanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list)
1015 optionsFanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list)
1016 optionsFilterListsMenuItem = menu.findItem(R.id.filterlists)
1017 optionsUltraListMenuItem = menu.findItem(R.id.ultralist)
1018 optionsUltraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy)
1019 optionsBlockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests)
1020 optionsProxyMenuItem = menu.findItem(R.id.proxy)
1021 optionsProxyNoneMenuItem = menu.findItem(R.id.proxy_none)
1022 optionsProxyTorMenuItem = menu.findItem(R.id.proxy_tor)
1023 optionsProxyI2pMenuItem = menu.findItem(R.id.proxy_i2p)
1024 optionsProxyCustomMenuItem = menu.findItem(R.id.proxy_custom)
1025 optionsUserAgentMenuItem = menu.findItem(R.id.user_agent)
1026 optionsUserAgentPrivacyBrowserMenuItem = menu.findItem(R.id.user_agent_privacy_browser)
1027 optionsUserAgentWebViewDefaultMenuItem = menu.findItem(R.id.user_agent_webview_default)
1028 optionsUserAgentFirefoxOnAndroidMenuItem = menu.findItem(R.id.user_agent_firefox_on_android)
1029 optionsUserAgentChromeOnAndroidMenuItem = menu.findItem(R.id.user_agent_chrome_on_android)
1030 optionsUserAgentSafariOnIosMenuItem = menu.findItem(R.id.user_agent_safari_on_ios)
1031 optionsUserAgentFirefoxOnLinuxMenuItem = menu.findItem(R.id.user_agent_firefox_on_linux)
1032 optionsUserAgentChromiumOnLinuxMenuItem = menu.findItem(R.id.user_agent_chromium_on_linux)
1033 optionsUserAgentFirefoxOnWindowsMenuItem = menu.findItem(R.id.user_agent_firefox_on_windows)
1034 optionsUserAgentChromeOnWindowsMenuItem = menu.findItem(R.id.user_agent_chrome_on_windows)
1035 optionsUserAgentEdgeOnWindowsMenuItem = menu.findItem(R.id.user_agent_edge_on_windows)
1036 optionsUserAgentInternetExplorerOnWindowsMenuItem = menu.findItem(R.id.user_agent_internet_explorer_on_windows)
1037 optionsUserAgentSafariOnMacosMenuItem = menu.findItem(R.id.user_agent_safari_on_macos)
1038 optionsUserAgentCustomMenuItem = menu.findItem(R.id.user_agent_custom)
1039 optionsSwipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh)
1040 optionsWideViewportMenuItem = menu.findItem(R.id.wide_viewport)
1041 optionsDisplayImagesMenuItem = menu.findItem(R.id.display_images)
1042 optionsDarkWebViewMenuItem = menu.findItem(R.id.dark_webview)
1043 optionsFontSizeMenuItem = menu.findItem(R.id.font_size)
1044 optionsAddOrEditDomainMenuItem = menu.findItem(R.id.add_or_edit_domain)
1046 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1047 updatePrivacyIcons(false)
1049 // Only display the form data menu items if the API < 26.
1050 optionsSaveFormDataMenuItem.isVisible = Build.VERSION.SDK_INT < 26
1051 optionsClearFormDataMenuItem.isVisible = Build.VERSION.SDK_INT < 26
1053 // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
1054 optionsClearFormDataMenuItem.isEnabled = Build.VERSION.SDK_INT < 26
1056 // Only display the dark WebView menu item if the API >= 29.
1057 optionsDarkWebViewMenuItem.isVisible = Build.VERSION.SDK_INT >= 29
1059 // 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.
1060 if (displayAdditionalAppBarIcons) { // Display the additional icons.
1061 optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
1062 optionsBookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM)
1063 optionsCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM)
1064 } else { //Do not display the additional icons.
1065 optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER)
1066 optionsBookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER)
1067 optionsCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER)
1070 // Replace `Refresh` with `Stop` if a URL is already loading.
1071 if ((currentWebView != null) && (currentWebView!!.progress != 100)) {
1073 optionsRefreshMenuItem.setTitle(R.string.stop)
1075 // 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.
1076 if (displayAdditionalAppBarIcons)
1077 optionsRefreshMenuItem.setIcon(R.drawable.close_blue)
1080 // Store a handle for the options menu.
1087 override fun onPrepareOptionsMenu(menu: Menu): Boolean {
1088 // Initialize the current user agent string and the font size.
1089 var currentUserAgent = getString(R.string.user_agent_privacy_browser)
1092 // 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.
1093 if (currentWebView != null) {
1094 // Set the add or edit domain text.
1095 if (currentWebView!!.domainSettingsApplied)
1096 optionsAddOrEditDomainMenuItem.setTitle(R.string.edit_domain_settings)
1098 optionsAddOrEditDomainMenuItem.setTitle(R.string.add_domain_settings)
1100 // Get the current user agent from the WebView.
1101 currentUserAgent = currentWebView!!.settings.userAgentString
1103 // Get the current font size from the the WebView.
1104 fontSize = currentWebView!!.settings.textZoom
1106 // Set the status of the menu item checkboxes.
1107 optionsDomStorageMenuItem.isChecked = currentWebView!!.settings.domStorageEnabled
1108 @Suppress("DEPRECATION")
1109 optionsSaveFormDataMenuItem.isChecked = currentWebView!!.settings.saveFormData // Form data can be removed once the minimum API >= 26.
1110 optionsEasyListMenuItem.isChecked = currentWebView!!.easyListEnabled
1111 optionsEasyPrivacyMenuItem.isChecked = currentWebView!!.easyPrivacyEnabled
1112 optionsFanboysAnnoyanceListMenuItem.isChecked = currentWebView!!.fanboysAnnoyanceListEnabled
1113 optionsFanboysSocialBlockingListMenuItem.isChecked = currentWebView!!.fanboysSocialBlockingListEnabled
1114 optionsUltraListMenuItem.isChecked = currentWebView!!.ultraListEnabled
1115 optionsUltraPrivacyMenuItem.isChecked = currentWebView!!.ultraPrivacyEnabled
1116 optionsBlockAllThirdPartyRequestsMenuItem.isChecked = currentWebView!!.blockAllThirdPartyRequests
1117 optionsSwipeToRefreshMenuItem.isChecked = currentWebView!!.swipeToRefresh
1118 optionsWideViewportMenuItem.isChecked = currentWebView!!.settings.useWideViewPort
1119 optionsDisplayImagesMenuItem.isChecked = currentWebView!!.settings.loadsImagesAutomatically
1121 // Initialize the display names for the filter lists with the number of blocked requests.
1122 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + currentWebView!!.getRequestsCount(BLOCKED_REQUESTS)
1123 optionsEasyListMenuItem.title = currentWebView!!.getRequestsCount(EASYLIST).toString() + " - " + getString(R.string.easylist)
1124 optionsEasyPrivacyMenuItem.title = currentWebView!!.getRequestsCount(EASYPRIVACY).toString() + " - " + getString(R.string.easyprivacy)
1125 optionsFanboysAnnoyanceListMenuItem.title = currentWebView!!.getRequestsCount(FANBOYS_ANNOYANCE_LIST).toString() + " - " + getString(R.string.fanboys_annoyance_list)
1126 optionsFanboysSocialBlockingListMenuItem.title = currentWebView!!.getRequestsCount(FANBOYS_SOCIAL_BLOCKING_LIST).toString() + " - " + getString(R.string.fanboys_social_blocking_list)
1127 optionsUltraListMenuItem.title = currentWebView!!.getRequestsCount(com.stoutner.privacybrowser.views.ULTRALIST).toString() + " - " + getString(R.string.ultralist)
1128 optionsUltraPrivacyMenuItem.title = currentWebView!!.getRequestsCount(ULTRAPRIVACY).toString() + " - " + getString(R.string.ultraprivacy)
1129 optionsBlockAllThirdPartyRequestsMenuItem.title = currentWebView!!.getRequestsCount(THIRD_PARTY_REQUESTS).toString() + " - " + getString(R.string.block_all_third_party_requests)
1131 // Enable DOM Storage if JavaScript is enabled.
1132 optionsDomStorageMenuItem.isEnabled = currentWebView!!.settings.javaScriptEnabled
1134 // Get the current theme status.
1135 val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
1137 // Enable dark WebView if night mode is enabled.
1138 optionsDarkWebViewMenuItem.isEnabled = (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES)
1140 // Set the checkbox status for dark WebView if the device is running API >= 29 and algorithmic darkening is supported.
1141 if ((Build.VERSION.SDK_INT >= 29) && WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING))
1142 optionsDarkWebViewMenuItem.isChecked = WebSettingsCompat.isAlgorithmicDarkeningAllowed(currentWebView!!.settings)
1145 // Set the cookies menu item checked status.
1146 optionsCookiesMenuItem.isChecked = cookieManager.acceptCookie()
1148 // Enable Clear Cookies if there are any.
1149 optionsClearCookiesMenuItem.isEnabled = cookieManager.hasCookies()
1151 // 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`.
1152 val privateDataDirectoryString = applicationInfo.dataDir
1154 // Get the storage directories.
1155 val localStorageDirectory = File("$privateDataDirectoryString/app_webview/Local Storage/")
1156 val indexedDBDirectory = File("$privateDataDirectoryString/app_webview/IndexedDB")
1158 // Initialize the number of files counters.
1159 var localStorageDirectoryNumberOfFiles = 0
1160 var indexedDBDirectoryNumberOfFiles = 0
1162 // 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.
1163 if (localStorageDirectory.exists())
1164 localStorageDirectoryNumberOfFiles = (localStorageDirectory.list())?.size ?: 0
1166 // Get a count of the number of files in the IndexedDB directory. The list can be null, in which case a `0` is returned.
1167 if (indexedDBDirectory.exists())
1168 indexedDBDirectoryNumberOfFiles = (indexedDBDirectory.list())?.size ?: 0
1170 // Enable Clear DOM Storage if there is any.
1171 optionsClearDomStorageMenuItem.isEnabled = localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0
1173 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
1174 if (Build.VERSION.SDK_INT < 26) {
1175 // Get the WebView database.
1176 val webViewDatabase = WebViewDatabase.getInstance(this)
1178 // Enable the clear form data menu item if there is anything to clear.
1179 @Suppress("DEPRECATION")
1180 optionsClearFormDataMenuItem.isEnabled = webViewDatabase.hasFormData()
1183 // Enable Clear Data if any of the submenu items are enabled.
1184 optionsClearDataMenuItem.isEnabled = (optionsClearCookiesMenuItem.isEnabled || optionsClearDomStorageMenuItem.isEnabled || optionsClearFormDataMenuItem.isEnabled)
1186 // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
1187 optionsFanboysSocialBlockingListMenuItem.isEnabled = !optionsFanboysAnnoyanceListMenuItem.isChecked
1189 // Set the proxy title and check the applied proxy.
1191 ProxyHelper.NONE -> {
1192 // Set the proxy title.
1193 optionsProxyMenuItem.title = getString(R.string.proxy) + " - " + getString(R.string.proxy_none)
1195 // Check the proxy None radio button.
1196 optionsProxyNoneMenuItem.isChecked = true
1199 ProxyHelper.TOR -> {
1200 // Set the proxy title.
1201 optionsProxyMenuItem.title = getString(R.string.proxy) + " - " + getString(R.string.proxy_tor)
1203 // Check the proxy Tor radio button.
1204 optionsProxyTorMenuItem.isChecked = true
1207 ProxyHelper.I2P -> {
1208 // Set the proxy title.
1209 optionsProxyMenuItem.title = getString(R.string.proxy) + " - " + getString(R.string.proxy_i2p)
1211 // Check the proxy I2P radio button.
1212 optionsProxyI2pMenuItem.isChecked = true
1215 ProxyHelper.CUSTOM -> {
1216 // Set the proxy title.
1217 optionsProxyMenuItem.title = getString(R.string.proxy) + " - " + getString(R.string.proxy_custom)
1219 // Check the proxy Custom radio button.
1220 optionsProxyCustomMenuItem.isChecked = true
1224 // Select the current user agent menu item.
1225 when (currentUserAgent) {
1226 resources.getStringArray(R.array.user_agent_data)[0] -> { // Privacy Browser.
1227 // Update the user agent menu item title.
1228 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_privacy_browser)
1230 // Select the Privacy Browser radio box.
1231 optionsUserAgentPrivacyBrowserMenuItem.isChecked = true
1234 webViewDefaultUserAgent -> { // WebView Default.
1235 // Update the user agent menu item title.
1236 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_webview_default)
1238 // Select the WebView Default radio box.
1239 optionsUserAgentWebViewDefaultMenuItem.isChecked = true
1242 resources.getStringArray(R.array.user_agent_data)[2] -> { // Firefox on Android.
1243 // Update the user agent menu item title.
1244 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_android)
1246 // Select the Firefox on Android radio box.
1247 optionsUserAgentFirefoxOnAndroidMenuItem.isChecked = true
1250 resources.getStringArray(R.array.user_agent_data)[3] -> { // Chrome on Android.
1251 // Update the user agent menu item title.
1252 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_android)
1254 // Select the Chrome on Android radio box.
1255 optionsUserAgentChromeOnAndroidMenuItem.isChecked = true
1258 resources.getStringArray(R.array.user_agent_data)[4] -> { // Safari on iOS.
1259 // Update the user agent menu item title.
1260 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_ios)
1262 // Select the Safari on iOS radio box.
1263 optionsUserAgentSafariOnIosMenuItem.isChecked = true
1266 resources.getStringArray(R.array.user_agent_data)[5] -> { // Firefox on Linux.
1267 // Update the user agent menu item title.
1268 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_linux)
1270 // Select the Firefox on Linux radio box.
1271 optionsUserAgentFirefoxOnLinuxMenuItem.isChecked = true
1274 resources.getStringArray(R.array.user_agent_data)[6] -> { // Chromium on Linux.
1275 // Update the user agent menu item title.
1276 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chromium_on_linux)
1278 // Select the Chromium on Linux radio box.
1279 optionsUserAgentChromiumOnLinuxMenuItem.isChecked = true
1282 resources.getStringArray(R.array.user_agent_data)[7] -> { // Firefox on Windows.
1283 // Update the user agent menu item title.
1284 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_windows)
1286 // Select the Firefox on Windows radio box.
1287 optionsUserAgentFirefoxOnWindowsMenuItem.isChecked = true
1290 resources.getStringArray(R.array.user_agent_data)[8] -> { // Chrome on Windows.
1291 // Update the user agent menu item title.
1292 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_windows)
1294 // Select the Chrome on Windows radio box.
1295 optionsUserAgentChromeOnWindowsMenuItem.isChecked = true
1298 resources.getStringArray(R.array.user_agent_data)[9] -> { // Edge on Windows.
1299 // Update the user agent menu item title.
1300 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_edge_on_windows)
1302 // Select the Edge on Windows radio box.
1303 optionsUserAgentEdgeOnWindowsMenuItem.isChecked = true
1306 resources.getStringArray(R.array.user_agent_data)[10] -> { // Internet Explorer on Windows.
1307 // Update the user agent menu item title.
1308 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_internet_explorer_on_windows)
1310 // Select the Internet on Windows radio box.
1311 optionsUserAgentInternetExplorerOnWindowsMenuItem.isChecked = true
1314 resources.getStringArray(R.array.user_agent_data)[11] -> { // Safari on macOS.
1315 // Update the user agent menu item title.
1316 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_macos)
1318 // Select the Safari on macOS radio box.
1319 optionsUserAgentSafariOnMacosMenuItem.isChecked = true
1322 else -> { // Custom user agent.
1323 // Update the user agent menu item title.
1324 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_custom)
1326 // Select the Custom radio box.
1327 optionsUserAgentCustomMenuItem.isChecked = true
1331 // Set the font size title.
1332 optionsFontSizeMenuItem.title = getString(R.string.font_size) + " - " + fontSize + "%"
1334 // Run all the other default commands.
1335 super.onPrepareOptionsMenu(menu)
1337 // Display the menu.
1341 override fun onOptionsItemSelected(menuItem: MenuItem): Boolean {
1342 // Run the commands that correlate to the selected menu item.
1343 return when (menuItem.itemId) {
1344 R.id.javascript -> { // JavaScript.
1345 // Toggle the JavaScript status.
1346 currentWebView!!.settings.javaScriptEnabled = !currentWebView!!.settings.javaScriptEnabled
1348 // Update the privacy icon.
1349 updatePrivacyIcons(true)
1351 // Display a snackbar.
1352 if (currentWebView!!.settings.javaScriptEnabled) // JavaScrip is enabled.
1353 Snackbar.make(webViewViewPager2, R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show()
1354 else if (cookieManager.acceptCookie()) // JavaScript is disabled, but cookies are enabled.
1355 Snackbar.make(webViewViewPager2, R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show()
1356 else // Privacy mode.
1357 Snackbar.make(webViewViewPager2, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show()
1359 // Reload the current WebView.
1360 currentWebView!!.reload()
1362 // Consume the event.
1366 R.id.refresh -> { // Refresh.
1367 // Run the command that correlates to the current status of the menu item.
1368 if (menuItem.title == getString(R.string.refresh)) // The refresh button was pushed.
1369 currentWebView!!.reload()
1370 else // The stop button was pushed.
1371 currentWebView!!.stopLoading()
1373 // Consume the event.
1377 R.id.bookmarks -> { // Bookmarks.
1378 // Open the bookmarks drawer.
1379 drawerLayout.openDrawer(GravityCompat.END)
1381 // Consume the event.
1385 R.id.cookies -> { // Cookies.
1386 // Toggle the cookie status.
1387 cookieManager.setAcceptCookie(!cookieManager.acceptCookie())
1389 // Store the cookie status.
1390 currentWebView!!.acceptCookies = cookieManager.acceptCookie()
1392 // Update the menu checkbox.
1393 menuItem.isChecked = cookieManager.acceptCookie()
1395 // Update the privacy icon.
1396 updatePrivacyIcons(true)
1398 // Display a snackbar.
1399 if (cookieManager.acceptCookie()) // Cookies are enabled.
1400 Snackbar.make(webViewViewPager2, R.string.cookies_enabled, Snackbar.LENGTH_SHORT).show()
1401 else if (currentWebView!!.settings.javaScriptEnabled) // JavaScript is still enabled.
1402 Snackbar.make(webViewViewPager2, R.string.cookies_disabled, Snackbar.LENGTH_SHORT).show()
1403 else // Privacy mode.
1404 Snackbar.make(webViewViewPager2, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show()
1406 // Reload the current WebView.
1407 currentWebView!!.reload()
1409 // Consume the event.
1413 R.id.dom_storage -> { // DOM storage.
1414 // Toggle the DOM storage status.
1415 currentWebView!!.settings.domStorageEnabled = !currentWebView!!.settings.domStorageEnabled
1417 // Update the menu checkbox.
1418 menuItem.isChecked = currentWebView!!.settings.domStorageEnabled
1420 // Update the privacy icon.
1421 updatePrivacyIcons(true)
1423 // Display a snackbar.
1424 if (currentWebView!!.settings.domStorageEnabled)
1425 Snackbar.make(webViewViewPager2, R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show()
1427 Snackbar.make(webViewViewPager2, R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show()
1429 // Reload the current WebView.
1430 currentWebView!!.reload()
1432 // Consume the event.
1436 R.id.save_form_data -> { // Form data. This can be removed once the minimum API >= 26.
1437 // Switch the status of saveFormDataEnabled.
1438 @Suppress("DEPRECATION")
1439 currentWebView!!.settings.saveFormData = !currentWebView!!.settings.saveFormData
1441 // Update the menu checkbox.
1442 @Suppress("DEPRECATION")
1443 menuItem.isChecked = currentWebView!!.settings.saveFormData
1445 // Display a snackbar.
1446 @Suppress("DEPRECATION")
1447 if (currentWebView!!.settings.saveFormData)
1448 Snackbar.make(webViewViewPager2, R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show()
1450 Snackbar.make(webViewViewPager2, R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show()
1452 // Update the privacy icon.
1453 updatePrivacyIcons(true)
1455 // Reload the current WebView.
1456 currentWebView!!.reload()
1458 // Consume the event.
1462 R.id.clear_cookies -> { // Clear cookies.
1463 // Create a snackbar.
1464 Snackbar.make(webViewViewPager2, R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1465 .setAction(R.string.undo) {} // Everything will be handled by `onDismissed()` below.
1466 .addCallback(object : Snackbar.Callback() {
1467 override fun onDismissed(snackbar: Snackbar, event: Int) {
1468 if (event != DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1469 // Delete the cookies.
1470 cookieManager.removeAllCookies(null)
1476 // Consume the event.
1480 R.id.clear_dom_storage -> { // Clear DOM storage.
1481 // Create a snackbar.
1482 Snackbar.make(webViewViewPager2, R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1483 .setAction(R.string.undo) {} // Everything will be handled by `onDismissed()` below.
1484 .addCallback(object : Snackbar.Callback() {
1485 override fun onDismissed(snackbar: Snackbar, event: Int) {
1486 if (event != DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1487 // Get a handle for the web storage.
1488 val webStorage = WebStorage.getInstance()
1490 // Delete the DOM Storage.
1491 webStorage.deleteAllData()
1493 // Initialize a handler to manually delete the DOM storage files and directories.
1494 val deleteDomStorageHandler = Handler(Looper.getMainLooper())
1496 // Setup a runnable to manually delete the DOM storage files and directories.
1497 val deleteDomStorageRunnable = Runnable {
1499 // Get a handle for the runtime.
1500 val runtime = Runtime.getRuntime()
1502 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1503 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1504 val privateDataDirectoryString = applicationInfo.dataDir
1506 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1507 val deleteLocalStorageProcess = runtime.exec(arrayOf("rm", "-rf", "$privateDataDirectoryString/app_webview/Local Storage/"))
1509 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1510 val deleteIndexProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview/IndexedDB")
1511 val deleteQuotaManagerProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/QuotaManager")
1512 val deleteQuotaManagerJournalProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/QuotaManager-journal")
1513 val deleteDatabasesProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview/databases")
1515 // Wait for the processes to finish.
1516 deleteLocalStorageProcess.waitFor()
1517 deleteIndexProcess.waitFor()
1518 deleteQuotaManagerProcess.waitFor()
1519 deleteQuotaManagerJournalProcess.waitFor()
1520 deleteDatabasesProcess.waitFor()
1521 } catch (exception: Exception) {
1522 // Do nothing if an error is thrown.
1526 // Manually delete the DOM storage files after 200 milliseconds.
1527 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200)
1533 // Consume the event.
1537 R.id.clear_form_data -> { // Clear form data. This can be remove once the minimum API >= 26.
1538 // Create a snackbar.
1539 Snackbar.make(webViewViewPager2, R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1540 .setAction(R.string.undo) {} // Everything will be handled by `onDismissed()` below.
1541 .addCallback(object : Snackbar.Callback() {
1542 override fun onDismissed(snackbar: Snackbar, event: Int) {
1543 if (event != DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1544 // Get a handle for the webView database.
1545 val webViewDatabase = WebViewDatabase.getInstance(applicationContext)
1547 // Delete the form data.
1548 @Suppress("DEPRECATION")
1549 webViewDatabase.clearFormData()
1555 // Consume the event.
1559 R.id.easylist -> { // EasyList.
1560 // Toggle the EasyList status.
1561 currentWebView!!.easyListEnabled = !currentWebView!!.easyListEnabled
1563 // Update the menu checkbox.
1564 menuItem.isChecked = currentWebView!!.easyListEnabled
1566 // Reload the current WebView.
1567 currentWebView!!.reload()
1569 // Consume the event.
1573 R.id.easyprivacy -> { // EasyPrivacy.
1574 // Toggle the EasyPrivacy status.
1575 currentWebView!!.easyPrivacyEnabled = !currentWebView!!.easyPrivacyEnabled
1577 // Update the menu checkbox.
1578 menuItem.isChecked = currentWebView!!.easyPrivacyEnabled
1580 // Reload the current WebView.
1581 currentWebView!!.reload()
1583 // Consume the event.
1587 R.id.fanboys_annoyance_list -> { // Fanboy's Annoyance List.
1588 // Toggle Fanboy's Annoyance List status.
1589 currentWebView!!.fanboysAnnoyanceListEnabled = !currentWebView!!.fanboysAnnoyanceListEnabled
1591 // Update the menu checkbox.
1592 menuItem.isChecked = currentWebView!!.fanboysAnnoyanceListEnabled
1594 // Update the status of Fanboy's Social Blocking List.
1595 optionsFanboysSocialBlockingListMenuItem.isEnabled = !currentWebView!!.fanboysAnnoyanceListEnabled
1597 // Reload the current WebView.
1598 currentWebView!!.reload()
1600 // Consume the event.
1604 R.id.fanboys_social_blocking_list -> { // Fanboy's Social Blocking List.
1605 // Toggle Fanboy's Social Blocking List status.
1606 currentWebView!!.fanboysSocialBlockingListEnabled = !currentWebView!!.fanboysSocialBlockingListEnabled
1608 // Update the menu checkbox.
1609 menuItem.isChecked = currentWebView!!.fanboysSocialBlockingListEnabled
1611 // Reload the current WebView.
1612 currentWebView!!.reload()
1614 // Consume the event.
1618 R.id.ultralist -> { // UltraList.
1619 // Toggle the UltraList status.
1620 currentWebView!!.ultraListEnabled = !currentWebView!!.ultraListEnabled
1622 // Update the menu checkbox.
1623 menuItem.isChecked = currentWebView!!.ultraListEnabled
1625 // Reload the current WebView.
1626 currentWebView!!.reload()
1628 // Consume the event.
1632 R.id.ultraprivacy -> { // UltraPrivacy.
1633 // Toggle the UltraPrivacy status.
1634 currentWebView!!.ultraPrivacyEnabled = !currentWebView!!.ultraPrivacyEnabled
1636 // Update the menu checkbox.
1637 menuItem.isChecked = currentWebView!!.ultraPrivacyEnabled
1639 // Reload the current WebView.
1640 currentWebView!!.reload()
1642 // Consume the event.
1646 R.id.block_all_third_party_requests -> { // Block all third-party requests.
1647 //Toggle the third-party requests blocker status.
1648 currentWebView!!.blockAllThirdPartyRequests = !currentWebView!!.blockAllThirdPartyRequests
1650 // Update the menu checkbox.
1651 menuItem.isChecked = currentWebView!!.blockAllThirdPartyRequests
1653 // Reload the current WebView.
1654 currentWebView!!.reload()
1656 // Consume the event.
1660 R.id.proxy_none -> { // Proxy - None.
1661 // Update the proxy mode.
1662 proxyMode = ProxyHelper.NONE
1664 // Apply the proxy mode.
1667 // Consume the event.
1671 R.id.proxy_tor -> { // Proxy - Tor.
1672 // Update the proxy mode.
1673 proxyMode = ProxyHelper.TOR
1675 // Apply the proxy mode.
1678 // Consume the event.
1682 R.id.proxy_i2p -> { // Proxy - I2P.
1683 // Update the proxy mode.
1684 proxyMode = ProxyHelper.I2P
1686 // Apply the proxy mode.
1689 // Consume the event.
1693 R.id.proxy_custom -> { // Proxy - Custom.
1694 // Update the proxy mode.
1695 proxyMode = ProxyHelper.CUSTOM
1697 // Apply the proxy mode.
1700 // Consume the event.
1704 R.id.user_agent_privacy_browser -> { // User Agent - Privacy Browser.
1705 // Update the user agent.
1706 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[0]
1708 // Reload the current WebView.
1709 currentWebView!!.reload()
1711 // Consume the event.
1715 R.id.user_agent_webview_default -> { // User Agent - WebView Default.
1716 // Update the user agent.
1717 currentWebView!!.settings.userAgentString = ""
1719 // Reload the current WebView.
1720 currentWebView!!.reload()
1722 // Consume the event.
1726 R.id.user_agent_firefox_on_android -> { // User Agent - Firefox on Android.
1727 // Update the user agent.
1728 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[2]
1730 // Reload the current WebView.
1731 currentWebView!!.reload()
1733 // Consume the event.
1737 R.id.user_agent_chrome_on_android -> { // User Agent - Chrome on Android.
1738 // Update the user agent.
1739 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[3]
1741 // Reload the current WebView.
1742 currentWebView!!.reload()
1744 // Consume the event.
1748 R.id.user_agent_safari_on_ios -> { // User Agent - Safari on iOS.
1749 // Update the user agent.
1750 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[4]
1752 // Reload the current WebView.
1753 currentWebView!!.reload()
1755 // Consume the event.
1759 R.id.user_agent_firefox_on_linux -> { // User Agent - Firefox on Linux.
1760 // Update the user agent.
1761 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[5]
1763 // Reload the current WebView.
1764 currentWebView!!.reload()
1766 // Consume the event.
1770 R.id.user_agent_chromium_on_linux -> { // User Agent - Chromium on Linux.
1771 // Update the user agent.
1772 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[6]
1774 // Reload the current WebView.
1775 currentWebView!!.reload()
1777 // Consume the event.
1781 R.id.user_agent_firefox_on_windows -> { // User Agent - Firefox on Windows.
1782 // Update the user agent.
1783 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[7]
1785 // Reload the current WebView.
1786 currentWebView!!.reload()
1788 // Consume the event.
1792 R.id.user_agent_chrome_on_windows -> { // User Agent - Chrome on Windows.
1793 // Update the user agent.
1794 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[8]
1796 // Reload the current WebView.
1797 currentWebView!!.reload()
1799 // Consume the event.
1803 R.id.user_agent_edge_on_windows -> { // User Agent - Edge on Windows.
1804 // Update the user agent.
1805 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[9]
1807 // Reload the current WebView.
1808 currentWebView!!.reload()
1810 // Consume the event.
1814 R.id.user_agent_internet_explorer_on_windows -> { // User Agent - Internet Explorer on Windows.
1815 // Update the user agent.
1816 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[10]
1818 // Reload the current WebView.
1819 currentWebView!!.reload()
1821 // Consume the event.
1825 R.id.user_agent_safari_on_macos -> { // User Agent - Safari on macOS.
1826 // Update the user agent.
1827 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[11]
1829 // Reload the current WebView.
1830 currentWebView!!.reload()
1832 // Consume the event.
1836 R.id.user_agent_custom -> { // User Agent - Custom.
1837 // Update the user agent.
1838 currentWebView!!.settings.userAgentString = sharedPreferences.getString(getString(R.string.custom_user_agent_key), getString(R.string.custom_user_agent_default_value))
1840 // Reload the current WebView.
1841 currentWebView!!.reload()
1843 // Consume the event.
1847 R.id.font_size -> { // Font size.
1848 // Instantiate the font size dialog.
1849 val fontSizeDialogFragment: DialogFragment = FontSizeDialog.displayDialog(currentWebView!!.settings.textZoom)
1851 // Show the font size dialog.
1852 fontSizeDialogFragment.show(supportFragmentManager, getString(R.string.font_size))
1854 // Consume the event.
1858 R.id.swipe_to_refresh -> { // Swipe to refresh.
1859 // Toggle the stored status of swipe to refresh.
1860 currentWebView!!.swipeToRefresh = !currentWebView!!.swipeToRefresh
1862 // Update the swipe refresh layout.
1863 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.
1864 swipeRefreshLayout.isEnabled = currentWebView!!.scrollY == 0
1865 else // Swipe to refresh is disabled.
1866 swipeRefreshLayout.isEnabled = false
1868 // Consume the event.
1872 R.id.wide_viewport -> { // Wide viewport.
1873 // Toggle the viewport.
1874 currentWebView!!.settings.useWideViewPort = !currentWebView!!.settings.useWideViewPort
1876 // Consume the event.
1880 R.id.display_images -> { // Display images.
1881 // Toggle the displaying of images.
1882 if (currentWebView!!.settings.loadsImagesAutomatically) { // Images are currently loaded automatically.
1883 // Disable loading of images.
1884 currentWebView!!.settings.loadsImagesAutomatically = false
1886 // Reload the website to remove existing images.
1887 currentWebView!!.reload()
1888 } else { // Images are not currently loaded automatically.
1889 // Enable loading of images. Missing images will be loaded without the need for a reload.
1890 currentWebView!!.settings.loadsImagesAutomatically = true
1893 // Consume the event.
1897 R.id.dark_webview -> { // Dark WebView.
1898 // Toggle dark WebView if supported.
1899 if ((Build.VERSION.SDK_INT >= 29) && WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING))
1900 WebSettingsCompat.setAlgorithmicDarkeningAllowed(currentWebView!!.settings, !WebSettingsCompat.isAlgorithmicDarkeningAllowed(currentWebView!!.settings)
1903 // Consume the event.
1907 R.id.find_on_page -> { // Find on page.
1908 // Set the minimum height of the find on page linear layout to match the toolbar.
1909 findOnPageLinearLayout.minimumHeight = toolbar.height
1911 // Hide the toolbar.
1912 toolbar.visibility = View.GONE
1914 // Show the find on page linear layout.
1915 findOnPageLinearLayout.visibility = View.VISIBLE
1917 // Display the keyboard. The app must wait 200 ms before running the command to work around a bug in Android.
1918 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1919 findOnPageEditText.postDelayed({
1920 // Set the focus on the find on page edit text.
1921 findOnPageEditText.requestFocus()
1923 // Get a handle for the input method manager.
1924 val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
1926 // Display the keyboard. `0` sets no input flags.
1927 inputMethodManager.showSoftInput(findOnPageEditText, 0)
1930 // Consume the event.
1934 R.id.print -> { // Print.
1935 // Get a print manager instance.
1936 val printManager = (getSystemService(PRINT_SERVICE) as PrintManager)
1938 // Create a print document adapter from the current WebView.
1939 val printDocumentAdapter = currentWebView!!.createPrintDocumentAdapter(getString(R.string.print))
1941 // Print the document.
1942 printManager.print(getString(R.string.privacy_browser_webpage), printDocumentAdapter, null)
1944 // Consume the event.
1948 R.id.save_url -> { // Save URL.
1949 // Check the download preference.
1950 if (downloadWithExternalApp) // Download with an external app.
1951 downloadUrlWithExternalApp(currentWebView!!.currentUrl)
1952 else // Handle the download inside of Privacy Browser. The dialog will be displayed once the file size and the content disposition have been acquired.
1953 PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, currentWebView!!.currentUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
1955 // Consume the event.
1959 R.id.save_archive -> {
1960 // Open the file picker with a default file name built from the current domain name.
1961 saveWebpageArchiveActivityResultLauncher.launch(currentWebView!!.currentDomainName + ".mht")
1963 // Consume the event.
1967 R.id.save_image -> { // Save image.
1968 // Open the file picker with a default file name built from the current domain name.
1969 saveWebpageImageActivityResultLauncher.launch(currentWebView!!.currentDomainName + ".png")
1971 // Consume the event.
1975 R.id.add_to_homescreen -> { // Add to homescreen.
1976 // Instantiate the create home screen shortcut dialog.
1977 val createHomeScreenShortcutDialogFragment: DialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView!!.title!!, currentWebView!!.url!!, currentWebView!!.getFavoriteIcon())
1979 // Show the create home screen shortcut dialog.
1980 createHomeScreenShortcutDialogFragment.show(supportFragmentManager, getString(R.string.create_shortcut))
1982 // Consume the event.
1986 R.id.view_source -> { // View source.
1987 // Create an intent to launch the view source activity.
1988 val viewSourceIntent = Intent(this, ViewSourceActivity::class.java)
1990 // Add the variables to the intent.
1991 viewSourceIntent.putExtra(CURRENT_URL, currentWebView!!.url)
1992 viewSourceIntent.putExtra(USER_AGENT, currentWebView!!.settings.userAgentString)
1995 startActivity(viewSourceIntent)
1997 // Consume the event.
2001 R.id.share_message -> { // Share a message.
2002 // Prepare the share string.
2003 val shareString = currentWebView!!.title + " – " + currentWebView!!.url
2005 // Create the share intent.
2006 val shareMessageIntent = Intent(Intent.ACTION_SEND)
2008 // Add the share string to the intent.
2009 shareMessageIntent.putExtra(Intent.EXTRA_TEXT, shareString)
2011 // Set the MIME type.
2012 shareMessageIntent.type = "text/plain"
2014 // Set the intent to open in a new task.
2015 shareMessageIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
2018 startActivity(Intent.createChooser(shareMessageIntent, getString(R.string.share_message)))
2020 // Consume the event.
2024 R.id.share_url -> { // Share URL.
2025 // Create the share intent.
2026 val shareUrlIntent = Intent(Intent.ACTION_SEND)
2028 // Add the URL to the intent.
2029 shareUrlIntent.putExtra(Intent.EXTRA_TEXT, currentWebView!!.url)
2031 // Add the title to the intent.
2032 shareUrlIntent.putExtra(Intent.EXTRA_SUBJECT, currentWebView!!.title)
2034 // Set the MIME type.
2035 shareUrlIntent.type = "text/plain"
2037 // Set the intent to open in a new task.
2038 shareUrlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
2041 startActivity(Intent.createChooser(shareUrlIntent, getString(R.string.share_url)))
2043 // Consume the event.
2047 R.id.open_with_app -> { // Open with app.
2048 // Open the URL with an outside app.
2049 openWithApp(currentWebView!!.url!!)
2051 // Consume the event.
2055 R.id.open_with_browser -> { // Open with browser.
2056 // Open the URL with an outside browser.
2057 openWithBrowser(currentWebView!!.url!!)
2059 // Consume the event.
2063 R.id.add_or_edit_domain -> { // Add or edit domain.
2064 // Reapply the domain settings on returning to `MainWebViewActivity`.
2065 reapplyDomainSettingsOnRestart = true
2067 // Check if domain settings are currently applied.
2068 if (currentWebView!!.domainSettingsApplied) { // Edit the current domain settings.
2069 // Create an intent to launch the domains activity.
2070 val domainsIntent = Intent(this, DomainsActivity::class.java)
2072 // Add the extra information to the intent.
2073 domainsIntent.putExtra(LOAD_DOMAIN, currentWebView!!.domainSettingsDatabaseId)
2074 domainsIntent.putExtra(CLOSE_ON_BACK, true)
2075 domainsIntent.putExtra(CURRENT_URL, currentWebView!!.url)
2076 domainsIntent.putExtra(CURRENT_IP_ADDRESSES, currentWebView!!.currentIpAddresses)
2078 // Get the current certificate.
2079 val sslCertificate = currentWebView!!.certificate
2081 // Check to see if the SSL certificate is populated.
2082 if (sslCertificate != null) {
2083 // Extract the certificate to strings.
2084 val issuedToCName = sslCertificate.issuedTo.cName
2085 val issuedToOName = sslCertificate.issuedTo.oName
2086 val issuedToUName = sslCertificate.issuedTo.uName
2087 val issuedByCName = sslCertificate.issuedBy.cName
2088 val issuedByOName = sslCertificate.issuedBy.oName
2089 val issuedByUName = sslCertificate.issuedBy.uName
2090 val startDateLong = sslCertificate.validNotBeforeDate.time
2091 val endDateLong = sslCertificate.validNotAfterDate.time
2093 // Add the certificate to the intent.
2094 domainsIntent.putExtra(SSL_ISSUED_TO_CNAME, issuedToCName)
2095 domainsIntent.putExtra(SSL_ISSUED_TO_ONAME, issuedToOName)
2096 domainsIntent.putExtra(SSL_ISSUED_TO_UNAME, issuedToUName)
2097 domainsIntent.putExtra(SSL_ISSUED_BY_CNAME, issuedByCName)
2098 domainsIntent.putExtra(SSL_ISSUED_BY_ONAME, issuedByOName)
2099 domainsIntent.putExtra(SSL_ISSUED_BY_UNAME, issuedByUName)
2100 domainsIntent.putExtra(SSL_START_DATE, startDateLong)
2101 domainsIntent.putExtra(SSL_END_DATE, endDateLong)
2105 startActivity(domainsIntent)
2106 } else { // Add a new domain.
2107 // Get the current URI.
2108 val currentUri = Uri.parse(currentWebView!!.url)
2110 // Get the current domain from the URI. Use an empty string if it is null.
2111 val currentDomain = currentUri.host?: ""
2113 // Create the domain and store the database ID.
2114 val newDomainDatabaseId = domainsDatabaseHelper!!.addDomain(currentDomain)
2116 // Create an intent to launch the domains activity.
2117 val domainsIntent = Intent(this, DomainsActivity::class.java)
2119 // Add the extra information to the intent.
2120 domainsIntent.putExtra(LOAD_DOMAIN, newDomainDatabaseId)
2121 domainsIntent.putExtra(CLOSE_ON_BACK, true)
2122 domainsIntent.putExtra(CURRENT_URL, currentWebView!!.url)
2123 domainsIntent.putExtra(CURRENT_IP_ADDRESSES, currentWebView!!.currentIpAddresses)
2125 // Get the current certificate.
2126 val sslCertificate = currentWebView!!.certificate
2128 // Check to see if the SSL certificate is populated.
2129 if (sslCertificate != null) {
2130 // Extract the certificate to strings.
2131 val issuedToCName = sslCertificate.issuedTo.cName
2132 val issuedToOName = sslCertificate.issuedTo.oName
2133 val issuedToUName = sslCertificate.issuedTo.uName
2134 val issuedByCName = sslCertificate.issuedBy.cName
2135 val issuedByOName = sslCertificate.issuedBy.oName
2136 val issuedByUName = sslCertificate.issuedBy.uName
2137 val startDateLong = sslCertificate.validNotBeforeDate.time
2138 val endDateLong = sslCertificate.validNotAfterDate.time
2140 // Add the certificate to the intent.
2141 domainsIntent.putExtra(SSL_ISSUED_TO_CNAME, issuedToCName)
2142 domainsIntent.putExtra(SSL_ISSUED_TO_ONAME, issuedToOName)
2143 domainsIntent.putExtra(SSL_ISSUED_TO_UNAME, issuedToUName)
2144 domainsIntent.putExtra(SSL_ISSUED_BY_CNAME, issuedByCName)
2145 domainsIntent.putExtra(SSL_ISSUED_BY_ONAME, issuedByOName)
2146 domainsIntent.putExtra(SSL_ISSUED_BY_UNAME, issuedByUName)
2147 domainsIntent.putExtra(SSL_START_DATE, startDateLong)
2148 domainsIntent.putExtra(SSL_END_DATE, endDateLong)
2152 startActivity(domainsIntent)
2155 // Consume the event.
2159 else -> { // There is no match with the options menu. Pass the event up to the parent method.
2160 // Don't consume the event.
2161 super.onOptionsItemSelected(menuItem)
2166 override fun onNavigationItemSelected(menuItem: MenuItem): Boolean {
2167 // Run the commands that correspond to the selected menu item.
2168 when (menuItem.itemId) {
2169 R.id.clear_and_exit -> { // Clear and exit.
2170 // Clear and exit Privacy Browser.
2174 R.id.home -> { // Home.
2175 // Load the homepage.
2176 loadUrl(currentWebView!!, sharedPreferences.getString(getString(R.string.homepage_key), getString(R.string.homepage_default_value))!!)
2179 R.id.back -> { // Back.
2180 // Check if the WebView can go back.
2181 if (currentWebView!!.canGoBack()) {
2182 // Get the current web back forward list.
2183 val webBackForwardList = currentWebView!!.copyBackForwardList()
2185 // Get the previous entry URL.
2186 val previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex - 1).url
2188 // Apply the domain settings.
2189 applyDomainSettings(currentWebView!!, previousUrl, resetTab = false, reloadWebsite = false, loadUrl = false)
2191 // Load the previous website in the history.
2192 currentWebView!!.goBack()
2196 R.id.forward -> { // Forward.
2197 // Check if the WebView can go forward.
2198 if (currentWebView!!.canGoForward()) {
2199 // Get the current web back forward list.
2200 val webBackForwardList = currentWebView!!.copyBackForwardList()
2202 // Get the next entry URL.
2203 val nextUrl = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex + 1).url
2205 // Apply the domain settings.
2206 applyDomainSettings(currentWebView!!, nextUrl, resetTab = false, reloadWebsite = false, loadUrl = false)
2208 // Load the next website in the history.
2209 currentWebView!!.goForward()
2213 R.id.history -> { // History.
2214 // Instantiate the URL history dialog.
2215 val urlHistoryDialogFragment: DialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView!!.webViewFragmentId)
2217 // Show the URL history dialog.
2218 urlHistoryDialogFragment.show(supportFragmentManager, getString(R.string.history))
2221 R.id.open -> { // Open.
2222 // Instantiate the open file dialog.
2223 val openDialogFragment: DialogFragment = OpenDialog()
2225 // Show the open file dialog.
2226 openDialogFragment.show(supportFragmentManager, getString(R.string.open))
2229 R.id.requests -> { // Requests.
2230 // Populate the resource requests.
2231 RequestsActivity.resourceRequests = currentWebView!!.getResourceRequests()
2233 // Create an intent to launch the Requests activity.
2234 val requestsIntent = Intent(this, RequestsActivity::class.java)
2236 // Add the block third-party requests status to the intent.
2237 requestsIntent.putExtra(BLOCK_ALL_THIRD_PARTY_REQUESTS, currentWebView!!.blockAllThirdPartyRequests)
2240 startActivity(requestsIntent)
2243 R.id.downloads -> { // Downloads.
2244 // Try the default system download manager.
2246 // Launch the default system Download Manager.
2247 val defaultDownloadManagerIntent = Intent(DownloadManager.ACTION_VIEW_DOWNLOADS)
2249 // Launch as a new task so that the download manager and Privacy Browser show as separate windows in the recent tasks list.
2250 defaultDownloadManagerIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2253 startActivity(defaultDownloadManagerIntent)
2254 } catch (defaultDownloadManagerException: Exception) { // The system download manager is not available.
2255 // Try a generic file manager.
2257 // Create a generic file manager intent.
2258 val genericFileManagerIntent = Intent(Intent.ACTION_VIEW)
2260 // Open the download directory.
2261 genericFileManagerIntent.setDataAndType(Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()), DocumentsContract.Document.MIME_TYPE_DIR)
2263 // Launch as a new task so that the file manager and Privacy Browser show as separate windows in the recent tasks list.
2264 genericFileManagerIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2267 startActivity(genericFileManagerIntent)
2268 } catch (genericFileManagerException: Exception) { // A generic file manager is not available.
2269 // Try an alternate file manager.
2271 // Create an alternate file manager intent.
2272 val alternateFileManagerIntent = Intent(Intent.ACTION_VIEW)
2274 // Open the download directory.
2275 alternateFileManagerIntent.setDataAndType(Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()), "resource/folder")
2277 // Launch as a new task so that the file manager and Privacy Browser show as separate windows in the recent tasks list.
2278 alternateFileManagerIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2280 // Open the alternate file manager.
2281 startActivity(alternateFileManagerIntent)
2282 } catch (alternateFileManagerException: Exception) {
2283 // Display a snackbar.
2284 Snackbar.make(currentWebView!!, R.string.no_file_manager_detected, Snackbar.LENGTH_INDEFINITE).show()
2290 R.id.domains -> { // Domains.
2291 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2292 reapplyDomainSettingsOnRestart = true
2294 // Create a domains activity intent.
2295 val domainsIntent = Intent(this, DomainsActivity::class.java)
2297 // Add the extra information to the intent.
2298 domainsIntent.putExtra(CURRENT_URL, currentWebView!!.url)
2299 domainsIntent.putExtra(CURRENT_IP_ADDRESSES, currentWebView!!.currentIpAddresses)
2301 // Get the current certificate.
2302 val sslCertificate = currentWebView!!.certificate
2304 // Check to see if the SSL certificate is populated.
2305 if (sslCertificate != null) {
2306 // Extract the certificate to strings.
2307 val issuedToCName = sslCertificate.issuedTo.cName
2308 val issuedToOName = sslCertificate.issuedTo.oName
2309 val issuedToUName = sslCertificate.issuedTo.uName
2310 val issuedByCName = sslCertificate.issuedBy.cName
2311 val issuedByOName = sslCertificate.issuedBy.oName
2312 val issuedByUName = sslCertificate.issuedBy.uName
2313 val startDateLong = sslCertificate.validNotBeforeDate.time
2314 val endDateLong = sslCertificate.validNotAfterDate.time
2316 // Add the certificate to the intent.
2317 domainsIntent.putExtra(SSL_ISSUED_TO_CNAME, issuedToCName)
2318 domainsIntent.putExtra(SSL_ISSUED_TO_ONAME, issuedToOName)
2319 domainsIntent.putExtra(SSL_ISSUED_TO_UNAME, issuedToUName)
2320 domainsIntent.putExtra(SSL_ISSUED_BY_CNAME, issuedByCName)
2321 domainsIntent.putExtra(SSL_ISSUED_BY_ONAME, issuedByOName)
2322 domainsIntent.putExtra(SSL_ISSUED_BY_UNAME, issuedByUName)
2323 domainsIntent.putExtra(SSL_START_DATE, startDateLong)
2324 domainsIntent.putExtra(SSL_END_DATE, endDateLong)
2328 startActivity(domainsIntent)
2331 R.id.settings -> { // Settings.
2332 // Set the reapply on restart flags.
2333 reapplyAppSettingsOnRestart = true
2334 reapplyDomainSettingsOnRestart = true
2336 // Create a settings intent.
2337 val settingsIntent = Intent(this, SettingsActivity::class.java)
2340 startActivity(settingsIntent)
2343 R.id.import_export -> { // Import/Export.
2344 // Create an intent to launch the import/export activity.
2345 val importExportIntent = Intent(this, ImportExportActivity::class.java)
2348 startActivity(importExportIntent)
2351 R.id.logcat -> { // Logcat.
2352 // Create an intent to launch the logcat activity.
2353 val logcatIntent = Intent(this, LogcatActivity::class.java)
2356 startActivity(logcatIntent)
2359 R.id.webview_devtools -> { // WebView DevTools.
2360 // Create a WebView DevTools intent.
2361 val webViewDevToolsIntent = Intent("com.android.webview.SHOW_DEV_UI")
2363 // Launch as a new task so that the WebView DevTools and Privacy Browser show as a separate windows in the recent tasks list.
2364 webViewDevToolsIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2367 startActivity(webViewDevToolsIntent)
2370 R.id.guide -> { // Guide.
2371 // Create an intent to launch the guide activity.
2372 val guideIntent = Intent(this, GuideActivity::class.java)
2375 startActivity(guideIntent)
2378 R.id.about -> { // About
2379 // Create an intent to launch the about activity.
2380 val aboutIntent = Intent(this, AboutActivity::class.java)
2382 // Create a string array for the filter list versions.
2383 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])
2385 // Add the filter list versions to the intent.
2386 aboutIntent.putExtra(FILTERLIST_VERSIONS, filterListVersions)
2389 startActivity(aboutIntent)
2393 // Close the navigation drawer.
2394 drawerLayout.closeDrawer(GravityCompat.START)
2400 override fun onCreateContextMenu(contextMenu: ContextMenu, view: View, contextMenuInfo: ContextMenu.ContextMenuInfo?) {
2401 // Get the hit test result.
2402 val hitTestResult = currentWebView!!.hitTestResult
2404 // Define the URL strings.
2405 val imageUrl: String?
2406 val linkUrl: String?
2408 // Get a handle for the clipboard manager.
2409 val clipboardManager = (getSystemService(CLIPBOARD_SERVICE) as ClipboardManager)
2411 // Process the link according to the type.
2412 when (hitTestResult.type) {
2413 // `SRC_ANCHOR_TYPE` is a link.
2414 WebView.HitTestResult.SRC_ANCHOR_TYPE -> {
2415 // Get the target URL.
2416 linkUrl = hitTestResult.extra!!
2418 // Set the target URL as the context menu title.
2419 contextMenu.setHeaderTitle(linkUrl)
2421 // Add an open in new tab entry.
2422 contextMenu.add(R.string.open_in_new_tab).setOnMenuItemClickListener {
2423 // Load the link URL in a new tab and move to it.
2424 addNewTab(linkUrl, true)
2426 // Consume the event.
2430 // Add an open in background entry.
2431 contextMenu.add(R.string.open_in_background).setOnMenuItemClickListener {
2432 // Load the link URL in a new tab but do not move to it.
2433 addNewTab(linkUrl, false)
2435 // Consume the event.
2439 // Add an open with app entry.
2440 contextMenu.add(R.string.open_with_app).setOnMenuItemClickListener {
2441 // Open the URL with another app.
2442 openWithApp(linkUrl)
2444 // Consume the event.
2448 // Add an open with browser entry.
2449 contextMenu.add(R.string.open_with_browser).setOnMenuItemClickListener {
2450 // Open the URL with another browser.
2451 openWithBrowser(linkUrl)
2453 // Consume the event.
2457 // Add a copy URL entry.
2458 contextMenu.add(R.string.copy_url).setOnMenuItemClickListener {
2459 // Save the link URL in a clip data.
2460 val srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl)
2462 // Set the clip data as the clipboard's primary clip.
2463 clipboardManager.setPrimaryClip(srcAnchorTypeClipData)
2465 // Consume the event.
2469 // Add a Save URL entry.
2470 contextMenu.add(R.string.save_url).setOnMenuItemClickListener {
2471 // Check the download preference.
2472 if (downloadWithExternalApp) // Download with an external app.
2473 downloadUrlWithExternalApp(linkUrl)
2474 else // Handle the download inside of Privacy Browser. The dialog will be displayed once the file size and the content disposition have been acquired.
2475 PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, linkUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
2477 // Consume the event.
2481 // Add an empty cancel entry, which by default closes the context menu.
2482 contextMenu.add(R.string.cancel)
2485 // `IMAGE_TYPE` is an image.
2486 WebView.HitTestResult.IMAGE_TYPE -> {
2487 // Get the image URL.
2488 imageUrl = hitTestResult.extra!!
2490 // Set the context menu title.
2491 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.
2492 contextMenu.setHeaderTitle(imageUrl.substring(0, 100))
2493 else // The image URL does not contain the full image data. Set the image URL as the title of the context menu.
2494 contextMenu.setHeaderTitle(imageUrl)
2496 // Add an open in new tab entry.
2497 contextMenu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener {
2498 // Load the image in a new tab.
2499 addNewTab(imageUrl, true)
2501 // Consume the event.
2505 // Add an open with app entry.
2506 contextMenu.add(R.string.open_with_app).setOnMenuItemClickListener {
2507 // Open the image URL with an external app.
2508 openWithApp(imageUrl)
2510 // Consume the event.
2514 // Add an open with browser entry.
2515 contextMenu.add(R.string.open_with_browser).setOnMenuItemClickListener {
2516 // Open the image URL with an external browser.
2517 openWithBrowser(imageUrl)
2519 // Consume the event.
2523 // Add a view image entry.
2524 contextMenu.add(R.string.view_image).setOnMenuItemClickListener {
2525 // Load the image in the current tab.
2526 loadUrl(currentWebView!!, imageUrl)
2528 // Consume the event.
2532 // Add a save image entry.
2533 contextMenu.add(R.string.save_image).setOnMenuItemClickListener {
2534 // Check the download preference.
2535 if (downloadWithExternalApp) { // Download with an external app.
2536 downloadUrlWithExternalApp(imageUrl)
2537 } else { // Handle the download inside of Privacy Browser. The dialog will be displayed once the file size and the content disposition have been acquired.
2538 PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, imageUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
2541 // Consume the event.
2545 // Add a copy URL entry.
2546 contextMenu.add(R.string.copy_url).setOnMenuItemClickListener {
2547 // Save the image URL in a clip data.
2548 val imageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl)
2550 // Set the clip data as the clipboard's primary clip.
2551 clipboardManager.setPrimaryClip(imageTypeClipData)
2553 // Consume the event.
2557 // Add an empty cancel entry, which by default closes the context menu.
2558 contextMenu.add(R.string.cancel)
2561 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2562 WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE -> {
2563 // Get the image URL.
2564 imageUrl = hitTestResult.extra!!
2566 // Instantiate a handler.
2567 val handler = Handler(Looper.getMainLooper())
2569 // Get a handle for the handler message.
2570 val message = handler.obtainMessage()
2572 // Request the image details from the last touched node be returned in the message.
2573 currentWebView!!.requestFocusNodeHref(message)
2575 // Get the link URL from the message data.
2576 linkUrl = message.data.getString("url")!!
2578 // Set the link URL as the title of the context menu.
2579 contextMenu.setHeaderTitle(linkUrl)
2581 // Add an open in new tab entry.
2582 contextMenu.add(R.string.open_in_new_tab).setOnMenuItemClickListener {
2583 // Load the link URL in a new tab and move to it.
2584 addNewTab(linkUrl, true)
2586 // Consume the event.
2590 // Add an open in background entry.
2591 contextMenu.add(R.string.open_in_background).setOnMenuItemClickListener {
2592 // Lod the link URL in a new tab but do not move to it.
2593 addNewTab(linkUrl, false)
2595 // Consume the event.
2599 // Add an open image in new tab entry.
2600 contextMenu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener {
2601 // Load the image in a new tab and move to it.
2602 addNewTab(imageUrl, true)
2604 // Consume the event.
2608 // Add an open with app entry.
2609 contextMenu.add(R.string.open_with_app).setOnMenuItemClickListener {
2610 // Open the link URL with an external app.
2611 openWithApp(linkUrl)
2613 // Consume the event.
2617 // Add an open with browser entry.
2618 contextMenu.add(R.string.open_with_browser).setOnMenuItemClickListener {
2619 // Open the link URL with an external browser.
2620 openWithBrowser(linkUrl)
2622 // Consume the event.
2626 // Add a view image entry.
2627 contextMenu.add(R.string.view_image).setOnMenuItemClickListener {
2628 // View the image in the current tab.
2629 loadUrl(currentWebView!!, imageUrl)
2631 // Consume the event.
2635 // Add a Save Image entry.
2636 contextMenu.add(R.string.save_image).setOnMenuItemClickListener {
2637 // Check the download preference.
2638 if (downloadWithExternalApp) // Download with an external app.
2639 downloadUrlWithExternalApp(imageUrl)
2640 else // Handle the download inside of Privacy Browser. The dialog will be displayed once the file size and the content disposition have been acquired.
2641 PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, imageUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
2643 // Consume the event.
2647 // Add a copy URL entry.
2648 contextMenu.add(R.string.copy_url).setOnMenuItemClickListener {
2649 // Save the link URL in a clip data.
2650 val srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl)
2652 // Set the clip data as the clipboard's primary clip.
2653 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData)
2655 // Consume the event.
2659 // Add a save URL entry.
2660 contextMenu.add(R.string.save_url).setOnMenuItemClickListener {
2661 // Check the download preference.
2662 if (downloadWithExternalApp) // Download with an external app.
2663 downloadUrlWithExternalApp(linkUrl)
2664 else // Handle the download inside of Privacy Browser. The dialog will be displayed once the file size and the content disposition have been acquired.
2665 PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, linkUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
2667 // Consume the event.
2671 // Add an empty cancel entry, which by default closes the context menu.
2672 contextMenu.add(R.string.cancel)
2675 WebView.HitTestResult.EMAIL_TYPE -> {
2676 // Get the target URL.
2677 linkUrl = hitTestResult.extra
2679 // Set the target URL as the title of the context menu.
2680 contextMenu.setHeaderTitle(linkUrl)
2682 // Add a write email entry.
2683 contextMenu.add(R.string.write_email).setOnMenuItemClickListener {
2684 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2685 val emailIntent = Intent(Intent.ACTION_SENDTO)
2687 // Parse the url and set it as the data for the intent.
2688 emailIntent.data = Uri.parse("mailto:$linkUrl")
2690 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2691 emailIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2695 startActivity(emailIntent)
2696 } catch (exception: ActivityNotFoundException) {
2697 // Display a snackbar.
2698 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
2701 // Consume the event.
2705 // Add a copy email address entry.
2706 contextMenu.add(R.string.copy_email_address).setOnMenuItemClickListener {
2707 // Save the email address in a clip data.
2708 val srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl)
2710 // Set the clip data as the clipboard's primary clip.
2711 clipboardManager.setPrimaryClip(srcEmailTypeClipData)
2713 // Consume the event.
2717 // Add an empty cancel entry, which by default closes the context menu.
2718 contextMenu.add(R.string.cancel)
2723 // The view parameter cannot be removed because it is called from the layout onClick.
2724 fun addTab(@Suppress("UNUSED_PARAMETER")view: View?) {
2725 // Add a new tab with a blank URL.
2729 private fun addNewTab(urlString: String, moveToTab: Boolean) {
2730 // Clear the focus from the URL edit text, so that it will be populated with the information from the new tab.
2731 urlEditText.clearFocus()
2733 // Get the new page number. The page numbers are 0 indexed, so the new page number will match the current count.
2734 val newTabNumber = tabLayout.tabCount
2737 tabLayout.addTab(tabLayout.newTab())
2740 val newTab = tabLayout.getTabAt(newTabNumber)!!
2742 // Set a custom view on the new tab.
2743 newTab.setCustomView(R.layout.tab_custom_view)
2745 // Add the new WebView page.
2746 webViewStateAdapter!!.addPage(newTabNumber, webViewViewPager2, urlString, moveToTab)
2748 // Show the app bar if it is at the bottom of the screen and the new tab is taking focus.
2749 if (bottomAppBar && moveToTab && appBarLayout.translationY != 0f) {
2750 // Animate the bottom app bar onto the screen.
2751 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0f)
2754 objectAnimator.start()
2758 private fun applyAppSettings() {
2759 // 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.
2760 defaultJavaScript = sharedPreferences.getBoolean(getString(R.string.javascript_key), false)
2761 defaultCookies = sharedPreferences.getBoolean(getString(R.string.cookies_key), false)
2762 defaultDomStorage = sharedPreferences.getBoolean(getString(R.string.dom_storage_key), false)
2763 defaultFormData = sharedPreferences.getBoolean(getString(R.string.save_form_data_key), false) // Form data can be removed once the minimum API >= 26.
2764 defaultEasyList = sharedPreferences.getBoolean(getString(R.string.easylist_key), true)
2765 defaultEasyPrivacy = sharedPreferences.getBoolean(getString(R.string.easyprivacy_key), true)
2766 defaultFanboysAnnoyanceList = sharedPreferences.getBoolean(getString(R.string.fanboys_annoyance_list_key), true)
2767 defaultFanboysSocialBlockingList = sharedPreferences.getBoolean(getString(R.string.fanboys_social_blocking_list_key), true)
2768 defaultUltraList = sharedPreferences.getBoolean(getString(R.string.ultralist_key), true)
2769 defaultUltraPrivacy = sharedPreferences.getBoolean(getString(R.string.ultraprivacy_key), true)
2770 defaultBlockAllThirdPartyRequests = sharedPreferences.getBoolean(getString(R.string.block_all_third_party_requests_key), false)
2771 defaultFontSizeString = sharedPreferences.getString(getString(R.string.font_size_key), getString(R.string.font_size_default_value))!!
2772 defaultUserAgentName = sharedPreferences.getString(getString(R.string.user_agent_key), getString(R.string.user_agent_default_value))!!
2773 defaultSwipeToRefresh = sharedPreferences.getBoolean(getString(R.string.swipe_to_refresh_key), true)
2774 defaultWebViewTheme = sharedPreferences.getString(getString(R.string.webview_theme_key), getString(R.string.webview_theme_default_value))!!
2775 defaultWideViewport = sharedPreferences.getBoolean(getString(R.string.wide_viewport_key), true)
2776 defaultDisplayWebpageImages = sharedPreferences.getBoolean(getString(R.string.display_webpage_images_key), true)
2778 // 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.
2779 webViewThemeEntryValuesStringArray = resources.getStringArray(R.array.webview_theme_entry_values)
2781 // 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.
2782 userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item)
2783 userAgentDataArray = resources.getStringArray(R.array.user_agent_data)
2785 // Store the values from the shared preferences in variables.
2786 incognitoModeEnabled = sharedPreferences.getBoolean(getString(R.string.incognito_mode_key), false)
2787 sanitizeTrackingQueries = sharedPreferences.getBoolean(getString(R.string.tracking_queries_key), true)
2788 sanitizeAmpRedirects = sharedPreferences.getBoolean(getString(R.string.amp_redirects_key), true)
2789 proxyMode = sharedPreferences.getString(getString(R.string.proxy_key), getString(R.string.proxy_default_value))!!
2790 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean(getString(R.string.full_screen_browsing_mode_key), false)
2791 hideAppBar = sharedPreferences.getBoolean(getString(R.string.hide_app_bar_key), true)
2792 downloadWithExternalApp = sharedPreferences.getBoolean(getString(R.string.download_with_external_app_key), false)
2793 scrollAppBar = sharedPreferences.getBoolean(getString(R.string.scroll_app_bar_key), true)
2795 // Apply the saved proxy mode if the app has been restarted.
2796 if (savedProxyMode != null) {
2797 // Apply the saved proxy mode.
2798 proxyMode = savedProxyMode!!
2800 // Reset the saved proxy mode.
2801 savedProxyMode = null
2804 // Get the search string.
2805 val searchString = sharedPreferences.getString(getString(R.string.search_key), getString(R.string.search_default_value))!!
2807 // Set the search string, using the custom search URL if specified.
2808 searchURL = if (searchString == getString(R.string.custom_url_item))
2809 sharedPreferences.getString(getString(R.string.search_custom_url_key), getString(R.string.search_custom_url_default_value))!!
2816 // Adjust the layout and scrolling parameters according to the position of the app bar.
2817 if (bottomAppBar) { // The app bar is on the bottom.
2819 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) { // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
2820 // Reset the WebView padding to fill the available space.
2821 swipeRefreshLayout.setPadding(0, 0, 0, 0)
2822 } else { // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
2823 // Move the WebView above the app bar layout.
2824 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
2826 // Show the app bar if it is scrolled off the screen.
2827 if (appBarLayout.translationY != 0f) {
2828 // Animate the bottom app bar onto the screen.
2829 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0f)
2832 objectAnimator.start()
2835 } else { // The app bar is on the top.
2836 // Get the current layout parameters. Using coordinator layout parameters allows the `setBehavior()` command and using app bar layout parameters allows the `setScrollFlags()` command.
2837 val swipeRefreshLayoutParams = swipeRefreshLayout.layoutParams as CoordinatorLayout.LayoutParams
2838 val toolbarLayoutParams = toolbar.layoutParams as AppBarLayout.LayoutParams
2839 val findOnPageLayoutParams = findOnPageLinearLayout.layoutParams as AppBarLayout.LayoutParams
2840 val tabsLayoutParams = tabsLinearLayout.layoutParams as AppBarLayout.LayoutParams
2842 // Add the scrolling behavior to the layout parameters.
2844 // Enable scrolling of the app bar.
2845 swipeRefreshLayoutParams.behavior = AppBarLayout.ScrollingViewBehavior()
2846 toolbarLayoutParams.scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS or AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP
2847 findOnPageLayoutParams.scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS or AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP
2848 tabsLayoutParams.scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS or AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP
2850 // Disable scrolling of the app bar.
2851 swipeRefreshLayoutParams.behavior = null
2852 toolbarLayoutParams.scrollFlags = 0
2853 findOnPageLayoutParams.scrollFlags = 0
2854 tabsLayoutParams.scrollFlags = 0
2856 // Expand the app bar if it is currently collapsed.
2857 appBarLayout.setExpanded(true)
2860 // Set the app bar scrolling for each WebView.
2861 for (i in 0 until webViewStateAdapter!!.itemCount) {
2862 // Get the WebView tab fragment.
2863 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
2865 // Get the fragment view.
2866 val fragmentView = webViewTabFragment.view
2868 // Only modify the WebViews if they exist.
2869 if (fragmentView != null) {
2870 // Get the nested scroll WebView from the tab fragment.
2871 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
2873 // Set the app bar scrolling.
2874 nestedScrollWebView.isNestedScrollingEnabled = scrollAppBar
2879 // Update the full screen browsing mode settings.
2880 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
2881 // Update the visibility of the app bar, which might have changed in the settings.
2883 // Hide the tab linear layout.
2884 tabsLinearLayout.visibility = View.GONE
2886 // Hide the app bar.
2889 // Show the tab linear layout.
2890 tabsLinearLayout.visibility = View.VISIBLE
2892 // Show the app bar.
2896 /* Hide the system bars.
2897 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2898 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
2899 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2900 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
2903 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
2904 @Suppress("DEPRECATION")
2905 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
2906 } else { // Privacy Browser is not in full screen browsing mode.
2907 // 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.
2908 inFullScreenBrowsingMode = false
2910 // Show the tab linear layout.
2911 tabsLinearLayout.visibility = View.VISIBLE
2913 // Show the app bar.
2916 // Remove the `SYSTEM_UI` flags from the root frame layout. The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
2917 @Suppress("DEPRECATION")
2918 rootFrameLayout.systemUiVisibility = 0
2922 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
2923 @SuppressLint("SetJavaScriptEnabled")
2924 private fun applyDomainSettings(nestedScrollWebView: NestedScrollWebView, url: String?, resetTab: Boolean, reloadWebsite: Boolean, loadUrl: Boolean) {
2925 // Store the current URL.
2926 nestedScrollWebView.currentUrl = url!!
2928 // Parse the URL into a URI.
2929 val uri = Uri.parse(url)
2931 // Extract the domain from the URI.
2932 var newHostName = uri.host
2934 // Strings don't like to be null.
2935 if (newHostName == null)
2938 // 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.
2939 if ((nestedScrollWebView.currentDomainName != newHostName) || (newHostName == "")) { // A new domain is being loaded.
2940 // Set the new host name as the current domain name.
2941 nestedScrollWebView.currentDomainName = newHostName
2943 // Reset the ignoring of pinned domain information.
2944 nestedScrollWebView.ignorePinnedDomainInformation = false
2946 // Clear any pinned SSL certificate or IP addresses.
2947 nestedScrollWebView.clearPinnedSslCertificate()
2948 nestedScrollWebView.pinnedIpAddresses = ""
2950 // Reset the favorite icon if specified.
2952 // Initialize the favorite icon.
2953 nestedScrollWebView.initializeFavoriteIcon()
2955 // Get the current page position.
2956 val currentPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
2958 // Get the corresponding tab.
2959 val tab = tabLayout.getTabAt(currentPagePosition)
2961 // Update the tab if it isn't null, which sometimes happens when restarting from the background.
2963 // Get the tab custom view.
2964 val tabCustomView = tab.customView!!
2966 // Get the tab views.
2967 val tabFavoriteIconImageView = tabCustomView.findViewById<ImageView>(R.id.favorite_icon_imageview)
2968 val tabTitleTextView = tabCustomView.findViewById<TextView>(R.id.title_textview)
2970 // Set the default favorite icon as the favorite icon for this tab.
2971 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nestedScrollWebView.getFavoriteIcon(), 64, 64, true))
2973 // Set the loading title text.
2974 tabTitleTextView.setText(R.string.loading)
2978 // Initialize the domain name in database variable.
2979 var domainNameInDatabase: String? = null
2981 // Check the hostname against the domain settings set.
2982 if (domainsSettingsSet.contains(newHostName)) { // The hostname is contained in the domain settings set.
2983 // Record the domain name in the database.
2984 domainNameInDatabase = newHostName
2986 // Set the domain settings applied tracker to true.
2987 nestedScrollWebView.domainSettingsApplied = true
2988 } else { // The hostname is not contained in the domain settings set.
2989 // Set the domain settings applied tracker to false.
2990 nestedScrollWebView.domainSettingsApplied = false
2993 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
2994 while (!nestedScrollWebView.domainSettingsApplied && newHostName!!.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the hostname.
2995 if (domainsSettingsSet.contains("*.$newHostName")) { // Check the host name prepended by `*.`.
2996 // Set the domain settings applied tracker to true.
2997 nestedScrollWebView.domainSettingsApplied = true
2999 // Store the applied domain names as it appears in the database.
3000 domainNameInDatabase = "*.$newHostName"
3003 // Strip out the lowest subdomain of of the host name.
3004 newHostName = newHostName.substring(newHostName.indexOf(".") + 1)
3007 // Apply either the domain settings or the default settings.
3008 if (nestedScrollWebView.domainSettingsApplied) { // The url has custom domain settings.
3009 // Get a cursor for the current host.
3010 val currentDomainSettingsCursor = domainsDatabaseHelper!!.getCursorForDomainName(domainNameInDatabase!!)
3012 // Move to the first position.
3013 currentDomainSettingsCursor.moveToFirst()
3015 // Get the settings from the cursor.
3016 nestedScrollWebView.domainSettingsDatabaseId = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ID))
3017 val javaScriptInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_JAVASCRIPT))
3018 val cookiesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(COOKIES))
3019 val domStorageInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_DOM_STORAGE))
3020 val formDataInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_FORM_DATA)) // Form data can be removed once the minimum API >= 26.
3021 val easyListInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_EASYLIST))
3022 val easyPrivacyInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_EASYPRIVACY))
3023 val fanboysAnnoyanceListInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_FANBOYS_ANNOYANCE_LIST))
3024 val fanboysSocialBlockingListInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST))
3025 val ultraListInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.ULTRALIST))
3026 val ultraPrivacyInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_ULTRAPRIVACY))
3027 val blockAllThirdPartyRequestsInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.BLOCK_ALL_THIRD_PARTY_REQUESTS))
3028 val userAgentName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.USER_AGENT))
3029 val fontSize = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(FONT_SIZE))
3030 val swipeToRefreshInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(SWIPE_TO_REFRESH))
3031 val webViewThemeInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(WEBVIEW_THEME))
3032 val wideViewportInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(WIDE_VIEWPORT))
3033 val displayWebpageImagesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DISPLAY_IMAGES))
3034 val pinnedSslCertificate = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(PINNED_SSL_CERTIFICATE)) == 1)
3035 val pinnedSslIssuedToCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_TO_COMMON_NAME))
3036 val pinnedSslIssuedToOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_TO_ORGANIZATION))
3037 val pinnedSslIssuedToUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_TO_ORGANIZATIONAL_UNIT))
3038 val pinnedSslIssuedByCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_BY_COMMON_NAME))
3039 val pinnedSslIssuedByOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_BY_ORGANIZATION))
3040 val pinnedSslIssuedByUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_BY_ORGANIZATIONAL_UNIT))
3041 val pinnedSslStartDate = Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.SSL_START_DATE)))
3042 val pinnedSslEndDate = Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.SSL_END_DATE)))
3043 val pinnedIpAddresses = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(PINNED_IP_ADDRESSES)) == 1)
3044 val pinnedHostIpAddresses = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(IP_ADDRESSES))
3046 // Close the current host domain settings cursor.
3047 currentDomainSettingsCursor.close()
3049 // Set the JavaScript status.
3050 when (javaScriptInt) {
3051 SYSTEM_DEFAULT -> nestedScrollWebView.settings.javaScriptEnabled = defaultJavaScript
3052 ENABLED -> nestedScrollWebView.settings.javaScriptEnabled = true
3053 DISABLED -> nestedScrollWebView.settings.javaScriptEnabled = false
3056 // Store the cookies status.
3058 SYSTEM_DEFAULT -> nestedScrollWebView.acceptCookies = defaultCookies
3059 ENABLED -> nestedScrollWebView.acceptCookies = true
3060 DISABLED -> nestedScrollWebView.acceptCookies = false
3063 // Apply the cookies status.
3064 cookieManager.setAcceptCookie(nestedScrollWebView.acceptCookies)
3066 // Set the DOM storage status.
3067 when (domStorageInt) {
3068 SYSTEM_DEFAULT -> nestedScrollWebView.settings.domStorageEnabled = defaultDomStorage
3069 ENABLED -> nestedScrollWebView.settings.domStorageEnabled = true
3070 DISABLED -> nestedScrollWebView.settings.domStorageEnabled = false
3073 // Apply the form data setting if the API < 26.
3074 @Suppress("DEPRECATION")
3075 if (Build.VERSION.SDK_INT < 26) {
3076 // Set the form data status.
3077 when (formDataInt) {
3078 SYSTEM_DEFAULT -> nestedScrollWebView.settings.saveFormData = defaultFormData
3079 ENABLED -> nestedScrollWebView.settings.saveFormData = true
3080 DISABLED -> nestedScrollWebView.settings.saveFormData = false
3084 // Set the EasyList status.
3085 when (easyListInt) {
3086 SYSTEM_DEFAULT -> nestedScrollWebView.easyListEnabled = defaultEasyList
3087 ENABLED -> nestedScrollWebView.easyListEnabled = true
3088 DISABLED -> nestedScrollWebView.easyListEnabled = false
3091 // Set the EasyPrivacy status.
3092 when (easyPrivacyInt) {
3093 SYSTEM_DEFAULT -> nestedScrollWebView.easyPrivacyEnabled = defaultEasyPrivacy
3094 ENABLED -> nestedScrollWebView.easyPrivacyEnabled = true
3095 DISABLED -> nestedScrollWebView.easyPrivacyEnabled = false
3098 // Set the Fanboy's Annoyance List status.
3099 when (fanboysAnnoyanceListInt) {
3100 SYSTEM_DEFAULT -> nestedScrollWebView.fanboysAnnoyanceListEnabled = defaultFanboysAnnoyanceList
3101 ENABLED -> nestedScrollWebView.fanboysAnnoyanceListEnabled = true
3102 DISABLED -> nestedScrollWebView.fanboysAnnoyanceListEnabled = false
3105 // Set the Fanboy's Social Blocking List status.
3106 when (fanboysSocialBlockingListInt) {
3107 SYSTEM_DEFAULT -> nestedScrollWebView.fanboysSocialBlockingListEnabled = defaultFanboysSocialBlockingList
3108 ENABLED -> nestedScrollWebView.fanboysSocialBlockingListEnabled = true
3109 DISABLED -> nestedScrollWebView.fanboysSocialBlockingListEnabled = false
3112 // Set the UltraList status.
3113 when (ultraListInt) {
3114 SYSTEM_DEFAULT -> nestedScrollWebView.ultraListEnabled = defaultUltraList
3115 ENABLED -> nestedScrollWebView.ultraListEnabled = true
3116 DISABLED -> nestedScrollWebView.ultraListEnabled = false
3119 // Set the UltraPrivacy status.
3120 when (ultraPrivacyInt) {
3121 SYSTEM_DEFAULT -> nestedScrollWebView.ultraPrivacyEnabled = defaultUltraPrivacy
3122 ENABLED -> nestedScrollWebView.ultraPrivacyEnabled = true
3123 DISABLED -> nestedScrollWebView.ultraPrivacyEnabled = false
3126 // Set the block all third-party requests status.
3127 when (blockAllThirdPartyRequestsInt) {
3128 SYSTEM_DEFAULT -> nestedScrollWebView.blockAllThirdPartyRequests = defaultBlockAllThirdPartyRequests
3129 ENABLED -> nestedScrollWebView.blockAllThirdPartyRequests = true
3130 DISABLED -> nestedScrollWebView.blockAllThirdPartyRequests = false
3133 // Set the user agent.
3134 if (userAgentName == getString(R.string.system_default_user_agent)) { // Use the system default user agent.
3135 // Set the user agent according to the system default.
3136 when (val defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName)) {
3137 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3138 UNRECOGNIZED_USER_AGENT -> nestedScrollWebView.settings.userAgentString = defaultUserAgentName
3140 // Set the user agent to `""`, which uses the default value.
3141 SETTINGS_WEBVIEW_DEFAULT_USER_AGENT -> nestedScrollWebView.settings.userAgentString = ""
3143 // Set the default custom user agent.
3144 SETTINGS_CUSTOM_USER_AGENT -> nestedScrollWebView.settings.userAgentString =
3145 sharedPreferences.getString(getString(R.string.custom_user_agent_key), getString(R.string.custom_user_agent_default_value))
3147 // Get the user agent string from the user agent data array
3148 else -> nestedScrollWebView.settings.userAgentString = userAgentDataArray[defaultUserAgentArrayPosition]
3150 } else { // Set the user agent according to the stored name.
3151 // Set the user agent.
3152 when (val userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName)) {
3153 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3154 UNRECOGNIZED_USER_AGENT ->
3155 nestedScrollWebView.settings.userAgentString = userAgentName
3157 // Set the user agent to `""`, which uses the default value.
3158 SETTINGS_WEBVIEW_DEFAULT_USER_AGENT ->
3159 nestedScrollWebView.settings.userAgentString = ""
3161 // Get the user agent string from the user agent data array.
3163 nestedScrollWebView.settings.userAgentString = userAgentDataArray[userAgentArrayPosition]
3167 // Apply the font size.
3168 try { // Try the specified font size to see if it is valid.
3169 if (fontSize == 0) { // Apply the default font size.
3170 // Set the font size from the value in the app settings.
3171 nestedScrollWebView.settings.textZoom = defaultFontSizeString.toInt()
3172 } else { // Apply the font size from domain settings.
3173 nestedScrollWebView.settings.textZoom = fontSize
3175 } catch (exception: Exception) { // The specified font size is invalid
3176 // Set the font size to be 100%
3177 nestedScrollWebView.settings.textZoom = 100
3180 // Set swipe to refresh.
3181 when (swipeToRefreshInt) {
3183 // Store the swipe to refresh status in the nested scroll WebView.
3184 nestedScrollWebView.swipeToRefresh = defaultSwipeToRefresh
3186 // Update the swipe refresh layout.
3187 if (defaultSwipeToRefresh) { // Swipe to refresh is enabled.
3188 // 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).
3189 if (currentWebView != null) {
3190 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
3191 swipeRefreshLayout.isEnabled = (currentWebView!!.scrollY == 0)
3193 } else { // Swipe to refresh is disabled.
3194 // Disable the swipe refresh layout.
3195 swipeRefreshLayout.isEnabled = false
3200 // Store the swipe to refresh status in the nested scroll WebView.
3201 nestedScrollWebView.swipeToRefresh = true
3203 // 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).
3204 if (currentWebView != null) {
3205 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
3206 swipeRefreshLayout.isEnabled = (currentWebView!!.scrollY == 0)
3211 // Store the swipe to refresh status in the nested scroll WebView.
3212 nestedScrollWebView.swipeToRefresh = false
3214 // Disable swipe to refresh.
3215 swipeRefreshLayout.isEnabled = false
3219 // Set the WebView theme if device is running API >= 29 and algorithmic darkening is supported.
3220 if ((Build.VERSION.SDK_INT >= 29) && WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {
3221 // Set the WebView theme.
3222 when (webViewThemeInt) {
3223 // Set the WebView theme.
3225 when (defaultWebViewTheme) {
3226 // The light theme is selected. Turn off algorithmic darkening.
3227 webViewThemeEntryValuesStringArray[1] -> WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
3229 // The dark theme is selected. Turn on algorithmic darkening.
3230 webViewThemeEntryValuesStringArray[2] -> WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
3232 // The system default theme is selected.
3234 // Get the current system theme status.
3235 val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
3237 // Set the algorithmic darkening according to the current system theme status.
3238 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, currentThemeStatus == Configuration.UI_MODE_NIGHT_YES)
3242 // Turn off algorithmic darkening.
3243 LIGHT_THEME -> WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
3245 // Turn on algorithmic darkening.
3246 DARK_THEME -> WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
3250 // Set the wide viewport status.
3251 when (wideViewportInt) {
3252 SYSTEM_DEFAULT -> nestedScrollWebView.settings.useWideViewPort = defaultWideViewport
3253 ENABLED -> nestedScrollWebView.settings.useWideViewPort = true
3254 DISABLED -> nestedScrollWebView.settings.useWideViewPort = false
3257 // Set the display webpage images status.
3258 when (displayWebpageImagesInt) {
3259 SYSTEM_DEFAULT -> nestedScrollWebView.settings.loadsImagesAutomatically = defaultDisplayWebpageImages
3260 ENABLED -> nestedScrollWebView.settings.loadsImagesAutomatically = true
3261 DISABLED -> nestedScrollWebView.settings.loadsImagesAutomatically = false
3264 // If there is a pinned SSL certificate, store it in the WebView.
3265 if (pinnedSslCertificate)
3266 nestedScrollWebView.setPinnedSslCertificate(pinnedSslIssuedToCName, pinnedSslIssuedToOName, pinnedSslIssuedToUName, pinnedSslIssuedByCName, pinnedSslIssuedByOName, pinnedSslIssuedByUName,
3267 pinnedSslStartDate, pinnedSslEndDate)
3269 // If there is a pinned IP address, store it in the WebView.
3270 if (pinnedIpAddresses)
3271 nestedScrollWebView.pinnedIpAddresses = pinnedHostIpAddresses
3273 // Set a background on the URL relative layout to indicate that custom domain settings are being used.
3274 urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.drawable.domain_settings_url_background)
3275 } else { // The new URL does not have custom domain settings. Load the defaults.
3276 // Store the values from the shared preferences.
3277 nestedScrollWebView.settings.javaScriptEnabled = defaultJavaScript
3278 nestedScrollWebView.acceptCookies = defaultCookies
3279 nestedScrollWebView.settings.domStorageEnabled = defaultDomStorage
3280 nestedScrollWebView.easyListEnabled = defaultEasyList
3281 nestedScrollWebView.easyPrivacyEnabled = defaultEasyPrivacy
3282 nestedScrollWebView.fanboysAnnoyanceListEnabled = defaultFanboysAnnoyanceList
3283 nestedScrollWebView.fanboysSocialBlockingListEnabled = defaultFanboysSocialBlockingList
3284 nestedScrollWebView.ultraListEnabled = defaultUltraList
3285 nestedScrollWebView.ultraPrivacyEnabled = defaultUltraPrivacy
3286 nestedScrollWebView.blockAllThirdPartyRequests = defaultBlockAllThirdPartyRequests
3288 // Apply the default cookie setting.
3289 cookieManager.setAcceptCookie(nestedScrollWebView.acceptCookies)
3291 // Apply the form data setting if the API < 26.
3292 if (Build.VERSION.SDK_INT < 26)
3293 @Suppress("DEPRECATION")
3294 nestedScrollWebView.settings.saveFormData = defaultFormData
3296 // Apply the default font size setting.
3298 // Try to set the font size from the value in the app settings.
3299 nestedScrollWebView.settings.textZoom = defaultFontSizeString.toInt()
3300 } catch (exception: Exception) {
3301 // If the app settings value is invalid, set the font size to 100%.
3302 nestedScrollWebView.settings.textZoom = 100
3305 // Store the swipe to refresh status in the nested scroll WebView.
3306 nestedScrollWebView.swipeToRefresh = defaultSwipeToRefresh
3308 // Update the swipe refresh layout.
3309 if (defaultSwipeToRefresh) { // Swipe to refresh is enabled.
3310 // 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).
3311 if (currentWebView != null) {
3312 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
3313 swipeRefreshLayout.isEnabled = currentWebView!!.scrollY == 0
3315 } else { // Swipe to refresh is disabled.
3316 // Disable the swipe refresh layout.
3317 swipeRefreshLayout.isEnabled = false
3320 // Reset the domain settings database ID.
3321 nestedScrollWebView.domainSettingsDatabaseId = -1
3323 // Set the user agent.
3324 when (val userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName)) {
3325 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3326 UNRECOGNIZED_USER_AGENT -> nestedScrollWebView.settings.userAgentString = defaultUserAgentName
3328 // Set the user agent to `""`, which uses the default value.
3329 SETTINGS_WEBVIEW_DEFAULT_USER_AGENT -> nestedScrollWebView.settings.userAgentString = ""
3331 // Set the default custom user agent.
3332 SETTINGS_CUSTOM_USER_AGENT -> nestedScrollWebView.settings.userAgentString =
3333 sharedPreferences.getString(getString(R.string.custom_user_agent_key), getString(R.string.custom_user_agent_default_value))
3335 // Get the user agent string from the user agent data array
3336 else -> nestedScrollWebView.settings.userAgentString = userAgentDataArray[userAgentArrayPosition]
3339 // Set the WebView theme if the device is running API >= 29 and algorithmic darkening is supported.
3340 if ((Build.VERSION.SDK_INT >= 29) && WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {
3341 // Set the WebView theme.
3342 when (defaultWebViewTheme) {
3343 // The light theme is selected. Turn off algorithmic darkening.
3344 webViewThemeEntryValuesStringArray[1] -> WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
3346 // The dark theme is selected. Turn on algorithmic darkening.
3347 webViewThemeEntryValuesStringArray[2] -> WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
3349 // The system default theme is selected. Get the current system theme status.
3351 // Get the current theme status.
3352 val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
3354 // Set the algorithmic darkening according to the current system theme status.
3355 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, currentThemeStatus == Configuration.UI_MODE_NIGHT_YES)
3360 // Set the viewport.
3361 nestedScrollWebView.settings.useWideViewPort = defaultWideViewport
3363 // Set the loading of webpage images.
3364 nestedScrollWebView.settings.loadsImagesAutomatically = defaultDisplayWebpageImages
3366 // Set a transparent background on the URL relative layout.
3367 urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.color.transparent)
3370 // Update the privacy icons.
3371 updatePrivacyIcons(true)
3374 // Reload the website if returning from the Domains activity.
3376 nestedScrollWebView.reload()
3378 // 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.
3380 nestedScrollWebView.loadUrl(url)
3383 private fun applyProxy(reloadWebViews: Boolean) {
3384 // Set the proxy according to the mode.
3385 proxyHelper.setProxy(applicationContext, appBarLayout, proxyMode)
3387 // Reset the waiting for proxy tracker.
3388 waitingForProxy = false
3392 ProxyHelper.NONE -> {
3393 // Initialize a color background typed value.
3394 val colorBackgroundTypedValue = TypedValue()
3396 // Get the color background from the theme.
3397 theme.resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true)
3399 // Get the color background int from the typed value.
3400 val colorBackgroundInt = colorBackgroundTypedValue.data
3402 // Set the default app bar layout background.
3403 appBarLayout.setBackgroundColor(colorBackgroundInt)
3406 ProxyHelper.TOR -> {
3407 // Set the app bar background to indicate proxying is enabled.
3408 appBarLayout.setBackgroundResource(R.color.blue_background)
3410 // Check to see if Orbot is installed.
3412 // Get the package manager.
3413 val packageManager = packageManager
3415 // 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.
3416 @Suppress("DEPRECATION")
3417 packageManager.getPackageInfo("org.torproject.android", 0)
3419 // Check to see if the proxy is ready.
3420 if (orbotStatus != ProxyHelper.ORBOT_STATUS_ON) { // Orbot is not ready.
3421 // Set the waiting for proxy status.
3422 waitingForProxy = true
3424 // Show the waiting for proxy dialog if it isn't already displayed.
3425 if (supportFragmentManager.findFragmentByTag(getString(R.string.waiting_for_proxy_dialog)) == null) {
3426 // Get a handle for the waiting for proxy alert dialog.
3427 val waitingForProxyDialogFragment = WaitingForProxyDialog()
3429 // Try to show the dialog. Sometimes the window is not yet active if returning from Settings.
3431 // Show the waiting for proxy alert dialog.
3432 waitingForProxyDialogFragment.show(supportFragmentManager, getString(R.string.waiting_for_proxy_dialog))
3433 } catch (waitingForTorException: Exception) {
3434 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
3435 pendingDialogsArrayList.add(PendingDialogDataClass(waitingForProxyDialogFragment, getString(R.string.waiting_for_proxy_dialog)))
3439 } catch (exception: PackageManager.NameNotFoundException) { // Orbot is not installed.
3440 // Show the Orbot not installed dialog if it is not already displayed.
3441 if (supportFragmentManager.findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
3442 // Get a handle for the Orbot not installed alert dialog.
3443 val orbotNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode)
3445 // Try to show the dialog. Sometimes the window is not yet active if returning from Settings.
3447 // Display the Orbot not installed alert dialog.
3448 orbotNotInstalledDialogFragment.show(supportFragmentManager, getString(R.string.proxy_not_installed_dialog))
3449 } catch (orbotNotInstalledException: Exception) {
3450 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
3451 pendingDialogsArrayList.add(PendingDialogDataClass(orbotNotInstalledDialogFragment, getString(R.string.proxy_not_installed_dialog)))
3457 ProxyHelper.I2P -> {
3458 // Set the app bar background to indicate proxying is enabled.
3459 appBarLayout.setBackgroundResource(R.color.blue_background)
3461 // Check to see if I2P is installed.
3463 // 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.
3464 // The deprecated method must be used until the minimum API >= 33.
3465 @Suppress("DEPRECATION")
3466 packageManager.getPackageInfo("net.i2p.android.router", 0)
3467 } catch (fdroidException: PackageManager.NameNotFoundException) { // The F-Droid flavor is not installed.
3469 // 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.
3470 // The deprecated method must be used until the minimum API >= 33.
3471 @Suppress("DEPRECATION")
3472 packageManager.getPackageInfo("net.i2p.android", 0)
3473 } catch (googlePlayException: PackageManager.NameNotFoundException) { // The Google Play flavor is not installed.
3474 // Sow the I2P not installed dialog if it is not already displayed.
3475 if (supportFragmentManager.findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
3476 // Get a handle for the waiting for proxy alert dialog.
3477 val i2pNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode)
3479 // Try to show the dialog. Sometimes the window is not yet active if returning from Settings.
3481 // Display the I2P not installed alert dialog.
3482 i2pNotInstalledDialogFragment.show(supportFragmentManager, getString(R.string.proxy_not_installed_dialog))
3483 } catch (i2pNotInstalledException: Exception) {
3484 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
3485 pendingDialogsArrayList.add(PendingDialogDataClass(i2pNotInstalledDialogFragment, getString(R.string.proxy_not_installed_dialog)))
3492 ProxyHelper.CUSTOM ->
3493 // Set the app bar background to indicate proxying is enabled.
3494 appBarLayout.setBackgroundResource(R.color.blue_background)
3497 // Reload the WebViews if requested and not waiting for the proxy.
3498 if (reloadWebViews && !waitingForProxy) {
3499 // Reload the WebViews.
3500 for (i in 0 until webViewStateAdapter!!.itemCount) {
3501 // Get the WebView tab fragment.
3502 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
3504 // Get the fragment view.
3505 val fragmentView = webViewTabFragment.view
3507 // Only reload the WebViews if they exist.
3508 if (fragmentView != null) {
3509 // Get the nested scroll WebView from the tab fragment.
3510 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
3512 // Reload the WebView.
3513 nestedScrollWebView.reload()
3519 // The view parameter cannot be removed because it is called from the layout onClick.
3520 fun bookmarksBack(@Suppress("UNUSED_PARAMETER")view: View?) {
3521 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
3522 // close the bookmarks drawer.
3523 drawerLayout.closeDrawer(GravityCompat.END)
3524 } else { // A subfolder is displayed.
3525 // Set the former parent folder as the current folder.
3526 currentBookmarksFolder = bookmarksDatabaseHelper!!.getParentFolderName(currentBookmarksFolder)
3528 // Load the new folder.
3529 loadBookmarksFolder()
3533 private fun clearAndExit() {
3534 // Close the bookmarks cursor if it exists.
3535 bookmarksCursor?.close()
3537 // Close the databases helpers if they exist.
3538 bookmarksDatabaseHelper?.close()
3539 domainsDatabaseHelper?.close()
3541 // Get the status of the clear everything preference.
3542 val clearEverything = sharedPreferences.getBoolean(getString(R.string.clear_everything_key), true)
3544 // Get a handle for the runtime.
3545 val runtime = Runtime.getRuntime()
3547 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
3548 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
3549 val privateDataDirectoryString = applicationInfo.dataDir
3552 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_cookies_key), true)) {
3553 // Ass the cookie manager to delete all the cookies.
3554 cookieManager.removeAllCookies(null)
3556 // Ask the cookie manager to flush the cookie database.
3557 cookieManager.flush()
3559 // Manually delete the cookies database, as the cookie manager sometimes will not flush its changes to disk before system exit is run.
3561 // Two commands must be used because `Runtime.exec()` does not like `*`.
3562 val deleteCookiesProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/Cookies")
3563 val deleteCookiesJournalProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/Cookies-journal")
3565 // Wait until the processes have finished.
3566 deleteCookiesProcess.waitFor()
3567 deleteCookiesJournalProcess.waitFor()
3568 } catch (exception: Exception) {
3569 // Do nothing if an error is thrown.
3573 // Clear DOM storage.
3574 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_dom_storage_key), true)) {
3575 // Ask web storage to clear the DOM storage.
3576 WebStorage.getInstance().deleteAllData()
3578 // Manually delete the DOM storage files and directories, as web storage sometimes will not flush its changes to disk before system exit is run.
3580 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
3581 val deleteLocalStorageProcess = runtime.exec(arrayOf("rm", "-rf", "$privateDataDirectoryString/app_webview/Local Storage/"))
3583 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
3584 val deleteIndexProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview/IndexedDB")
3585 val deleteQuotaManagerProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/QuotaManager")
3586 val deleteQuotaManagerJournalProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/QuotaManager-journal")
3587 val deleteDatabaseProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview/databases")
3589 // Wait until the processes have finished.
3590 deleteLocalStorageProcess.waitFor()
3591 deleteIndexProcess.waitFor()
3592 deleteQuotaManagerProcess.waitFor()
3593 deleteQuotaManagerJournalProcess.waitFor()
3594 deleteDatabaseProcess.waitFor()
3595 } catch (exception: Exception) {
3596 // Do nothing if an error is thrown.
3600 // Clear form data if the API < 26.
3601 if (Build.VERSION.SDK_INT < 26 && (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_form_data_key), true))) {
3602 // Ask the WebView database to clear the form data.
3603 @Suppress("DEPRECATION")
3604 WebViewDatabase.getInstance(this).clearFormData()
3606 // Manually delete the form data database, as the WebView database sometimes will not flush its changes to disk before system exit is run.
3608 // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
3609 val deleteWebDataProcess = runtime.exec(arrayOf("rm", "-f", "$privateDataDirectoryString/app_webview/Web Data"))
3610 val deleteWebDataJournalProcess = runtime.exec(arrayOf("rm", "-f", "$privateDataDirectoryString/app_webview/Web Data-journal"))
3612 // Wait until the processes have finished.
3613 deleteWebDataProcess.waitFor()
3614 deleteWebDataJournalProcess.waitFor()
3615 } catch (exception: Exception) {
3616 // Do nothing if an error is thrown.
3620 // Clear the logcat.
3621 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_logcat_key), true)) {
3623 // Clear the logcat. `-c` clears the logcat. `-b all` clears all the buffers (instead of just crash, main, and system).
3624 val process = Runtime.getRuntime().exec("logcat -b all -c")
3626 // Wait for the process to finish.
3628 } catch (exception: IOException) {
3630 } catch (exception: InterruptedException) {
3636 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_cache_key), true)) {
3637 // Clear the cache from each WebView.
3638 for (i in 0 until webViewStateAdapter!!.itemCount) {
3639 // Get the WebView tab fragment.
3640 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
3642 // Get the WebView fragment view.
3643 val webViewFragmentView = webViewTabFragment.view
3645 // Only clear the cache if the WebView exists.
3646 if (webViewFragmentView != null) {
3647 // Get the nested scroll WebView from the tab fragment.
3648 val nestedScrollWebView = webViewFragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
3650 // Clear the cache for this WebView.
3651 nestedScrollWebView.clearCache(true)
3655 // Manually delete the cache directories.
3657 // Delete the main cache directory.
3658 val deleteCacheProcess = runtime.exec("rm -rf $privateDataDirectoryString/cache")
3660 // Delete the secondary `Service Worker` cache directory.
3661 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
3662 val deleteServiceWorkerProcess = runtime.exec(arrayOf("rm", "-rf", "$privateDataDirectoryString/app_webview/Default/Service Worker/"))
3664 // Wait until the processes have finished.
3665 deleteCacheProcess.waitFor()
3666 deleteServiceWorkerProcess.waitFor()
3667 } catch (exception: Exception) {
3668 // Do nothing if an error is thrown.
3672 // Wipe out each WebView.
3673 for (i in 0 until webViewStateAdapter!!.itemCount) {
3674 // Get the WebView tab fragment.
3675 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
3677 // Get the WebView frame layout.
3678 val webViewFrameLayout = webViewTabFragment.view as FrameLayout?
3680 // Only wipe out the WebView if it exists.
3681 if (webViewFrameLayout != null) {
3682 // Get the nested scroll WebView from the tab fragment.
3683 val nestedScrollWebView = webViewFrameLayout.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
3685 // Clear SSL certificate preferences for this WebView.
3686 nestedScrollWebView.clearSslPreferences()
3688 // Clear the back/forward history for this WebView.
3689 nestedScrollWebView.clearHistory()
3691 // Remove all the views from the frame layout.
3692 webViewFrameLayout.removeAllViews()
3694 // Destroy the internal state of the WebView.
3695 nestedScrollWebView.destroy()
3699 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
3700 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
3701 if (clearEverything) {
3703 // Delete the folder.
3704 val deleteAppWebviewProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview")
3706 // Wait until the process has finished.
3707 deleteAppWebviewProcess.waitFor()
3708 } catch (exception: Exception) {
3709 // Do nothing if an error is thrown.
3713 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
3714 finishAndRemoveTask()
3716 // Remove the terminated program from RAM. The status code is `0`.
3720 // The view parameter cannot be removed because it is called from the layout onClick.
3721 fun closeFindOnPage(@Suppress("UNUSED_PARAMETER")view: View?) {
3722 // Delete the contents of the find on page edit text.
3723 findOnPageEditText.text = null
3725 // Clear the highlighted phrases if the WebView is not null.
3726 currentWebView?.clearMatches()
3728 // Hide the find on page linear layout.
3729 findOnPageLinearLayout.visibility = View.GONE
3731 // Show the toolbar.
3732 toolbar.visibility = View.VISIBLE
3734 // Get a handle for the input method manager.
3735 val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
3737 // Hide the keyboard.
3738 inputMethodManager.hideSoftInputFromWindow(toolbar.windowToken, 0)
3741 // The view parameter cannot be removed because it is called from the layout onClick.
3742 fun closeTab(@Suppress("UNUSED_PARAMETER")view: View?) {
3743 // Run the command according to the number of tabs.
3744 if (tabLayout.tabCount > 1) { // There is more than one tab open.
3745 // Get the current tab number.
3746 val currentTabNumber = tabLayout.selectedTabPosition
3748 // Delete the current tab.
3749 tabLayout.removeTabAt(currentTabNumber)
3751 // 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,
3752 // meaning that the current WebView must be reset. Otherwise it will happen automatically as the selected tab number changes.
3753 if (webViewStateAdapter!!.deletePage(currentTabNumber, webViewViewPager2))
3754 setCurrentWebView(currentTabNumber)
3755 } else { // There is only one tab open.
3760 override fun createBookmark(dialogFragment: DialogFragment, favoriteIconBitmap: Bitmap) {
3762 val dialog = dialogFragment.dialog!!
3764 // Get the views from the dialog fragment.
3765 val createBookmarkNameEditText = dialog.findViewById<EditText>(R.id.create_bookmark_name_edittext)
3766 val createBookmarkUrlEditText = dialog.findViewById<EditText>(R.id.create_bookmark_url_edittext)
3768 // Extract the strings from the edit texts.
3769 val bookmarkNameString = createBookmarkNameEditText.text.toString()
3770 val bookmarkUrlString = createBookmarkUrlEditText.text.toString()
3772 // Create a favorite icon byte array output stream.
3773 val favoriteIconByteArrayOutputStream = ByteArrayOutputStream()
3775 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
3776 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream)
3778 // Convert the favorite icon byte array stream to a byte array.
3779 val favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray()
3781 // Display the new bookmark below the current items in the (0 indexed) list.
3782 val newBookmarkDisplayOrder = bookmarksListView.count
3784 // Create the bookmark.
3785 bookmarksDatabaseHelper!!.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray)
3787 // Update the bookmarks cursor with the current contents of this folder.
3788 bookmarksCursor = bookmarksDatabaseHelper!!.getBookmarksByDisplayOrder(currentBookmarksFolder)
3790 // Update the list view.
3791 bookmarksCursorAdapter.changeCursor(bookmarksCursor)
3793 // Scroll to the new bookmark.
3794 bookmarksListView.setSelection(newBookmarkDisplayOrder)
3797 override fun createBookmarkFolder(dialogFragment: DialogFragment, favoriteIconBitmap: Bitmap) {
3799 val dialog = dialogFragment.dialog!!
3801 // Get handles for the views in the dialog fragment.
3802 val folderNameEditText = dialog.findViewById<EditText>(R.id.folder_name_edittext)
3803 val defaultIconRadioButton = dialog.findViewById<RadioButton>(R.id.default_icon_radiobutton)
3804 val defaultIconImageView = dialog.findViewById<ImageView>(R.id.default_icon_imageview)
3806 // Get new folder name string.
3807 val folderNameString = folderNameEditText.text.toString()
3809 // Set the folder icon bitmap according to the dialog.
3810 val folderIconBitmap: Bitmap = if (defaultIconRadioButton.isChecked) { // Use the default folder icon.
3811 // Get the default folder icon drawable.
3812 val folderIconDrawable = defaultIconImageView.drawable
3814 // Convert the folder icon drawable to a bitmap drawable.
3815 val folderIconBitmapDrawable = folderIconDrawable as BitmapDrawable
3817 // Convert the folder icon bitmap drawable to a bitmap.
3818 folderIconBitmapDrawable.bitmap
3819 } else { // Use the WebView favorite icon.
3820 // Copy the favorite icon bitmap to the folder icon bitmap.
3824 // Create a folder icon byte array output stream.
3825 val folderIconByteArrayOutputStream = ByteArrayOutputStream()
3827 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
3828 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream)
3830 // Convert the folder icon byte array stream to a byte array.
3831 val folderIconByteArray = folderIconByteArrayOutputStream.toByteArray()
3833 // Move all the bookmarks down one in the display order.
3834 for (i in 0 until bookmarksListView.count) {
3835 // Get the bookmark database id.
3836 val databaseId = bookmarksListView.getItemIdAtPosition(i).toInt()
3838 // Move the bookmark down one slot.
3839 bookmarksDatabaseHelper!!.updateDisplayOrder(databaseId, i + 1)
3842 // Create the folder, which will be placed at the top of the list view.
3843 bookmarksDatabaseHelper!!.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray)
3845 // Update the bookmarks cursor with the current contents of this folder.
3846 bookmarksCursor = bookmarksDatabaseHelper!!.getBookmarksByDisplayOrder(currentBookmarksFolder)
3848 // Update the list view.
3849 bookmarksCursorAdapter.changeCursor(bookmarksCursor)
3851 // Scroll to the new folder.
3852 bookmarksListView.setSelection(0)
3855 private fun downloadUrlWithExternalApp(url: String) {
3856 // Create a download intent. Not specifying the action type will display the maximum number of options.
3857 val downloadIntent = Intent()
3859 // Set the URI and the mime type.
3860 downloadIntent.setDataAndType(Uri.parse(url), "text/html")
3862 // Flag the intent to open in a new task.
3863 downloadIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
3865 // Show the chooser.
3866 startActivity(Intent.createChooser(downloadIntent, getString(R.string.download_with_external_app)))
3869 private fun exitFullScreenVideo() {
3870 // Re-enable the screen timeout.
3871 fullScreenVideoFrameLayout.keepScreenOn = false
3873 // Unset the full screen video flag.
3874 displayingFullScreenVideo = false
3876 // Remove all the views from the full screen video frame layout.
3877 fullScreenVideoFrameLayout.removeAllViews()
3879 // Hide the full screen video frame layout.
3880 fullScreenVideoFrameLayout.visibility = View.GONE
3882 // Enable the sliding drawers.
3883 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED)
3885 // Show the coordinator layout.
3886 coordinatorLayout.visibility = View.VISIBLE
3888 // Apply the appropriate full screen mode flags.
3889 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
3890 // Hide the app bar if specified.
3892 // Hide the tab linear layout.
3893 tabsLinearLayout.visibility = View.GONE
3895 // Hide the app bar.
3899 /* Hide the system bars.
3900 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3901 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
3902 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3903 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3906 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
3907 @Suppress("DEPRECATION")
3908 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
3909 } else { // Switch to normal viewing mode.
3910 // Remove the `SYSTEM_UI` flags from the root frame layout. The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
3911 @Suppress("DEPRECATION")
3912 rootFrameLayout.systemUiVisibility = 0
3916 // The view parameter cannot be removed because it is called from the layout onClick.
3917 fun findNextOnPage(@Suppress("UNUSED_PARAMETER")view: View?) {
3918 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
3919 currentWebView!!.findNext(true)
3922 // The view parameter cannot be removed because it is called from the layout onClick.
3923 fun findPreviousOnPage(@Suppress("UNUSED_PARAMETER")view: View?) {
3924 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
3925 currentWebView!!.findNext(false)
3928 override fun finishedPopulatingFilterLists(combinedFilterLists: ArrayList<ArrayList<List<Array<String>>>>) {
3929 // Store the filter lists.
3930 easyList = combinedFilterLists[0]
3931 easyPrivacy = combinedFilterLists[1]
3932 fanboysAnnoyanceList = combinedFilterLists[2]
3933 fanboysSocialList = combinedFilterLists[3]
3934 ultraList = combinedFilterLists[4]
3935 ultraPrivacy = combinedFilterLists[5]
3937 // Check to see if the activity has been restarted with a saved state.
3938 if ((savedStateArrayList == null) || (savedStateArrayList!!.size == 0)) { // The activity has not been restarted or it was restarted on start to change the theme.
3939 // Add the first tab.
3940 addNewTab("", false)
3941 } else { // The activity has been restarted.
3942 // Restore each tab.
3943 for (i in savedStateArrayList!!.indices) {
3945 tabLayout.addTab(tabLayout.newTab())
3948 val newTab = tabLayout.getTabAt(i)!!
3950 // Set a custom view on the new tab.
3951 newTab.setCustomView(R.layout.tab_custom_view)
3953 // Add the new page.
3954 webViewStateAdapter!!.restorePage(savedStateArrayList!![i], savedNestedScrollWebViewStateArrayList!![i])
3957 // Reset the saved state variables.
3958 savedStateArrayList = null
3959 savedNestedScrollWebViewStateArrayList = null
3961 // Restore the selected tab position.
3962 if (savedTabPosition == 0) { // The first tab is selected.
3963 // Set the first page as the current WebView.
3964 setCurrentWebView(0)
3965 } else { // The first tab is not selected.
3966 // Move to the selected tab.
3967 webViewViewPager2.currentItem = savedTabPosition
3970 // Get the intent that started the app.
3973 // Reset the intent. This prevents a duplicate tab from being created on restart.
3976 // Get the information from the intent.
3977 val intentAction = intent.action
3978 val intentUriData = intent.data
3979 val intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT)
3981 // Determine if this is a web search.
3982 val isWebSearch = (intentAction != null) && (intentAction == Intent.ACTION_WEB_SEARCH)
3984 // 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.
3985 if ((intentUriData != null) || (intentStringExtra != null) || isWebSearch) {
3986 // Get the URL string.
3987 val urlString = if (isWebSearch) { // The intent is a web search.
3988 // Sanitize the search input.
3989 val encodedSearchString: String = try {
3990 URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8")
3991 } catch (exception: UnsupportedEncodingException) {
3995 // Add the base search URL.
3996 searchURL + encodedSearchString
3997 } else { // The intent contains a URL formatted as a URI or a URL in the string extra.
3998 // Get the URL string.
3999 intentUriData?.toString() ?: intentStringExtra!!
4002 // Add a new tab if specified in the preferences.
4003 if (sharedPreferences.getBoolean(getString(R.string.open_intents_in_new_tab_key), true)) { // Load the URL in a new tab.
4004 // Set the loading new intent flag.
4005 loadingNewIntent = true
4008 addNewTab(urlString, true)
4009 } else { // Load the URL in the current tab.
4011 loadUrl(currentWebView!!, urlString)
4017 // Remove the warning that `OnTouchListener()` needs to override `performClick()`, as the only purpose of setting the `OnTouchListener()` is to make it do nothing.
4018 @SuppressLint("ClickableViewAccessibility")
4019 private fun initializeApp() {
4020 // Get a handle for the input method.
4021 val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
4023 // Initialize the color spans for highlighting the URLs.
4024 initialGrayColorSpan = ForegroundColorSpan(getColor(R.color.gray_500))
4025 finalGrayColorSpan = ForegroundColorSpan(getColor(R.color.gray_500))
4026 redColorSpan = ForegroundColorSpan(getColor(R.color.red_text))
4028 // Remove the formatting from the URL edit text when the user is editing the text.
4029 urlEditText.onFocusChangeListener = View.OnFocusChangeListener { _: View?, hasFocus: Boolean ->
4030 if (hasFocus) { // The user is editing the URL text box.
4031 // Remove the syntax highlighting.
4032 urlEditText.text.removeSpan(redColorSpan)
4033 urlEditText.text.removeSpan(initialGrayColorSpan)
4034 urlEditText.text.removeSpan(finalGrayColorSpan)
4035 } else { // The user has stopped editing the URL text box.
4036 // Move to the beginning of the string.
4037 urlEditText.setSelection(0)
4039 // Reapply the syntax highlighting.
4040 UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
4044 // Set the go button on the keyboard to load the URL in url text box.
4045 urlEditText.setOnKeyListener { _: View?, keyCode: Int, keyEvent: KeyEvent ->
4046 // If the event is a key-down event on the `enter` button, load the URL.
4047 if ((keyEvent.action == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The enter key was pressed.
4049 loadUrlFromTextBox()
4051 // Consume the event.
4052 return@setOnKeyListener true
4053 } else { // Some other key was pressed.
4054 // Do not consume the event.
4055 return@setOnKeyListener false
4059 // Create an Orbot status broadcast receiver.
4060 orbotStatusBroadcastReceiver = object : BroadcastReceiver() {
4061 override fun onReceive(context: Context, intent: Intent) {
4062 // Get the content of the status message.
4063 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS")!!
4065 // If Privacy Browser is waiting on the proxy, load the website now that Orbot is connected.
4066 if ((orbotStatus == ProxyHelper.ORBOT_STATUS_ON) && waitingForProxy) {
4067 // Reset the waiting for proxy status.
4068 waitingForProxy = false
4070 // Get a list of the current fragments.
4071 val fragmentList = supportFragmentManager.fragments
4073 // Check each fragment to see if it is a waiting for proxy dialog. Sometimes more than one is displayed.
4074 for (i in fragmentList.indices) {
4075 // Get the fragment tag.
4076 val fragmentTag = fragmentList[i].tag
4078 // Check to see if it is the waiting for proxy dialog.
4079 if (fragmentTag != null && fragmentTag == getString(R.string.waiting_for_proxy_dialog)) {
4080 // Dismiss the waiting for proxy dialog.
4081 (fragmentList[i] as DialogFragment).dismiss()
4085 // Reload existing URLs and load any URLs that are waiting for the proxy.
4086 for (i in 0 until webViewStateAdapter!!.itemCount) {
4087 // Get the WebView tab fragment.
4088 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
4090 // Get the fragment view.
4091 val fragmentView = webViewTabFragment.view
4093 // Only process the WebViews if they exist.
4094 if (fragmentView != null) {
4095 // Get the nested scroll WebView from the tab fragment.
4096 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
4098 // Get the waiting for proxy URL string.
4099 val waitingForProxyUrlString = nestedScrollWebView.waitingForProxyUrlString
4101 // Load the pending URL if it exists.
4102 if (waitingForProxyUrlString.isNotEmpty()) { // A URL is waiting to be loaded.
4104 loadUrl(nestedScrollWebView, waitingForProxyUrlString)
4106 // Reset the waiting for proxy URL string.
4107 nestedScrollWebView.waitingForProxyUrlString = ""
4108 } else { // No URL is waiting to be loaded.
4109 // Reload the existing URL.
4110 nestedScrollWebView.reload()
4118 // Register the Orbot status broadcast receiver.
4119 registerReceiver(orbotStatusBroadcastReceiver, IntentFilter("org.torproject.android.intent.action.STATUS"))
4121 // Get handles for views that need to be modified.
4122 val bookmarksHeaderLinearLayout = findViewById<LinearLayout>(R.id.bookmarks_header_linearlayout)
4123 val launchBookmarksActivityFab = findViewById<FloatingActionButton>(R.id.launch_bookmarks_activity_fab)
4124 val createBookmarkFolderFab = findViewById<FloatingActionButton>(R.id.create_bookmark_folder_fab)
4125 val createBookmarkFab = findViewById<FloatingActionButton>(R.id.create_bookmark_fab)
4127 // Update the WebView pager every time a tab is modified.
4128 webViewViewPager2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
4129 override fun onPageSelected(position: Int) {
4130 // Close the find on page bar if it is open.
4131 closeFindOnPage(null)
4133 // Set the current WebView.
4134 setCurrentWebView(position)
4136 // 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.
4137 if (tabLayout.selectedTabPosition != position) {
4138 // Wait until the new tab has been created.
4140 // Get a handle for the tab.
4141 val tab = tabLayout.getTabAt(position)!!
4150 // Handle tab selections.
4151 tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
4152 override fun onTabSelected(tab: TabLayout.Tab) {
4153 // Select the same page in the view pager.
4154 webViewViewPager2.currentItem = tab.position
4157 override fun onTabUnselected(tab: TabLayout.Tab) {}
4159 override fun onTabReselected(tab: TabLayout.Tab) {
4160 // Instantiate the View SSL Certificate dialog.
4161 val viewSslCertificateDialogFragment: DialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView!!.webViewFragmentId, currentWebView!!.getFavoriteIcon())
4163 // Display the View SSL Certificate dialog.
4164 viewSslCertificateDialogFragment.show(supportFragmentManager, getString(R.string.view_ssl_certificate))
4168 // Set a touch listener on the bookmarks header linear layout so that touches don't pass through to the button underneath.
4169 bookmarksHeaderLinearLayout.setOnTouchListener { _: View?, _: MotionEvent? -> true }
4171 // Set the launch bookmarks activity floating action button to launch the bookmarks activity.
4172 launchBookmarksActivityFab.setOnClickListener {
4173 // Get a copy of the favorite icon bitmap.
4174 val currentFavoriteIconBitmap = currentWebView!!.getFavoriteIcon()
4176 // Create a favorite icon byte array output stream.
4177 val currentFavoriteIconByteArrayOutputStream = ByteArrayOutputStream()
4179 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
4180 currentFavoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, currentFavoriteIconByteArrayOutputStream)
4182 // Convert the favorite icon byte array stream to a byte array.
4183 val currentFavoriteIconByteArray = currentFavoriteIconByteArrayOutputStream.toByteArray()
4185 // Create an intent to launch the bookmarks activity.
4186 val bookmarksIntent = Intent(applicationContext, BookmarksActivity::class.java)
4188 // Add the extra information to the intent.
4189 bookmarksIntent.putExtra(CURRENT_FOLDER, currentBookmarksFolder)
4190 bookmarksIntent.putExtra(CURRENT_TITLE, currentWebView!!.title)
4191 bookmarksIntent.putExtra(CURRENT_URL, currentWebView!!.url)
4192 bookmarksIntent.putExtra(CURRENT_FAVORITE_ICON_BYTE_ARRAY, currentFavoriteIconByteArray)
4195 startActivity(bookmarksIntent)
4198 // Set the create new bookmark folder floating action button to display an alert dialog.
4199 createBookmarkFolderFab.setOnClickListener {
4200 // Create a create bookmark folder dialog.
4201 val createBookmarkFolderDialog: DialogFragment = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView!!.getFavoriteIcon())
4203 // Show the create bookmark folder dialog.
4204 createBookmarkFolderDialog.show(supportFragmentManager, getString(R.string.create_folder))
4207 // Set the create new bookmark floating action button to display an alert dialog.
4208 createBookmarkFab.setOnClickListener {
4209 // Instantiate the create bookmark dialog.
4210 val createBookmarkDialog: DialogFragment = CreateBookmarkDialog.createBookmark(currentWebView!!.url!!, currentWebView!!.title!!, currentWebView!!.getFavoriteIcon())
4212 // Display the create bookmark dialog.
4213 createBookmarkDialog.show(supportFragmentManager, getString(R.string.create_bookmark))
4216 // Search for the string on the page whenever a character changes in the find on page edit text.
4217 findOnPageEditText.addTextChangedListener(object : TextWatcher {
4218 override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
4220 override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
4222 override fun afterTextChanged(s: Editable) {
4223 // 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.
4224 currentWebView?.findAllAsync(findOnPageEditText.text.toString())
4228 // Set the `check mark` button for the find on page edit text keyboard to close the soft keyboard.
4229 findOnPageEditText.setOnKeyListener { _: View?, keyCode: Int, keyEvent: KeyEvent ->
4230 if ((keyEvent.action == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
4231 // Hide the soft keyboard.
4232 inputMethodManager.hideSoftInputFromWindow(currentWebView!!.windowToken, 0)
4234 // Consume the event.
4235 return@setOnKeyListener true
4236 } else { // A different key was pressed.
4237 // Do not consume the event.
4238 return@setOnKeyListener false
4242 // Implement swipe to refresh.
4243 swipeRefreshLayout.setOnRefreshListener {
4244 // Reload the website.
4245 currentWebView!!.reload()
4248 // Store the default progress view offsets.
4249 defaultProgressViewStartOffset = swipeRefreshLayout.progressViewStartOffset
4250 defaultProgressViewEndOffset = swipeRefreshLayout.progressViewEndOffset
4252 // Set the refresh color scheme according to the theme.
4253 swipeRefreshLayout.setColorSchemeResources(R.color.blue_text)
4255 // Initialize a color background typed value.
4256 val colorBackgroundTypedValue = TypedValue()
4258 // Get the color background from the theme.
4259 theme.resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true)
4261 // Get the color background int from the typed value.
4262 val colorBackgroundInt = colorBackgroundTypedValue.data
4264 // Set the swipe refresh background color.
4265 swipeRefreshLayout.setProgressBackgroundColorSchemeColor(colorBackgroundInt)
4267 // Set the drawer titles, which identify the drawer layouts in accessibility mode.
4268 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer))
4269 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks))
4271 // Load the bookmarks folder.
4272 loadBookmarksFolder()
4274 // Handle clicks on bookmarks.
4275 bookmarksListView.onItemClickListener = AdapterView.OnItemClickListener { _: AdapterView<*>?, _: View?, _: Int, id: Long ->
4276 // Convert the id from long to int to match the format of the bookmarks database.
4277 val databaseId = id.toInt()
4279 // Get the bookmark cursor for this ID.
4280 val bookmarkCursor = bookmarksDatabaseHelper!!.getBookmark(databaseId)
4282 // Move the bookmark cursor to the first row.
4283 bookmarkCursor.moveToFirst()
4285 // Act upon the bookmark according to the type.
4286 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
4287 // Store the folder name.
4288 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME))
4290 // Load the new folder.
4291 loadBookmarksFolder()
4292 } else { // The selected bookmark is not a folder.
4293 // Load the bookmark URL.
4294 loadUrl(currentWebView!!, bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_URL)))
4296 // Close the bookmarks drawer if it is not pinned.
4297 if (!bookmarksDrawerPinned)
4298 drawerLayout.closeDrawer(GravityCompat.END)
4301 // Close the cursor.
4302 bookmarkCursor.close()
4305 // Handle long-presses on bookmarks.
4306 bookmarksListView.onItemLongClickListener = AdapterView.OnItemLongClickListener { _: AdapterView<*>?, _: View?, _: Int, id: Long ->
4307 // Convert the database ID from `long` to `int`.
4308 val databaseId = id.toInt()
4310 // Run the commands associated with the type.
4311 if (bookmarksDatabaseHelper!!.isFolder(databaseId)) { // The bookmark is a folder.
4312 // Get a cursor of all the bookmarks in the folder.
4313 val bookmarksCursor = bookmarksDatabaseHelper!!.getFolderBookmarks(databaseId)
4315 // Move to the first entry in the cursor.
4316 bookmarksCursor.moveToFirst()
4318 // Open each bookmark
4319 for (i in 0 until bookmarksCursor.count) {
4320 // Load the bookmark in a new tab, moving to the tab for the first bookmark if the drawer is not pinned.
4321 addNewTab(bookmarksCursor.getString(bookmarksCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_URL)), !bookmarksDrawerPinned && (i == 0))
4323 // Move to the next bookmark.
4324 bookmarksCursor.moveToNext()
4327 // Close the cursor.
4328 bookmarksCursor.close()
4329 } else { // The bookmark is not a folder.
4330 // Get the bookmark cursor for this ID.
4331 val bookmarkCursor = bookmarksDatabaseHelper!!.getBookmark(databaseId)
4333 // Move the bookmark cursor to the first row.
4334 bookmarkCursor.moveToFirst()
4336 // Load the bookmark in a new tab and move to the tab if the drawer is not pinned.
4337 addNewTab(bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_URL)), !bookmarksDrawerPinned)
4339 // Close the cursor.
4340 bookmarkCursor.close()
4343 // Close the bookmarks drawer if it is not pinned.
4344 if (!bookmarksDrawerPinned)
4345 drawerLayout.closeDrawer(GravityCompat.END)
4347 // Consume the event.
4351 // The drawer listener is used to update the navigation menu.
4352 drawerLayout.addDrawerListener(object : DrawerLayout.DrawerListener {
4353 override fun onDrawerSlide(drawerView: View, slideOffset: Float) {}
4355 override fun onDrawerOpened(drawerView: View) {}
4357 override fun onDrawerClosed(drawerView: View) {
4358 // Reset the drawer icon when the drawer is closed. Otherwise, it remains an arrow if the drawer is open when the app is restarted.
4359 actionBarDrawerToggle!!.syncState()
4362 override fun onDrawerStateChanged(newState: Int) {
4363 if (newState == DrawerLayout.STATE_SETTLING || newState == DrawerLayout.STATE_DRAGGING) { // A drawer is opening or closing.
4364 // Update the navigation menu items if the WebView is not null.
4365 if (currentWebView != null) {
4366 navigationBackMenuItem.isEnabled = currentWebView!!.canGoBack()
4367 navigationForwardMenuItem.isEnabled = currentWebView!!.canGoForward()
4368 navigationHistoryMenuItem.isEnabled = currentWebView!!.canGoBack() || currentWebView!!.canGoForward()
4369 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + currentWebView!!.getRequestsCount(BLOCKED_REQUESTS)
4371 // Hide the keyboard (if displayed).
4372 inputMethodManager.hideSoftInputFromWindow(currentWebView!!.windowToken, 0)
4375 // 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.
4376 urlEditText.clearFocus()
4378 // 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.
4379 // Clearing the focus from the WebView removes any text selection markers and context menus, which otherwise draw above the open drawers.
4380 currentWebView?.clearFocus()
4385 // Inflate a bare WebView to get the default user agent. It is not used to render content on the screen.
4386 @SuppressLint("InflateParams") val webViewLayout = layoutInflater.inflate(R.layout.bare_webview, null, false)
4388 // Get a handle for the WebView.
4389 val bareWebView = webViewLayout.findViewById<WebView>(R.id.bare_webview)
4391 // Store the default user agent.
4392 webViewDefaultUserAgent = bareWebView.settings.userAgentString
4394 // Destroy the bare WebView.
4395 bareWebView.destroy()
4397 // Update the domains settings set.
4398 updateDomainsSettingsSet()
4400 // Instantiate the check filter list helper.
4401 checkFilterListHelper = CheckFilterListHelper()
4404 @SuppressLint("ClickableViewAccessibility")
4405 override fun initializeWebView(nestedScrollWebView: NestedScrollWebView, pageNumber: Int, progressBar: ProgressBar, urlString: String, restoringState: Boolean) {
4406 // Get the WebView theme.
4407 val webViewTheme = sharedPreferences.getString(getString(R.string.webview_theme_key), getString(R.string.webview_theme_default_value))
4409 // Get the WebView theme entry values string array.
4410 val webViewThemeEntryValuesStringArray = resources.getStringArray(R.array.webview_theme_entry_values)
4412 // Set the WebView theme if device is running API >= 29 and algorithmic darkening is supported.
4413 if (Build.VERSION.SDK_INT >= 29 && WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {
4414 // Set the WebView them. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
4415 if (webViewTheme == webViewThemeEntryValuesStringArray[1]) { // The light theme is selected.
4416 // Turn off algorithmic darkening.
4417 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
4419 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
4420 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
4421 nestedScrollWebView.visibility = View.VISIBLE
4422 } else if (webViewTheme == webViewThemeEntryValuesStringArray[2]) { // The dark theme is selected.
4423 // Turn on algorithmic darkening.
4424 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
4425 } else { // The system default theme is selected.
4426 // Get the current theme status.
4427 val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
4429 // Set the algorithmic darkening according to the current system theme status.
4430 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) { // The system is in day mode.
4431 // Turn off algorithmic darkening.
4432 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
4434 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
4435 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
4436 nestedScrollWebView.visibility = View.VISIBLE
4437 } else { // The system is in night mode.
4438 // Turn on algorithmic darkening.
4439 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
4444 // Get a handle for the input method manager.
4445 val inputMethodManager = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
4447 // Set the app bar scrolling.
4448 nestedScrollWebView.isNestedScrollingEnabled = scrollAppBar
4450 // Allow pinch to zoom.
4451 nestedScrollWebView.settings.builtInZoomControls = true
4453 // Hide zoom controls.
4454 nestedScrollWebView.settings.displayZoomControls = false
4456 // Don't allow mixed content (HTTP and HTTPS) on the same website.
4457 nestedScrollWebView.settings.mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW
4459 // Set the WebView to load in overview mode (zoomed out to the maximum width).
4460 nestedScrollWebView.settings.loadWithOverviewMode = true
4462 // Explicitly disable geolocation.
4463 nestedScrollWebView.settings.setGeolocationEnabled(false)
4465 // Allow loading of file:// URLs. This is necessary for opening MHT web archives, which are copied into a temporary cache location.
4466 nestedScrollWebView.settings.allowFileAccess = true
4468 // Create a double-tap gesture detector to toggle full-screen mode.
4469 val doubleTapGestureDetector = GestureDetector(this, object : GestureDetector.SimpleOnGestureListener() {
4470 // Override `onDoubleTap()`. All other events are handled using the default settings.
4471 override fun onDoubleTap(motionEvent: MotionEvent): Boolean {
4472 return if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
4473 // Toggle the full screen browsing mode tracker.
4474 inFullScreenBrowsingMode = !inFullScreenBrowsingMode
4476 // Toggle the full screen browsing mode.
4477 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
4478 // Hide the app bar if specified.
4479 if (hideAppBar) { // App bar hiding is enabled.
4480 // Close the find on page bar if it is visible.
4481 closeFindOnPage(null)
4483 // Hide the tab linear layout.
4484 tabsLinearLayout.visibility = View.GONE
4486 // Hide the app bar.
4489 // Set layout and scrolling parameters according to the position of the app bar.
4490 if (bottomAppBar) { // The app bar is at the bottom.
4491 // Reset the WebView padding to fill the available space.
4492 swipeRefreshLayout.setPadding(0, 0, 0, 0)
4493 } else { // The app bar is at the top.
4494 // Check to see if the app bar is normally scrolled.
4495 if (scrollAppBar) { // The app bar is scrolled when it is displayed.
4496 // Get the swipe refresh layout parameters.
4497 val swipeRefreshLayoutParams = swipeRefreshLayout.layoutParams as CoordinatorLayout.LayoutParams
4499 // Remove the off-screen scrolling layout.
4500 swipeRefreshLayoutParams.behavior = null
4501 } else { // The app bar is not scrolled when it is displayed.
4502 // Remove the padding from the top of the swipe refresh layout.
4503 swipeRefreshLayout.setPadding(0, 0, 0, 0)
4505 // The swipe refresh circle must be moved above the now removed status bar location.
4506 swipeRefreshLayout.setProgressViewOffset(false, -200, defaultProgressViewEndOffset)
4509 } else { // App bar hiding is not enabled.
4510 // Adjust the UI for the bottom app bar.
4512 // Adjust the UI according to the scrolling of the app bar.
4514 // Reset the WebView padding to fill the available space.
4515 swipeRefreshLayout.setPadding(0, 0, 0, 0)
4517 // Move the WebView above the app bar layout.
4518 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
4523 /* Hide the system bars.
4524 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4525 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4526 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4527 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4530 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4531 @Suppress("DEPRECATION")
4532 rootFrameLayout.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
4533 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
4534 } else { // Switch to normal viewing mode.
4535 // Show the app bar if it was hidden.
4537 // Show the tab linear layout.
4538 tabsLinearLayout.visibility = View.VISIBLE
4540 // Show the app bar.
4544 // Set layout and scrolling parameters according to the position of the app bar.
4545 if (bottomAppBar) { // The app bar is at the bottom.
4548 // Reset the WebView padding to fill the available space.
4549 swipeRefreshLayout.setPadding(0, 0, 0, 0)
4551 // Move the WebView above the app bar layout.
4552 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
4554 } else { // The app bar is at the top.
4555 // Check to see if the app bar is normally scrolled.
4556 if (scrollAppBar) { // The app bar is scrolled when it is displayed.
4557 // Get the swipe refresh layout parameters.
4558 val swipeRefreshLayoutParams = swipeRefreshLayout.layoutParams as CoordinatorLayout.LayoutParams
4560 // Add the off-screen scrolling layout.
4561 swipeRefreshLayoutParams.behavior = AppBarLayout.ScrollingViewBehavior()
4562 } else { // The app bar is not scrolled when it is displayed.
4563 // The swipe refresh layout must be manually moved below the app bar layout.
4564 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0)
4566 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
4567 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight)
4571 // Remove the `SYSTEM_UI` flags from the root frame layout. The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4572 @Suppress("DEPRECATION")
4573 rootFrameLayout.systemUiVisibility = 0
4576 // Consume the double-tap.
4578 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
4584 override fun onFling(motionEvent1: MotionEvent, motionEvent2: MotionEvent, velocityX: Float, velocityY: Float): Boolean {
4585 // Scroll the bottom app bar if enabled.
4586 if (bottomAppBar && scrollAppBar && !objectAnimator.isRunning) {
4587 // Calculate the Y change.
4588 val motionY = motionEvent2.y - motionEvent1.y
4590 // Scroll the app bar if the change is greater than 50 pixels.
4592 // Animate the bottom app bar onto the screen.
4593 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0f)
4594 } else if (motionY < -50) {
4595 // Animate the bottom app bar off the screen.
4596 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", appBarLayout.height.toFloat())
4600 objectAnimator.start()
4603 // Do not consume the event.
4608 // Pass all touch events on the WebView through the double-tap gesture detector.
4609 nestedScrollWebView.setOnTouchListener { view: View, motionEvent: MotionEvent? ->
4610 // Call `performClick()` on the view, which is required for accessibility.
4613 // Check for double-taps.
4614 doubleTapGestureDetector.onTouchEvent(motionEvent!!)
4617 // Register the WebView for a context menu. This is used to see link targets and download images.
4618 registerForContextMenu(nestedScrollWebView)
4620 // Allow the downloading of files.
4621 nestedScrollWebView.setDownloadListener { downloadUrlString: String?, userAgent: String?, contentDisposition: String?, mimetype: String?, contentLength: Long ->
4622 // Check the download preference.
4623 if (downloadWithExternalApp) { // Download with an external app.
4624 downloadUrlWithExternalApp(downloadUrlString!!)
4625 } else { // Handle the download inside of Privacy Browser.
4626 // Define a formatted file size string.
4628 // Process the content length if it contains data.
4629 val formattedFileSizeString = if (contentLength > 0) { // The content length is greater than 0.
4630 // Format the content length as a string.
4631 NumberFormat.getInstance().format(contentLength) + " " + getString(R.string.bytes)
4632 } else { // The content length is not greater than 0.
4633 // Set the formatted file size string to be `unknown size`.
4634 getString(R.string.unknown_size)
4637 // Get the file name from the content disposition.
4638 val fileNameString = UrlHelper.getFileName(this, contentDisposition, mimetype, downloadUrlString!!)
4640 // Instantiate the save dialog.
4641 val saveDialogFragment = SaveDialog.saveUrl(downloadUrlString, fileNameString, formattedFileSizeString, userAgent!!, nestedScrollWebView.acceptCookies)
4643 // 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.
4645 // Show the save dialog.
4646 saveDialogFragment.show(supportFragmentManager, getString(R.string.save_dialog))
4647 } catch (exception: Exception) { // The dialog could not be shown.
4648 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
4649 pendingDialogsArrayList.add(PendingDialogDataClass(saveDialogFragment, getString(R.string.save_dialog)))
4654 // Update the find on page count.
4655 nestedScrollWebView.setFindListener { activeMatchOrdinal, numberOfMatches, isDoneCounting ->
4656 if (isDoneCounting && (numberOfMatches == 0)) { // There are no matches.
4657 // Set the find on page count text view to be `0/0`.
4658 findOnPageCountTextView.setText(R.string.zero_of_zero)
4659 } else if (isDoneCounting) { // There are matches.
4660 // The active match ordinal is zero-based.
4661 val activeMatch = activeMatchOrdinal + 1
4663 // Build the match string.
4664 val matchString = "$activeMatch/$numberOfMatches"
4666 // Update the find on page count text view.
4667 findOnPageCountTextView.text = matchString
4671 // Process scroll changes.
4672 nestedScrollWebView.setOnScrollChangeListener { _: View?, _: Int, _: Int, _: Int, _: Int ->
4673 // Set the swipe to refresh status.
4674 if (nestedScrollWebView.swipeToRefresh) // Only enable swipe to refresh if the WebView is scrolled to the top.
4675 swipeRefreshLayout.isEnabled = nestedScrollWebView.scrollY == 0
4676 else // Disable swipe to refresh.
4677 swipeRefreshLayout.isEnabled = false
4679 // Reinforce the system UI visibility flags if in full screen browsing mode.
4680 // This hides the status and navigation bars, which are displayed if other elements are shown, like dialog boxes, the options menu, or the keyboard.
4681 if (inFullScreenBrowsingMode) {
4682 /* Hide the system bars.
4683 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4684 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4685 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4686 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4689 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4690 @Suppress("DEPRECATION")
4691 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
4695 // Set the web chrome client.
4696 nestedScrollWebView.webChromeClient = object : WebChromeClient() {
4697 // Update the progress bar when a page is loading.
4698 override fun onProgressChanged(view: WebView, progress: Int) {
4699 // Update the progress bar.
4700 progressBar.progress = progress
4702 // Set the visibility of the progress bar.
4703 if (progress < 100) {
4704 // Show the progress bar.
4705 progressBar.visibility = View.VISIBLE
4707 // Hide the progress bar.
4708 progressBar.visibility = View.GONE
4710 //Stop the swipe to refresh indicator if it is running
4711 swipeRefreshLayout.isRefreshing = false
4713 // 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.
4714 nestedScrollWebView.visibility = View.VISIBLE
4718 // Set the favorite icon when it changes.
4719 override fun onReceivedIcon(view: WebView, icon: Bitmap) {
4720 // 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.
4721 // This prevents low resolution icons from replacing high resolution one.
4722 // The check for the visibility of the progress bar can possibly be removed once https://redmine.stoutner.com/issues/747 is fixed.
4723 if ((progressBar.visibility == View.GONE) && (icon.height > nestedScrollWebView.getFavoriteIconHeight())) {
4724 // Store the new favorite icon.
4725 nestedScrollWebView.setFavoriteIcon(icon)
4727 // Get the current page position.
4728 val currentPosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
4730 // Get the current tab.
4731 val tab = tabLayout.getTabAt(currentPosition)
4733 // Check to see if the tab has been populated.
4735 // Get the custom view from the tab.
4736 val tabView = tab.customView
4738 // Check to see if the custom tab view has been populated.
4739 if (tabView != null) {
4740 // Get the favorite icon image view from the tab.
4741 val tabFavoriteIconImageView = tabView.findViewById<ImageView>(R.id.favorite_icon_imageview)
4743 // Display the favorite icon in the tab.
4744 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true))
4750 // Save a copy of the title when it changes.
4751 override fun onReceivedTitle(view: WebView, title: String) {
4752 // Get the current page position.
4753 val currentPosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
4755 // Get the current tab.
4756 val tab = tabLayout.getTabAt(currentPosition)
4758 // Only populate the title text view if the tab has been fully created.
4760 // Get the custom view from the tab.
4761 val tabView = tab.customView
4763 // Only populate the title text view if the tab view has been fully populated.
4764 if (tabView != null) {
4765 // Get the title text view from the tab.
4766 val tabTitleTextView = tabView.findViewById<TextView>(R.id.title_textview)
4768 // Set the title according to the URL.
4769 if (title == "about:blank") {
4770 // Set the title to indicate a new tab.
4771 tabTitleTextView.setText(R.string.new_tab)
4773 // Set the title as the tab text.
4774 tabTitleTextView.text = title
4780 // Enter full screen video.
4781 override fun onShowCustomView(video: View, callback: CustomViewCallback) {
4782 // Set the full screen video flag.
4783 displayingFullScreenVideo = true
4785 // Hide the keyboard.
4786 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.windowToken, 0)
4788 // Hide the coordinator layout.
4789 coordinatorLayout.visibility = View.GONE
4791 /* Hide the system bars.
4792 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4793 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4794 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4795 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4798 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4799 @Suppress("DEPRECATION")
4800 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
4802 // Disable the sliding drawers.
4803 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
4805 // Add the video view to the full screen video frame layout.
4806 fullScreenVideoFrameLayout.addView(video)
4808 // Show the full screen video frame layout.
4809 fullScreenVideoFrameLayout.visibility = View.VISIBLE
4811 // Disable the screen timeout while the video is playing. YouTube does this automatically, but not all other videos do.
4812 fullScreenVideoFrameLayout.keepScreenOn = true
4815 // Exit full screen video.
4816 override fun onHideCustomView() {
4817 // Exit the full screen video.
4818 exitFullScreenVideo()
4822 override fun onShowFileChooser(webView: WebView, filePathCallback: ValueCallback<Array<Uri>>, fileChooserParams: FileChooserParams): Boolean {
4823 // Store the file path callback.
4824 fileChooserCallback = filePathCallback
4826 // Create an intent to open a chooser based on the file chooser parameters.
4827 val fileChooserIntent = fileChooserParams.createIntent()
4829 // Check to see if the file chooser intent resolves to an installed package.
4830 if (fileChooserIntent.resolveActivity(packageManager) != null) { // The file chooser intent is fine.
4831 // Launch the file chooser intent.
4832 browseFileUploadActivityResultLauncher.launch(fileChooserIntent)
4833 } else { // The file chooser intent will cause a crash.
4834 // Create a generic intent to open a chooser.
4835 val genericFileChooserIntent = Intent(Intent.ACTION_GET_CONTENT)
4837 // Request an openable file.
4838 genericFileChooserIntent.addCategory(Intent.CATEGORY_OPENABLE)
4840 // Set the file type to everything.
4841 genericFileChooserIntent.type = "*/*"
4843 // Launch the generic file chooser intent.
4844 browseFileUploadActivityResultLauncher.launch(genericFileChooserIntent)
4847 // Handle the event.
4851 nestedScrollWebView.webViewClient = object : WebViewClient() {
4852 // `shouldOverrideUrlLoading` makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
4853 override fun shouldOverrideUrlLoading(view: WebView, webResourceRequest: WebResourceRequest): Boolean {
4854 // Get the URL from the web resource request.
4855 var requestUrlString = webResourceRequest.url.toString()
4857 // Sanitize the url.
4858 requestUrlString = sanitizeUrl(requestUrlString)
4860 // Handle the URL according to the type.
4861 return if (requestUrlString.startsWith("http")) { // Load the URL in Privacy Browser.
4862 // Load the URL. By using `loadUrl()`, instead of `loadUrlFromBase()`, the Referer header will never be sent.
4863 loadUrl(nestedScrollWebView, requestUrlString)
4865 // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
4866 // Custom headers cannot be added if false is returned and the WebView handles the loading of the URL.
4868 } else if (requestUrlString.startsWith("mailto:")) { // Load the email address in an external email program.
4869 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
4870 val emailIntent = Intent(Intent.ACTION_SENDTO)
4872 // Parse the url and set it as the data for the intent.
4873 emailIntent.data = Uri.parse(requestUrlString)
4875 // Open the email program in a new task instead of as part of Privacy Browser.
4876 emailIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
4880 startActivity(emailIntent)
4881 } catch (exception: ActivityNotFoundException) {
4882 // Display a snackbar.
4883 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
4886 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
4888 } else if (requestUrlString.startsWith("tel:")) { // Load the phone number in the dialer.
4889 // Create a dial intent.
4890 val dialIntent = Intent(Intent.ACTION_DIAL)
4892 // Add the phone number to the intent.
4893 dialIntent.data = Uri.parse(requestUrlString)
4895 // Open the dialer in a new task instead of as part of Privacy Browser.
4896 dialIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
4900 startActivity(dialIntent)
4901 } catch (exception: ActivityNotFoundException) {
4902 // Display a snackbar.
4903 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
4906 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
4908 } else { // Load a system chooser to select an app that can handle the URL.
4909 // Create a generic intent to open an app.
4910 val genericIntent = Intent(Intent.ACTION_VIEW)
4912 // Add the URL to the intent.
4913 genericIntent.data = Uri.parse(requestUrlString)
4915 // List all apps that can handle the URL instead of just opening the first one.
4916 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE)
4918 // Open the app in a new task instead of as part of Privacy Browser.
4919 genericIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
4923 startActivity(genericIntent)
4924 } catch (exception: ActivityNotFoundException) {
4925 // Display a snackbar.
4926 Snackbar.make(nestedScrollWebView, getString(R.string.unrecognized_url, requestUrlString), Snackbar.LENGTH_SHORT).show()
4929 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
4934 // Check requests against the block lists.
4935 override fun shouldInterceptRequest(view: WebView, webResourceRequest: WebResourceRequest): WebResourceResponse? {
4937 val requestUrlString = webResourceRequest.url.toString()
4939 // Check to see if the resource request is for the main URL.
4940 if (requestUrlString == nestedScrollWebView.currentUrl) {
4941 // `return null` loads the resource request, which should never be blocked if it is the main URL.
4945 // 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.
4946 while (ultraPrivacy == null) {
4948 // Check to see if the filter lists have been populated after 100 ms.
4950 } catch (exception: InterruptedException) {
4955 // Create an empty web resource response to be used if the resource request is blocked.
4956 val emptyWebResourceResponse = WebResourceResponse("text/plain", "utf8", ByteArrayInputStream("".toByteArray()))
4958 // Initialize the variables.
4959 var allowListResultStringArray: Array<String>? = null
4960 var isThirdPartyRequest = false
4962 // Get the current URL. `.getUrl()` throws an error because operations on the WebView cannot be made from this thread.
4963 var currentBaseDomain = nestedScrollWebView.currentDomainName
4965 // Store a copy of the current domain for use in later requests.
4966 val currentDomain = currentBaseDomain
4968 // Get the request host name.
4969 var requestBaseDomain = webResourceRequest.url.host
4971 // Only check for third-party requests if the current base domain is not empty and the request domain is not null.
4972 if (currentBaseDomain.isNotEmpty() && (requestBaseDomain != null)) {
4973 // Determine the current base domain.
4974 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
4975 // Remove the first subdomain.
4976 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1)
4979 // Determine the request base domain.
4980 while (requestBaseDomain!!.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
4981 // Remove the first subdomain.
4982 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1)
4985 // Update the third party request tracker.
4986 isThirdPartyRequest = currentBaseDomain != requestBaseDomain
4989 // Get the current WebView page position.
4990 val webViewPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
4992 // Determine if the WebView is currently displayed.
4993 val webViewDisplayed = (webViewPagePosition == tabLayout.selectedTabPosition)
4995 // Block third-party requests if enabled.
4996 if (isThirdPartyRequest && nestedScrollWebView.blockAllThirdPartyRequests) {
4997 // Add the result to the resource requests.
4998 nestedScrollWebView.addResourceRequest(arrayOf(REQUEST_THIRD_PARTY, requestUrlString))
5000 // Increment the blocked requests counters.
5001 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5002 nestedScrollWebView.incrementRequestsCount(THIRD_PARTY_REQUESTS)
5004 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5005 if (webViewDisplayed) {
5006 // Updating the UI must be run from the UI thread.
5008 // Update the menu item titles.
5009 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5011 // Update the options menu if it has been populated.
5012 if (optionsMenu != null) {
5013 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5014 optionsBlockAllThirdPartyRequestsMenuItem.title =
5015 nestedScrollWebView.getRequestsCount(THIRD_PARTY_REQUESTS).toString() + " - " + getString(R.string.block_all_third_party_requests)
5020 // The resource request was blocked. Return an empty web resource response.
5021 return emptyWebResourceResponse
5024 // Check UltraList if it is enabled.
5025 if (nestedScrollWebView.ultraListEnabled) {
5026 // Check the URL against UltraList.
5027 val ultraListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, ultraList)
5029 // Process the UltraList results.
5030 if (ultraListResults[0] == REQUEST_BLOCKED) { // The resource request matched UltraList's block list.
5031 // Add the result to the resource requests.
5032 nestedScrollWebView.addResourceRequest(arrayOf(ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]))
5034 // Increment the blocked requests counters.
5035 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5036 nestedScrollWebView.incrementRequestsCount(com.stoutner.privacybrowser.views.ULTRALIST)
5038 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5039 if (webViewDisplayed) {
5040 // Updating the UI must be run from the UI thread.
5042 // Update the menu item titles.
5043 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5045 // Update the options menu if it has been populated.
5046 if (optionsMenu != null) {
5047 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5048 optionsUltraListMenuItem.title = nestedScrollWebView.getRequestsCount(com.stoutner.privacybrowser.views.ULTRALIST).toString() + " - " + getString(R.string.ultralist)
5053 // The resource request was blocked. Return an empty web resource response.
5054 return emptyWebResourceResponse
5055 } else if (ultraListResults[0] == REQUEST_ALLOWED) { // The resource request matched UltraList's allow list.
5056 // Add an allow list entry to the resource requests array.
5057 nestedScrollWebView.addResourceRequest(arrayOf(ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]))
5059 // The resource request has been allowed by UltraList. `return null` loads the requested resource.
5064 // Check UltraPrivacy if it is enabled.
5065 if (nestedScrollWebView.ultraPrivacyEnabled) {
5066 // Check the URL against UltraPrivacy.
5067 val ultraPrivacyResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, ultraPrivacy!!)
5069 // Process the UltraPrivacy results.
5070 if (ultraPrivacyResults[0] == REQUEST_BLOCKED) { // The resource request matched UltraPrivacy's block list.
5071 // Add the result to the resource requests.
5072 nestedScrollWebView.addResourceRequest(arrayOf(ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5073 ultraPrivacyResults[5]))
5075 // Increment the blocked requests counters.
5076 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5077 nestedScrollWebView.incrementRequestsCount(ULTRAPRIVACY)
5079 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5080 if (webViewDisplayed) {
5081 // Updating the UI must be run from the UI thread.
5083 // Update the menu item titles.
5084 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5086 // Update the options menu if it has been populated.
5087 if (optionsMenu != null) {
5088 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5089 optionsUltraPrivacyMenuItem.title = nestedScrollWebView.getRequestsCount(ULTRAPRIVACY).toString() + " - " + getString(R.string.ultraprivacy)
5094 // The resource request was blocked. Return an empty web resource response.
5095 return emptyWebResourceResponse
5096 } else if (ultraPrivacyResults[0] == REQUEST_ALLOWED) { // The resource request matched UltraPrivacy's allow list.
5097 // Add an allow list entry to the resource requests array.
5098 nestedScrollWebView.addResourceRequest(arrayOf(ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5099 ultraPrivacyResults[5]))
5101 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
5106 // Check EasyList if it is enabled.
5107 if (nestedScrollWebView.easyListEnabled) {
5108 // Check the URL against EasyList.
5109 val easyListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, easyList)
5111 // Process the EasyList results.
5112 if (easyListResults[0] == REQUEST_BLOCKED) { // The resource request matched EasyList's block list.
5113 // Add the result to the resource requests.
5114 nestedScrollWebView.addResourceRequest(arrayOf(easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]))
5116 // Increment the blocked requests counters.
5117 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5118 nestedScrollWebView.incrementRequestsCount(EASYLIST)
5120 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5121 if (webViewDisplayed) {
5122 // Updating the UI must be run from the UI thread.
5124 // Update the menu item titles.
5125 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5127 // Update the options menu if it has been populated.
5128 if (optionsMenu != null) {
5129 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5130 optionsEasyListMenuItem.title = nestedScrollWebView.getRequestsCount(EASYLIST).toString() + " - " + getString(R.string.easylist)
5135 // The resource request was blocked. Return an empty web resource response.
5136 return emptyWebResourceResponse
5137 } else if (easyListResults[0] == REQUEST_ALLOWED) { // The resource request matched EasyList's allow list.
5138 // Update the allow list result string array tracker.
5139 allowListResultStringArray = arrayOf(easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5])
5143 // Check EasyPrivacy if it is enabled.
5144 if (nestedScrollWebView.easyPrivacyEnabled) {
5145 // Check the URL against EasyPrivacy.
5146 val easyPrivacyResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, easyPrivacy)
5148 // Process the EasyPrivacy results.
5149 if (easyPrivacyResults[0] == REQUEST_BLOCKED) { // The resource request matched EasyPrivacy's block list.
5150 // Add the result to the resource requests.
5151 nestedScrollWebView.addResourceRequest(arrayOf(easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5]))
5153 // Increment the blocked requests counters.
5154 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5155 nestedScrollWebView.incrementRequestsCount(EASYPRIVACY)
5157 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5158 if (webViewDisplayed) {
5159 // Updating the UI must be run from the UI thread.
5161 // Update the menu item titles.
5162 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5164 // Update the options menu if it has been populated.
5165 if (optionsMenu != null) {
5166 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5167 optionsEasyPrivacyMenuItem.title = nestedScrollWebView.getRequestsCount(EASYPRIVACY).toString() + " - " + getString(R.string.easyprivacy)
5172 // The resource request was blocked. Return an empty web resource response.
5173 return emptyWebResourceResponse
5174 } else if (easyPrivacyResults[0] == REQUEST_ALLOWED) { // The resource request matched EasyPrivacy's allow list.
5175 // Update the allow list result string array tracker.
5176 allowListResultStringArray = arrayOf(easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5])
5180 // Check Fanboy’s Annoyance List if it is enabled.
5181 if (nestedScrollWebView.fanboysAnnoyanceListEnabled) {
5182 // Check the URL against Fanboy's Annoyance List.
5183 val fanboysAnnoyanceListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, fanboysAnnoyanceList)
5185 // Process the Fanboy's Annoyance List results.
5186 if (fanboysAnnoyanceListResults[0] == REQUEST_BLOCKED) { // The resource request matched Fanboy's Annoyance List's block list.
5187 // Add the result to the resource requests.
5188 nestedScrollWebView.addResourceRequest(arrayOf(fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5189 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]))
5191 // Increment the blocked requests counters.
5192 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5193 nestedScrollWebView.incrementRequestsCount(FANBOYS_ANNOYANCE_LIST)
5195 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5196 if (webViewDisplayed) {
5197 // Updating the UI must be run from the UI thread.
5199 // Update the menu item titles.
5200 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5202 // Update the options menu if it has been populated.
5203 if (optionsMenu != null) {
5204 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5205 optionsFanboysAnnoyanceListMenuItem.title = nestedScrollWebView.getRequestsCount(FANBOYS_ANNOYANCE_LIST).toString() + " - " + getString(R.string.fanboys_annoyance_list)
5210 // The resource request was blocked. Return an empty web resource response.
5211 return emptyWebResourceResponse
5212 } else if (fanboysAnnoyanceListResults[0] == REQUEST_ALLOWED) { // The resource request matched Fanboy's Annoyance List's allow list.
5213 // Update the allow list result string array tracker.
5214 allowListResultStringArray = arrayOf(fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5215 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5])
5217 } else if (nestedScrollWebView.fanboysSocialBlockingListEnabled) { // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
5218 // Check the URL against Fanboy's Annoyance List.
5219 val fanboysSocialListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, fanboysSocialList)
5221 // Process the Fanboy's Social Blocking List results.
5222 if (fanboysSocialListResults[0] == REQUEST_BLOCKED) { // The resource request matched Fanboy's Social Blocking List's block list.
5223 // Add the result to the resource requests.
5224 nestedScrollWebView.addResourceRequest(arrayOf(fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5225 fanboysSocialListResults[4], fanboysSocialListResults[5]))
5227 // Increment the blocked requests counters.
5228 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5229 nestedScrollWebView.incrementRequestsCount(FANBOYS_SOCIAL_BLOCKING_LIST)
5231 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5232 if (webViewDisplayed) {
5233 // Updating the UI must be run from the UI thread.
5235 // Update the menu item titles.
5236 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5238 // Update the options menu if it has been populated.
5239 if (optionsMenu != null) {
5240 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5241 optionsFanboysSocialBlockingListMenuItem.title =
5242 nestedScrollWebView.getRequestsCount(FANBOYS_SOCIAL_BLOCKING_LIST).toString() + " - " + getString(R.string.fanboys_social_blocking_list)
5247 // The resource request was blocked. Return an empty web resource response.
5248 return emptyWebResourceResponse
5249 } else if (fanboysSocialListResults[0] == REQUEST_ALLOWED) { // The resource request matched Fanboy's Social Blocking List's allow list.
5250 // Update the allow list result string array tracker.
5251 allowListResultStringArray = arrayOf(fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3], fanboysSocialListResults[4],
5252 fanboysSocialListResults[5])
5256 // Add the request to the log because it hasn't been processed by any of the previous checks.
5257 if (allowListResultStringArray != null) { // The request was processed by an allow list.
5258 nestedScrollWebView.addResourceRequest(allowListResultStringArray)
5259 } else { // The request didn't match any filter list entry. Log it as a default request.
5260 nestedScrollWebView.addResourceRequest(arrayOf(REQUEST_DEFAULT, requestUrlString))
5263 // The resource request has not been blocked. `return null` loads the requested resource.
5267 // Handle HTTP authentication requests.
5268 override fun onReceivedHttpAuthRequest(view: WebView, handler: HttpAuthHandler, host: String, realm: String) {
5269 // Store the handler.
5270 nestedScrollWebView.httpAuthHandler = handler
5272 // Instantiate an HTTP authentication dialog.
5273 val httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm, nestedScrollWebView.webViewFragmentId)
5275 // Show the HTTP authentication dialog.
5276 httpAuthenticationDialogFragment.show(supportFragmentManager, getString(R.string.http_authentication))
5279 override fun onPageStarted(webView: WebView, url: String, favicon: Bitmap?) {
5280 // Get the app bar layout height. This can't be done in `applyAppSettings()` because the app bar is not yet populated there.
5281 // 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.
5282 if (appBarLayout.height > 0)
5283 appBarHeight = appBarLayout.height
5285 // Set the padding and layout settings according to the position of the app bar.
5286 if (bottomAppBar) { // The app bar is on the bottom.
5288 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) { // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
5289 // Reset the WebView padding to fill the available space.
5290 swipeRefreshLayout.setPadding(0, 0, 0, 0)
5291 } else { // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
5292 // Move the WebView above the app bar layout.
5293 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
5295 } else { // The app bar is on the top.
5296 // 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.
5297 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) { // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
5298 // No padding is needed because it will automatically be placed below the app bar layout due to the scrolling layout behavior.
5299 swipeRefreshLayout.setPadding(0, 0, 0, 0)
5301 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5302 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10, defaultProgressViewEndOffset)
5303 } else { // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
5304 // The swipe refresh layout must be manually moved below the app bar layout.
5305 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0)
5307 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5308 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight)
5312 // Reset the list of resource requests.
5313 nestedScrollWebView.clearResourceRequests()
5315 // Reset the requests counters.
5316 nestedScrollWebView.resetRequestsCounters()
5318 // Get the current page position.
5319 val currentPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
5321 // Update the URL text bar if the page is currently selected and the URL edit text is not currently being edited.
5322 if ((tabLayout.selectedTabPosition == currentPagePosition) && !urlEditText.hasFocus()) {
5323 // Display the formatted URL text.
5324 urlEditText.setText(url)
5326 // Highlight the URL syntax.
5327 UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
5329 // Hide the keyboard.
5330 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.windowToken, 0)
5333 // Reset the list of host IP addresses.
5334 nestedScrollWebView.currentIpAddresses = ""
5336 // Get a URI for the current URL.
5337 val currentUri = Uri.parse(url)
5339 // Get the current domain name.
5340 val currentDomainName = currentUri.host
5342 // Get the IP addresses for the current domain.
5343 if (!currentDomainName.isNullOrEmpty())
5344 GetHostIpAddressesCoroutine.checkPinnedMismatch(currentDomainName, nestedScrollWebView, supportFragmentManager, getString(R.string.pinned_mismatch))
5346 // 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.)
5347 if ((optionsMenu != null) && (webView == currentWebView)) {
5349 optionsRefreshMenuItem.setTitle(R.string.stop)
5351 // Set the icon if it is displayed in the AppBar.
5352 if (displayAdditionalAppBarIcons)
5353 optionsRefreshMenuItem.setIcon(R.drawable.close_blue)
5357 override fun onPageFinished(webView: WebView, url: String) {
5358 // Flush any cookies to persistent storage. The cookie manager has become very lazy about flushing cookies in recent versions.
5359 if (nestedScrollWebView.acceptCookies)
5360 cookieManager.flush()
5362 // Update the Refresh menu item if the options menu has been created and the WebView is currently displayed.
5363 if (optionsMenu != null && (webView == currentWebView)) {
5364 // Reset the Refresh title.
5365 optionsRefreshMenuItem.setTitle(R.string.refresh)
5367 // Reset the icon if it is displayed in the app bar.
5368 if (displayAdditionalAppBarIcons)
5369 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled)
5372 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
5373 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
5374 val privateDataDirectoryString = applicationInfo.dataDir
5376 // Clear the cache, history, and logcat if Incognito Mode is enabled.
5377 if (incognitoModeEnabled) {
5378 // Clear the cache. `true` includes disk files.
5379 nestedScrollWebView.clearCache(true)
5381 // Clear the back/forward history.
5382 nestedScrollWebView.clearHistory()
5384 // Manually delete cache folders.
5386 // Delete the main cache directory.
5387 Runtime.getRuntime().exec("rm -rf $privateDataDirectoryString/cache")
5388 } catch (exception: IOException) {
5389 // Do nothing if an error is thrown.
5392 // Clear the logcat.
5394 // Clear the logcat. `-c` clears the logcat. `-b all` clears all the buffers (instead of just crash, main, and system).
5395 Runtime.getRuntime().exec("logcat -b all -c")
5396 } catch (exception: IOException) {
5401 // Clear the `Service Worker` directory.
5403 // A string array must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
5404 Runtime.getRuntime().exec(arrayOf("rm", "-rf", "$privateDataDirectoryString/app_webview/Default/Service Worker/"))
5405 } catch (exception: IOException) {
5409 // Get the current page position.
5410 val currentPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
5412 // 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.
5413 val currentUrl = nestedScrollWebView.url
5415 // Get the current tab.
5416 val tab = tabLayout.getTabAt(currentPagePosition)
5418 // Update the URL text bar if the page is currently selected and the user is not currently typing in the URL edit text.
5419 // Crash records show that, in some crazy way, it is possible for the current URL to be blank at this point.
5420 // Probably some sort of race condition when Privacy Browser is being resumed.
5421 if ((tabLayout.selectedTabPosition == currentPagePosition) && !urlEditText.hasFocus() && (currentUrl != null)) {
5422 // Check to see if the URL is `about:blank`.
5423 if (currentUrl == "about:blank") { // The WebView is blank.
5424 // Display the hint in the URL edit text.
5425 urlEditText.setText("")
5427 // Request focus for the URL text box.
5428 urlEditText.requestFocus()
5430 // Display the keyboard.
5431 inputMethodManager.showSoftInput(urlEditText, 0)
5433 // Apply the domain settings. This clears any settings from the previous domain.
5434 applyDomainSettings(nestedScrollWebView, "", resetTab = true, reloadWebsite = false, loadUrl = false)
5436 // Only populate the title text view if the tab has been fully created.
5438 // Get the custom view from the tab.
5439 val tabView = tab.customView!!
5441 // Get the title text view from the tab.
5442 val tabTitleTextView = tabView.findViewById<TextView>(R.id.title_textview)
5444 // Set the title as the tab text.
5445 tabTitleTextView.setText(R.string.new_tab)
5447 } else { // The WebView has loaded a webpage.
5448 // Update the URL edit text if it is not currently being edited.
5449 if (!urlEditText.hasFocus()) {
5450 // 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.
5451 val sanitizedUrl = sanitizeUrl(currentUrl)
5453 // Display the final URL. Getting the URL from the WebView instead of using the one provided by `onPageFinished()` makes websites like YouTube function correctly.
5454 urlEditText.setText(sanitizedUrl)
5456 // Highlight the URL syntax.
5457 UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
5460 // Only populate the title text view if the tab has been fully created.
5462 // Get the custom view from the tab.
5463 val tabView = tab.customView!!
5465 // Get the title text view from the tab.
5466 val tabTitleTextView = tabView.findViewById<TextView>(R.id.title_textview)
5468 // Set the title as the tab text. Sometimes `onReceivedTitle()` is not called, especially when navigating history.
5469 tabTitleTextView.text = nestedScrollWebView.title
5475 // Handle SSL Certificate errors. Suppress the lint warning that ignoring the error might be dangerous.
5476 @SuppressLint("WebViewClientOnReceivedSslError")
5477 override fun onReceivedSslError(view: WebView, handler: SslErrorHandler, error: SslError) {
5478 // Get the current website SSL certificate.
5479 val currentWebsiteSslCertificate = error.certificate
5481 // Extract the individual pieces of information from the current website SSL certificate.
5482 val currentWebsiteIssuedToCName = currentWebsiteSslCertificate.issuedTo.cName
5483 val currentWebsiteIssuedToOName = currentWebsiteSslCertificate.issuedTo.oName
5484 val currentWebsiteIssuedToUName = currentWebsiteSslCertificate.issuedTo.uName
5485 val currentWebsiteIssuedByCName = currentWebsiteSslCertificate.issuedBy.cName
5486 val currentWebsiteIssuedByOName = currentWebsiteSslCertificate.issuedBy.oName
5487 val currentWebsiteIssuedByUName = currentWebsiteSslCertificate.issuedBy.uName
5488 val currentWebsiteSslStartDate = currentWebsiteSslCertificate.validNotBeforeDate
5489 val currentWebsiteSslEndDate = currentWebsiteSslCertificate.validNotAfterDate
5491 // Get the pinned SSL certificate.
5492 val (pinnedSslCertificateStringArray, pinnedSslCertificateDateArray) = nestedScrollWebView.getPinnedSslCertificate()
5494 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
5495 if (nestedScrollWebView.hasPinnedSslCertificate() &&
5496 (currentWebsiteIssuedToCName == pinnedSslCertificateStringArray[0]) &&
5497 (currentWebsiteIssuedToOName == pinnedSslCertificateStringArray[1]) &&
5498 (currentWebsiteIssuedToUName == pinnedSslCertificateStringArray[2]) &&
5499 (currentWebsiteIssuedByCName == pinnedSslCertificateStringArray[3]) &&
5500 (currentWebsiteIssuedByOName == pinnedSslCertificateStringArray[4]) &&
5501 (currentWebsiteIssuedByUName == pinnedSslCertificateStringArray[5]) &&
5502 (currentWebsiteSslStartDate == pinnedSslCertificateDateArray[0]) &&
5503 (currentWebsiteSslEndDate == pinnedSslCertificateDateArray[1])) {
5505 // An SSL certificate is pinned and matches the current domain certificate. Proceed to the website without displaying an error.
5507 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
5508 // Store the SSL error handler.
5509 nestedScrollWebView.sslErrorHandler = handler
5511 // Instantiate an SSL certificate error alert dialog.
5512 val sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error, nestedScrollWebView.webViewFragmentId)
5514 // 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.
5516 // Show the SSL certificate error dialog.
5517 sslCertificateErrorDialogFragment.show(supportFragmentManager, getString(R.string.ssl_certificate_error))
5518 } catch (exception: Exception) {
5519 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
5520 pendingDialogsArrayList.add(PendingDialogDataClass(sslCertificateErrorDialogFragment, getString(R.string.ssl_certificate_error)))
5526 // Check to see if the state is being restored.
5527 if (restoringState) { // The state is being restored.
5528 // Resume the nested scroll WebView JavaScript timers.
5529 nestedScrollWebView.resumeTimers()
5530 } else if (pageNumber == 0) { // The first page is being loaded.
5531 // Set this nested scroll WebView as the current WebView.
5532 currentWebView = nestedScrollWebView
5534 // Get the intent that started the app.
5535 val launchingIntent = intent
5537 // Reset the intent. This prevents a duplicate tab from being created on restart.
5540 // Get the information from the intent.
5541 val launchingIntentAction = launchingIntent.action
5542 val launchingIntentUriData = launchingIntent.data
5543 val launchingIntentStringExtra = launchingIntent.getStringExtra(Intent.EXTRA_TEXT)
5545 // Parse the launching intent URL. Suppress the suggestions of using elvis expressions as they make the logic very difficult to follow.
5546 @Suppress("IfThenToElvis") val urlToLoadString = if ((launchingIntentAction != null) && (launchingIntentAction == Intent.ACTION_WEB_SEARCH)) { // The intent contains a search string.
5547 // Sanitize the search input and convert it to a search.
5548 val encodedSearchString = try {
5549 URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8")
5550 } catch (exception: UnsupportedEncodingException) {
5554 // Add the search URL to the encodedSearchString
5555 searchURL + encodedSearchString
5556 } else if (launchingIntentUriData != null) { // The launching intent contains a URL formatted as a URI.
5557 // Get the URL from the URI.
5558 launchingIntentUriData.toString()
5559 } else if (launchingIntentStringExtra != null) { // The launching intent contains text that might be a URL.
5560 // Get the URL from the string extra.
5561 launchingIntentStringExtra
5562 } else if (urlString != "") { // The activity has been restarted.
5563 // Load the saved URL.
5565 } else { // The is no saved URL and there is no URL in the intent.
5566 // Load the homepage.
5567 sharedPreferences.getString("homepage", getString(R.string.homepage_default_value))
5570 // Load the website if not waiting for the proxy.
5571 if (waitingForProxy) { // Store the URL to be loaded in the Nested Scroll WebView.
5572 nestedScrollWebView.waitingForProxyUrlString = urlToLoadString!!
5573 } else { // Load the URL.
5574 loadUrl(nestedScrollWebView, urlToLoadString!!)
5577 // 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.
5578 // 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.
5580 } else { // This is not the first tab.
5582 loadUrl(nestedScrollWebView, urlString)
5584 // Set the focus and display the keyboard if the URL is blank.
5585 if (urlString == "") {
5586 // Request focus for the URL text box.
5587 urlEditText.requestFocus()
5589 // Create a display keyboard handler.
5590 val displayKeyboardHandler = Handler(Looper.getMainLooper())
5592 // Create a display keyboard runnable.
5593 val displayKeyboardRunnable = Runnable {
5594 // Display the keyboard.
5595 inputMethodManager.showSoftInput(urlEditText, 0)
5598 // Display the keyboard after 100 milliseconds, which leaves enough time for the tab to transition.
5599 displayKeyboardHandler.postDelayed(displayKeyboardRunnable, 100)
5604 private fun loadBookmarksFolder() {
5605 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
5606 bookmarksCursor = bookmarksDatabaseHelper!!.getBookmarksByDisplayOrder(currentBookmarksFolder)
5608 // Populate the bookmarks cursor adapter.
5609 bookmarksCursorAdapter = object : CursorAdapter(this, bookmarksCursor, false) {
5610 override fun newView(context: Context, cursor: Cursor, parent: ViewGroup): View {
5611 // Inflate the individual item layout.
5612 return layoutInflater.inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false)
5615 override fun bindView(view: View, context: Context, cursor: Cursor) {
5616 // Get handles for the views.
5617 val bookmarkFavoriteIcon = view.findViewById<ImageView>(R.id.bookmark_favorite_icon)
5618 val bookmarkNameTextView = view.findViewById<TextView>(R.id.bookmark_name)
5620 // Get the favorite icon byte array from the cursor.
5621 val favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.FAVORITE_ICON))
5623 // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
5624 val favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.size)
5626 // Display the bitmap in the bookmark favorite icon.
5627 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap)
5629 // Display the bookmark name from the cursor in the bookmark name text view.
5630 bookmarkNameTextView.text = cursor.getString(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.BOOKMARK_NAME))
5632 // Make the font bold for folders.
5633 if (cursor.getInt(cursor.getColumnIndexOrThrow(BookmarksDatabaseHelper.IS_FOLDER)) == 1)
5634 bookmarkNameTextView.typeface = Typeface.DEFAULT_BOLD
5635 else // Reset the font to default for normal bookmarks.
5636 bookmarkNameTextView.typeface = Typeface.DEFAULT
5640 // Populate the list view with the adapter.
5641 bookmarksListView.adapter = bookmarksCursorAdapter
5643 // Set the bookmarks drawer title.
5644 if (currentBookmarksFolder.isEmpty())
5645 bookmarksTitleTextView.setText(R.string.bookmarks)
5647 bookmarksTitleTextView.text = currentBookmarksFolder
5650 private fun loadUrl(nestedScrollWebView: NestedScrollWebView, url: String) {
5651 // Sanitize the URL.
5652 val urlString = sanitizeUrl(url)
5654 // Apply the domain settings and load the URL.
5655 applyDomainSettings(nestedScrollWebView, urlString, resetTab = true, reloadWebsite = false, loadUrl = true)
5658 private fun loadUrlFromTextBox() {
5659 // 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.
5660 var unformattedUrlString = urlEditText.text.toString().trim { it <= ' ' }
5662 // Create the formatted URL string.
5665 // Check to see if the unformatted URL string is a valid URL. Otherwise, convert it into a search.
5666 if (unformattedUrlString.startsWith("content://")) { // This is a content URL.
5667 // Load the entire content URL.
5668 urlString = unformattedUrlString
5669 } else if (Patterns.WEB_URL.matcher(unformattedUrlString).matches() || unformattedUrlString.startsWith("http://") || unformattedUrlString.startsWith("https://") ||
5670 unformattedUrlString.startsWith("file://")) { // This is a standard URL.
5672 // Add `https://` at the beginning if there is no protocol. Otherwise the app will segfault.
5673 if (!unformattedUrlString.startsWith("http") && !unformattedUrlString.startsWith("file://"))
5674 unformattedUrlString = "https://$unformattedUrlString"
5676 // Initialize the unformatted URL.
5677 var unformattedUrl: URL? = null
5679 // Convert the unformatted URL string to a URL.
5681 unformattedUrl = URL(unformattedUrlString)
5682 } catch (exception: MalformedURLException) {
5683 exception.printStackTrace()
5686 // Get the components of the URL.
5687 val scheme = unformattedUrl?.protocol
5688 val authority = unformattedUrl?.authority
5689 val path = unformattedUrl?.path
5690 val query = unformattedUrl?.query
5691 val fragment = unformattedUrl?.ref
5694 val uri = Uri.Builder()
5696 // Build the URI from the components of the URL.
5697 uri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment)
5699 // Decode the URI as a UTF-8 string in.
5701 urlString = URLDecoder.decode(uri.build().toString(), "UTF-8")
5702 } catch (exception: UnsupportedEncodingException) {
5703 // Do nothing. The formatted URL string will remain blank.
5705 } else if (unformattedUrlString.isNotEmpty()) { // This is not a URL, but rather a search string.
5706 // Sanitize the search input.
5707 val encodedSearchString = try {
5708 URLEncoder.encode(unformattedUrlString, "UTF-8")
5709 } catch (exception: UnsupportedEncodingException) {
5713 // Add the base search URL.
5714 urlString = searchURL + encodedSearchString
5717 // 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.
5718 urlEditText.clearFocus()
5721 loadUrl(currentWebView!!, urlString)
5724 override fun navigateHistory(url: String, steps: Int) {
5725 // Apply the domain settings.
5726 applyDomainSettings(currentWebView!!, url, resetTab = false, reloadWebsite = false, loadUrl = false)
5728 // Load the history entry.
5729 currentWebView!!.goBackOrForward(steps)
5732 override fun openFile(dialogFragment: DialogFragment) {
5734 val dialog = dialogFragment.dialog!!
5736 // Get handles for the views.
5737 val fileNameEditText = dialog.findViewById<EditText>(R.id.file_name_edittext)
5738 val mhtCheckBox = dialog.findViewById<CheckBox>(R.id.mht_checkbox)
5740 // Get the file path string.
5741 val openFilePath = fileNameEditText.text.toString()
5743 // Apply the domain settings. This resets the favorite icon and removes any domain settings.
5744 applyDomainSettings(currentWebView!!, openFilePath, resetTab = true, reloadWebsite = false, loadUrl = false)
5746 // Open the file according to the type.
5747 if (mhtCheckBox.isChecked) { // Force opening of an MHT file.
5749 // Get the MHT file input stream.
5750 val mhtFileInputStream = contentResolver.openInputStream(Uri.parse(openFilePath))
5752 // Create a temporary MHT file.
5753 val temporaryMhtFile = File.createTempFile(TEMPORARY_MHT_FILE, ".mht", cacheDir)
5755 // Get a file output stream for the temporary MHT file.
5756 val temporaryMhtFileOutputStream = FileOutputStream(temporaryMhtFile)
5758 // Create a transfer byte array.
5759 val transferByteArray = ByteArray(1024)
5761 // Create an integer to track the number of bytes read.
5764 // Copy the temporary MHT file input stream to the MHT output stream.
5765 while (mhtFileInputStream!!.read(transferByteArray).also { bytesRead = it } > 0)
5766 temporaryMhtFileOutputStream.write(transferByteArray, 0, bytesRead)
5768 // Flush the temporary MHT file output stream.
5769 temporaryMhtFileOutputStream.flush()
5771 // Close the streams.
5772 temporaryMhtFileOutputStream.close()
5773 mhtFileInputStream.close()
5775 // Load the temporary MHT file.
5776 currentWebView!!.loadUrl(temporaryMhtFile.toString())
5777 } catch (exception: Exception) {
5778 // Display a snackbar.
5779 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
5781 } else { // Let the WebView handle opening of the file.
5783 currentWebView!!.loadUrl(openFilePath)
5787 private fun openWithApp(url: String) {
5788 // Create an open with app intent with `ACTION_VIEW`.
5789 val openWithAppIntent = Intent(Intent.ACTION_VIEW)
5791 // Set the URI but not the MIME type. This should open all available apps.
5792 openWithAppIntent.data = Uri.parse(url)
5794 // Flag the intent to open in a new task.
5795 openWithAppIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
5799 // Show the chooser.
5800 startActivity(openWithAppIntent)
5801 } catch (exception: ActivityNotFoundException) { // There are no apps available to open the URL.
5802 // Show a snackbar with the error.
5803 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
5807 private fun openWithBrowser(url: String) {
5809 // Create an open with browser intent with `ACTION_VIEW`.
5810 val openWithBrowserIntent = Intent(Intent.ACTION_VIEW)
5812 // Set the URI and the MIME type. `"text/html"` should load browser options.
5813 openWithBrowserIntent.setDataAndType(Uri.parse(url), "text/html")
5815 // Flag the intent to open in a new task.
5816 openWithBrowserIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
5820 // Show the chooser.
5821 startActivity(openWithBrowserIntent)
5822 } catch (exception: ActivityNotFoundException) { // There are no browsers available to open the URL.
5823 // Show a snackbar with the error.
5824 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
5828 override fun pinnedErrorGoBack() {
5829 // Get the current web back forward list.
5830 val webBackForwardList = currentWebView!!.copyBackForwardList()
5832 // Get the previous entry URL.
5833 val previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex - 1).url
5835 // Apply the domain settings.
5836 applyDomainSettings(currentWebView!!, previousUrl, resetTab = false, reloadWebsite = false, loadUrl = false)
5839 currentWebView!!.goBack()
5842 private fun sanitizeUrl(urlString: String): String {
5843 // Initialize a sanitized URL string.
5844 var sanitizedUrlString = urlString
5846 // Sanitize tracking queries.
5847 if (sanitizeTrackingQueries)
5848 sanitizedUrlString = SanitizeUrlHelper.sanitizeTrackingQueries(sanitizedUrlString)
5850 // Sanitize AMP redirects.
5851 if (sanitizeAmpRedirects)
5852 sanitizedUrlString = SanitizeUrlHelper.sanitizeAmpRedirects(sanitizedUrlString)
5854 // Return the sanitized URL string.
5855 return sanitizedUrlString
5858 override fun saveUrl(originalUrlString: String, fileNameString: String, dialogFragment: DialogFragment) {
5859 // Store the URL. This will be used in the save URL activity result launcher.
5860 saveUrlString = if (originalUrlString.startsWith("data:")) {
5861 // Save the original URL.
5865 val dialog = dialogFragment.dialog!!
5867 // Get a handle for the dialog URL edit text.
5868 val dialogUrlEditText = dialog.findViewById<EditText>(R.id.url_edittext)
5870 // Get the URL from the edit text, which may have been modified.
5871 dialogUrlEditText.text.toString()
5874 // Open the file picker.
5875 saveUrlActivityResultLauncher.launch(fileNameString)
5878 private fun setCurrentWebView(pageNumber: Int) {
5879 // Stop the swipe to refresh indicator if it is running
5880 swipeRefreshLayout.isRefreshing = false
5882 // Get the WebView tab fragment.
5883 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(pageNumber)
5885 // Get the fragment view.
5886 val webViewFragmentView = webViewTabFragment.view
5888 // Set the current WebView if the fragment view is not null.
5889 if (webViewFragmentView != null) { // The fragment has been populated.
5890 // Store the current WebView.
5891 currentWebView = webViewFragmentView.findViewById(R.id.nestedscroll_webview)
5893 // Update the status of swipe to refresh.
5894 if (currentWebView!!.swipeToRefresh) { // Swipe to refresh is enabled.
5895 // Enable the swipe refresh layout if the WebView is scrolled all the way to the top. It is updated every time the scroll changes.
5896 swipeRefreshLayout.isEnabled = (currentWebView!!.scrollY == 0)
5897 } else { // Swipe to refresh is disabled.
5898 // Disable the swipe refresh layout.
5899 swipeRefreshLayout.isEnabled = false
5902 // Set the cookie status.
5903 cookieManager.setAcceptCookie(currentWebView!!.acceptCookies)
5905 // Update the privacy icons. `true` redraws the icons in the app bar.
5906 updatePrivacyIcons(true)
5908 // Get a handle for the input method manager.
5909 val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
5911 // Get the current URL.
5912 val urlString = currentWebView!!.url
5914 // Update the URL edit text if not loading a new intent. Otherwise, this will be handled by `onPageStarted()` (if called) and `onPageFinished()`.
5915 if (!loadingNewIntent) { // A new intent is not being loaded.
5916 if ((urlString == null) || (urlString == "about:blank")) { // The WebView is blank.
5917 // Display the hint in the URL edit text.
5918 urlEditText.setText("")
5920 // Request focus for the URL text box.
5921 urlEditText.requestFocus()
5923 // Display the keyboard.
5924 inputMethodManager.showSoftInput(urlEditText, 0)
5925 } else { // The WebView has a loaded URL.
5926 // Clear the focus from the URL text box.
5927 urlEditText.clearFocus()
5929 // Hide the soft keyboard.
5930 inputMethodManager.hideSoftInputFromWindow(currentWebView!!.windowToken, 0)
5932 // Display the current URL in the URL text box.
5933 urlEditText.setText(urlString)
5935 // Highlight the URL syntax.
5936 UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
5938 } else { // A new intent is being loaded.
5939 // Reset the loading new intent flag.
5940 loadingNewIntent = false
5943 // Set the background to indicate the domain settings status.
5944 if (currentWebView!!.domainSettingsApplied) {
5945 // Set a background on the URL relative layout to indicate that custom domain settings are being used.
5946 urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.drawable.domain_settings_url_background)
5948 // Remove any background on the URL relative layout.
5949 urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.color.transparent)
5951 } else if ((pageNumber == savedTabPosition) || (pageNumber >= (webViewStateAdapter!!.itemCount - 1))) { // The tab has not been populated yet.
5952 // Try again in 100 milliseconds if the app is being restored or the a new tab has been added (the last tab).
5953 // Create a handler to set the current WebView.
5954 val setCurrentWebViewHandler = Handler(Looper.getMainLooper())
5956 // Create a runnable to set the current WebView.
5957 val setCurrentWebWebRunnable = Runnable {
5958 // Set the current WebView.
5959 setCurrentWebView(pageNumber)
5962 // Try setting the current WebView again after 100 milliseconds.
5963 setCurrentWebViewHandler.postDelayed(setCurrentWebWebRunnable, 100)
5967 // The view parameter cannot be removed because it is called from the layout onClick.
5968 fun toggleBookmarksDrawerPinned(@Suppress("UNUSED_PARAMETER")view: View?) {
5969 // Toggle the bookmarks drawer pinned tracker.
5970 bookmarksDrawerPinned = !bookmarksDrawerPinned
5972 // Update the bookmarks drawer pinned image view.
5973 updateBookmarksDrawerPinnedImageView()
5976 private fun updateBookmarksDrawerPinnedImageView() {
5977 // Set the current icon.
5978 if (bookmarksDrawerPinned)
5979 bookmarksDrawerPinnedImageView.setImageResource(R.drawable.pin_selected)
5981 bookmarksDrawerPinnedImageView.setImageResource(R.drawable.pin)
5984 private fun updateDomainsSettingsSet() {
5985 // Reset the domains settings set.
5986 domainsSettingsSet = HashSet()
5988 // Get a domains cursor.
5989 val domainsCursor = domainsDatabaseHelper!!.domainNameCursorOrderedByDomain
5991 // Get the current count of domains.
5992 val domainsCount = domainsCursor.count
5994 // Get the domain name column index.
5995 val domainNameColumnIndex = domainsCursor.getColumnIndexOrThrow(DOMAIN_NAME)
5997 // Populate the domain settings set.
5998 for (i in 0 until domainsCount) {
5999 // Move the domains cursor to the current row.
6000 domainsCursor.moveToPosition(i)
6002 // Store the domain name in the domain settings set.
6003 domainsSettingsSet.add(domainsCursor.getString(domainNameColumnIndex))
6006 // Close the domains cursor.
6007 domainsCursor.close()
6010 override fun updateFontSize(dialogFragment: DialogFragment) {
6012 val dialog = dialogFragment.dialog!!
6014 // Get a handle for the font size edit text.
6015 val fontSizeEditText = dialog.findViewById<EditText>(R.id.font_size_edittext)
6017 // Initialize the new font size variable with the current font size.
6018 var newFontSize = currentWebView!!.settings.textZoom
6020 // Get the font size from the edit text.
6022 newFontSize = fontSizeEditText.text.toString().toInt()
6023 } catch (exception: Exception) {
6024 // If the edit text does not contain a valid font size do nothing.
6027 // Apply the new font size.
6028 currentWebView!!.settings.textZoom = newFontSize
6031 private fun updatePrivacyIcons(runInvalidateOptionsMenu: Boolean) {
6032 // Only update the privacy icons if the options menu and the current WebView have already been populated.
6033 if ((optionsMenu != null) && (currentWebView != null)) {
6034 // Update the privacy icon.
6035 if (currentWebView!!.settings.javaScriptEnabled) // JavaScript is enabled.
6036 optionsPrivacyMenuItem.setIcon(R.drawable.javascript_enabled)
6037 else if (currentWebView!!.acceptCookies) // JavaScript is disabled but cookies are enabled.
6038 optionsPrivacyMenuItem.setIcon(R.drawable.warning)
6039 else // All the dangerous features are disabled.
6040 optionsPrivacyMenuItem.setIcon(R.drawable.privacy_mode)
6042 // Update the cookies icon.
6043 if (currentWebView!!.acceptCookies)
6044 optionsCookiesMenuItem.setIcon(R.drawable.cookies_enabled)
6046 optionsCookiesMenuItem.setIcon(R.drawable.cookies_disabled)
6048 // Update the refresh icon.
6049 if (optionsRefreshMenuItem.title == getString(R.string.refresh)) // The refresh icon is displayed.
6050 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled)
6051 else // The stop icon is displayed.
6052 optionsRefreshMenuItem.setIcon(R.drawable.close_blue)
6054 // `invalidateOptionsMenu()` calls `onPrepareOptionsMenu()` and redraws the icons in the app bar.
6055 if (runInvalidateOptionsMenu)
6056 invalidateOptionsMenu()