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