2 * Copyright 2015-2024 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.widget.AdapterView
80 import android.widget.ArrayAdapter
81 import android.widget.CheckBox
82 import android.widget.EditText
83 import android.widget.FrameLayout
84 import android.widget.ImageView
85 import android.widget.LinearLayout
86 import android.widget.ListView
87 import android.widget.ProgressBar
88 import android.widget.RadioButton
89 import android.widget.RadioGroup
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.AppCompatActivity
97 import androidx.appcompat.app.AppCompatDelegate
98 import androidx.appcompat.content.res.AppCompatResources
99 import androidx.appcompat.widget.Toolbar
100 import androidx.coordinatorlayout.widget.CoordinatorLayout
101 import androidx.core.content.ContextCompat
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.recyclerview.widget.LinearLayoutManager
108 import androidx.recyclerview.widget.RecyclerView
109 import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
110 import androidx.viewpager2.widget.ViewPager2
111 import androidx.webkit.WebSettingsCompat
112 import androidx.webkit.WebViewFeature
114 import com.google.android.material.appbar.AppBarLayout
115 import com.google.android.material.floatingactionbutton.FloatingActionButton
116 import com.google.android.material.navigation.NavigationView
117 import com.google.android.material.snackbar.Snackbar
118 import com.google.android.material.tabs.TabLayout
120 import com.stoutner.privacybrowser.R
121 import com.stoutner.privacybrowser.adapters.WebViewStateAdapter
122 import com.stoutner.privacybrowser.coroutines.GetHostIpAddressesCoroutine
123 import com.stoutner.privacybrowser.coroutines.PopulateFilterListsCoroutine
124 import com.stoutner.privacybrowser.coroutines.PrepareSaveDialogCoroutine
125 import com.stoutner.privacybrowser.coroutines.SaveUrlCoroutine
126 import com.stoutner.privacybrowser.coroutines.SaveWebpageImageCoroutine
127 import com.stoutner.privacybrowser.dataclasses.PendingDialogDataClass
128 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog
129 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog
130 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog
131 import com.stoutner.privacybrowser.dialogs.FontSizeDialog
132 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog
133 import com.stoutner.privacybrowser.dialogs.OpenDialog
134 import com.stoutner.privacybrowser.dialogs.PinnedMismatchDialog
135 import com.stoutner.privacybrowser.dialogs.ProxyNotInstalledDialog
136 import com.stoutner.privacybrowser.dialogs.SaveDialog
137 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog
138 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog
139 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog
140 import com.stoutner.privacybrowser.dialogs.WaitingForProxyDialog
141 import com.stoutner.privacybrowser.fragments.WebViewTabFragment
142 import com.stoutner.privacybrowser.helpers.BOOKMARK_NAME
143 import com.stoutner.privacybrowser.helpers.BOOKMARK_URL
144 import com.stoutner.privacybrowser.helpers.COOKIES
145 import com.stoutner.privacybrowser.helpers.DARK_THEME
146 import com.stoutner.privacybrowser.helpers.DISABLED
147 import com.stoutner.privacybrowser.helpers.DISPLAY_IMAGES
148 import com.stoutner.privacybrowser.helpers.DOMAIN_NAME
149 import com.stoutner.privacybrowser.helpers.ENABLE_DOM_STORAGE
150 import com.stoutner.privacybrowser.helpers.ENABLE_EASYLIST
151 import com.stoutner.privacybrowser.helpers.ENABLE_EASYPRIVACY
152 import com.stoutner.privacybrowser.helpers.ENABLE_FANBOYS_ANNOYANCE_LIST
153 import com.stoutner.privacybrowser.helpers.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST
154 import com.stoutner.privacybrowser.helpers.ENABLE_JAVASCRIPT
155 import com.stoutner.privacybrowser.helpers.ENABLE_ULTRAPRIVACY
156 import com.stoutner.privacybrowser.helpers.ENABLED
157 import com.stoutner.privacybrowser.helpers.FAVORITE_ICON
158 import com.stoutner.privacybrowser.helpers.FOLDER_ID
159 import com.stoutner.privacybrowser.helpers.FONT_SIZE
160 import com.stoutner.privacybrowser.helpers.ID
161 import com.stoutner.privacybrowser.helpers.IP_ADDRESSES
162 import com.stoutner.privacybrowser.helpers.IS_FOLDER
163 import com.stoutner.privacybrowser.helpers.LIGHT_THEME
164 import com.stoutner.privacybrowser.helpers.PINNED_IP_ADDRESSES
165 import com.stoutner.privacybrowser.helpers.PINNED_SSL_CERTIFICATE
166 import com.stoutner.privacybrowser.helpers.REQUEST_ALLOWED
167 import com.stoutner.privacybrowser.helpers.REQUEST_BLOCKED
168 import com.stoutner.privacybrowser.helpers.REQUEST_DEFAULT
169 import com.stoutner.privacybrowser.helpers.REQUEST_THIRD_PARTY
170 import com.stoutner.privacybrowser.helpers.SSL_ISSUED_BY_COMMON_NAME
171 import com.stoutner.privacybrowser.helpers.SSL_ISSUED_BY_ORGANIZATION
172 import com.stoutner.privacybrowser.helpers.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT
173 import com.stoutner.privacybrowser.helpers.SSL_ISSUED_TO_COMMON_NAME
174 import com.stoutner.privacybrowser.helpers.SSL_ISSUED_TO_ORGANIZATION
175 import com.stoutner.privacybrowser.helpers.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT
176 import com.stoutner.privacybrowser.helpers.SWIPE_TO_REFRESH
177 import com.stoutner.privacybrowser.helpers.SYSTEM_DEFAULT
178 import com.stoutner.privacybrowser.helpers.WEBVIEW_THEME
179 import com.stoutner.privacybrowser.helpers.WIDE_VIEWPORT
180 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper
181 import com.stoutner.privacybrowser.helpers.CheckFilterListHelper
182 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper
183 import com.stoutner.privacybrowser.helpers.ProxyHelper
184 import com.stoutner.privacybrowser.helpers.SanitizeUrlHelper
185 import com.stoutner.privacybrowser.helpers.UrlHelper
186 import com.stoutner.privacybrowser.views.BLOCKED_REQUESTS
187 import com.stoutner.privacybrowser.views.EASYLIST
188 import com.stoutner.privacybrowser.views.EASYPRIVACY
189 import com.stoutner.privacybrowser.views.FANBOYS_ANNOYANCE_LIST
190 import com.stoutner.privacybrowser.views.FANBOYS_SOCIAL_BLOCKING_LIST
191 import com.stoutner.privacybrowser.views.THIRD_PARTY_REQUESTS
192 import com.stoutner.privacybrowser.views.ULTRAPRIVACY
193 import com.stoutner.privacybrowser.views.NestedScrollWebView
195 import kotlinx.coroutines.CoroutineScope
196 import kotlinx.coroutines.Dispatchers
197 import kotlinx.coroutines.launch
198 import kotlinx.coroutines.withContext
200 import java.io.ByteArrayInputStream
201 import java.io.ByteArrayOutputStream
203 import java.io.FileInputStream
204 import java.io.FileOutputStream
205 import java.io.IOException
206 import java.io.UnsupportedEncodingException
208 import java.net.MalformedURLException
210 import java.net.URLDecoder
211 import java.net.URLEncoder
213 import java.text.NumberFormat
215 import java.util.ArrayList
216 import java.util.Date
217 import java.util.concurrent.Executors
218 import kotlin.system.exitProcess
220 // Define the public constants
221 const val CURRENT_URL = "current_url"
222 const val DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0
223 const val DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2
224 const val DOMAINS_CUSTOM_USER_AGENT = 12
225 const val SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1
226 const val SETTINGS_CUSTOM_USER_AGENT = 11
227 const val UNRECOGNIZED_USER_AGENT = -1
229 // Define the private class constants.
230 private const val BOOKMARKS_DRAWER_PINNED = "bookmarks_drawer_pinned"
231 private const val PROXY_MODE = "proxy_mode"
232 private const val SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST = "saved_nested_scroll_webview_state_array_list"
233 private const val SAVED_STATE_ARRAY_LIST = "saved_state_array_list"
234 private const val SAVED_TAB_POSITION = "saved_tab_position"
235 private const val TEMPORARY_MHT_FILE = "temporary_mht_file"
237 class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener, FontSizeDialog.UpdateFontSizeListener,
238 NavigationView.OnNavigationItemSelectedListener, OpenDialog.OpenListener, PinnedMismatchDialog.PinnedMismatchListener, PopulateFilterListsCoroutine.PopulateFilterListsListener, SaveDialog.SaveListener,
239 UrlHistoryDialog.NavigateHistoryListener, WebViewTabFragment.NewTabListener {
242 // Define the public static variables.
243 var currentBookmarksFolderId = 0L
244 val executorService = Executors.newFixedThreadPool(4)!!
245 var orbotStatus = "unknown"
246 val pendingDialogsArrayList = ArrayList<PendingDialogDataClass>()
247 var proxyMode = ProxyHelper.NONE
248 var restartFromBookmarksActivity = false
249 var webViewStateAdapter: WebViewStateAdapter? = null
251 // Declare the public static variables.
252 lateinit var appBarLayout: AppBarLayout
253 lateinit var defaultFavoriteIconBitmap : Bitmap
256 // Declare the class variables.
257 private lateinit var appBar: ActionBar
258 private lateinit var checkFilterListHelper: CheckFilterListHelper
259 private lateinit var bookmarksCursorAdapter: CursorAdapter
260 private lateinit var bookmarksListView: ListView
261 private lateinit var bookmarksDrawerPinnedImageView: ImageView
262 private lateinit var bookmarksTitleTextView: TextView
263 private lateinit var coordinatorLayout: CoordinatorLayout
264 private lateinit var cookieManager: CookieManager
265 private lateinit var defaultFontSizeString: String
266 private lateinit var defaultUserAgentName: String
267 private lateinit var defaultWebViewTheme: String
268 private lateinit var domainsSettingsSet: MutableSet<String>
269 private lateinit var drawerLayout: DrawerLayout
270 private lateinit var easyList: ArrayList<List<Array<String>>>
271 private lateinit var easyPrivacy: ArrayList<List<Array<String>>>
272 private lateinit var fanboysAnnoyanceList: ArrayList<List<Array<String>>>
273 private lateinit var fanboysSocialList: ArrayList<List<Array<String>>>
274 private lateinit var fileChooserCallback: ValueCallback<Array<Uri>>
275 private lateinit var finalGrayColorSpan: ForegroundColorSpan
276 private lateinit var findOnPageCountTextView: TextView
277 private lateinit var findOnPageEditText: EditText
278 private lateinit var findOnPageLinearLayout: LinearLayout
279 private lateinit var fullScreenVideoFrameLayout: FrameLayout
280 private lateinit var initialGrayColorSpan: ForegroundColorSpan
281 private lateinit var inputMethodManager: InputMethodManager
282 private lateinit var navigationBackMenuItem: MenuItem
283 private lateinit var navigationForwardMenuItem: MenuItem
284 private lateinit var navigationHistoryMenuItem: MenuItem
285 private lateinit var navigationRequestsMenuItem: MenuItem
286 private lateinit var navigationScrollToBottomMenuItem: MenuItem
287 private lateinit var navigationView: NavigationView
288 private lateinit var optionsAddOrEditDomainMenuItem: MenuItem
289 private lateinit var optionsBlockAllThirdPartyRequestsMenuItem: MenuItem
290 private lateinit var optionsClearCookiesMenuItem: MenuItem
291 private lateinit var optionsClearDataMenuItem: MenuItem
292 private lateinit var optionsClearDomStorageMenuItem: MenuItem
293 private lateinit var optionsCookiesMenuItem: MenuItem
294 private lateinit var optionsDarkWebViewMenuItem: MenuItem
295 private lateinit var optionsDisplayImagesMenuItem: MenuItem
296 private lateinit var optionsDomStorageMenuItem: MenuItem
297 private lateinit var optionsEasyListMenuItem: MenuItem
298 private lateinit var optionsEasyPrivacyMenuItem: MenuItem
299 private lateinit var optionsFanboysAnnoyanceListMenuItem: MenuItem
300 private lateinit var optionsFanboysSocialBlockingListMenuItem: MenuItem
301 private lateinit var optionsFilterListsMenuItem: MenuItem
302 private lateinit var optionsFontSizeMenuItem: MenuItem
303 private lateinit var optionsPrivacyMenuItem: MenuItem
304 private lateinit var optionsProxyCustomMenuItem: MenuItem
305 private lateinit var optionsProxyI2pMenuItem: MenuItem
306 private lateinit var optionsProxyMenuItem: MenuItem
307 private lateinit var optionsProxyNoneMenuItem: MenuItem
308 private lateinit var optionsProxyTorMenuItem: MenuItem
309 private lateinit var optionsRefreshMenuItem: MenuItem
310 private lateinit var optionsSwipeToRefreshMenuItem: MenuItem
311 private lateinit var optionsUltraListMenuItem: MenuItem
312 private lateinit var optionsUltraPrivacyMenuItem: MenuItem
313 private lateinit var optionsUserAgentChromeOnAndroidMenuItem: MenuItem
314 private lateinit var optionsUserAgentChromeOnWindowsMenuItem: MenuItem
315 private lateinit var optionsUserAgentChromiumOnLinuxMenuItem: MenuItem
316 private lateinit var optionsUserAgentCustomMenuItem: MenuItem
317 private lateinit var optionsUserAgentEdgeOnWindowsMenuItem: MenuItem
318 private lateinit var optionsUserAgentFirefoxOnAndroidMenuItem: MenuItem
319 private lateinit var optionsUserAgentFirefoxOnLinuxMenuItem: MenuItem
320 private lateinit var optionsUserAgentFirefoxOnWindowsMenuItem: MenuItem
321 private lateinit var optionsUserAgentMenuItem: MenuItem
322 private lateinit var optionsUserAgentPrivacyBrowserMenuItem: MenuItem
323 private lateinit var optionsUserAgentSafariOnIosMenuItem: MenuItem
324 private lateinit var optionsUserAgentSafariOnMacosMenuItem: MenuItem
325 private lateinit var optionsUserAgentWebViewDefaultMenuItem: MenuItem
326 private lateinit var optionsViewSourceMenuItem: MenuItem
327 private lateinit var optionsWideViewportMenuItem: MenuItem
328 private lateinit var proxyHelper: ProxyHelper
329 private lateinit var redColorSpan: ForegroundColorSpan
330 private lateinit var rootFrameLayout: FrameLayout
331 private lateinit var saveUrlString: String
332 private lateinit var searchURL: String
333 private lateinit var sharedPreferences: SharedPreferences
334 private lateinit var swipeRefreshLayout: SwipeRefreshLayout
335 private lateinit var tabLayout: TabLayout
336 private lateinit var tabsLinearLayout: LinearLayout
337 private lateinit var toolbar: Toolbar
338 private lateinit var webViewDefaultUserAgent: String
339 private lateinit var webViewThemeEntryValuesStringArray: Array<String>
340 private lateinit var webViewViewPager2: ViewPager2
341 private lateinit var ultraList: ArrayList<List<Array<String>>>
342 private lateinit var urlEditText: EditText
343 private lateinit var urlRelativeLayout: RelativeLayout
344 private lateinit var userAgentDataArray: Array<String>
345 private lateinit var userAgentNamesArray: Array<String>
346 private lateinit var userAgentDataArrayAdapter: ArrayAdapter<CharSequence>
347 private lateinit var userAgentNamesArrayAdapter: ArrayAdapter<CharSequence>
349 // Define the class variables.
350 private var appBarHeight = 0
351 private var bookmarksCursor: Cursor? = null
352 private var bookmarksDatabaseHelper: BookmarksDatabaseHelper? = null
353 private var bookmarksDrawerPinned = false
354 private var bottomAppBar = false
355 private var currentWebView: NestedScrollWebView? = null
356 private var defaultBlockAllThirdPartyRequests = false
357 private var defaultCookies = false
358 private var defaultDisplayWebpageImages = true
359 private var defaultDomStorage = false
360 private var defaultEasyList = true
361 private var defaultEasyPrivacy = true
362 private var defaultFanboysAnnoyanceList = true
363 private var defaultFanboysSocialBlockingList = true
364 private var defaultProgressViewEndOffset = 0
365 private var defaultProgressViewStartOffset = 0
366 private var defaultJavaScript = false
367 private var defaultSwipeToRefresh = true
368 private var defaultUltraList = true
369 private var defaultUltraPrivacy = true
370 private var defaultWideViewport = true
371 private var displayAdditionalAppBarIcons = false
372 private var displayingFullScreenVideo = false
373 private var domainsDatabaseHelper: DomainsDatabaseHelper? = null
374 private var downloadWithExternalApp = false
375 private var fullScreenBrowsingModeEnabled = false
376 private var hideAppBar = true
377 private var inFullScreenBrowsingMode = false
378 private var incognitoModeEnabled = false
379 private var loadingNewIntent = false
380 private var navigationDrawerFirstView = true
381 private var objectAnimator = ObjectAnimator()
382 private var optionsMenu: Menu? = null
383 private var orbotStatusBroadcastReceiver: BroadcastReceiver? = null
384 private var reapplyAppSettingsOnRestart = false
385 private var reapplyDomainSettingsOnRestart = false
386 private var sanitizeAmpRedirects = false
387 private var sanitizeTrackingQueries = false
388 private var savedProxyMode: String? = null
389 private var savedNestedScrollWebViewStateArrayList: ArrayList<Bundle>? = null
390 private var savedStateArrayList: ArrayList<Bundle>? = null
391 private var savedTabPosition = 0
392 private var scrollAppBar = false
393 private var ultraPrivacy: ArrayList<List<Array<String>>>? = null
394 private var waitingForProxy = false
396 // Define the browse file upload activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
397 private val browseFileUploadActivityResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { activityResult ->
398 // Pass the file to the WebView.
399 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(activityResult.resultCode, activityResult.data))
402 // Define the save URL activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
403 private val saveUrlActivityResultLauncher = registerForActivityResult(ActivityResultContracts.CreateDocument("*/*")) { fileUri ->
404 // Only save the URL if the file URI is not null, which happens if the user exited the file picker by pressing back.
405 if (fileUri != null) {
406 // Instantiate the save URL coroutine.
407 val saveUrlCoroutine = SaveUrlCoroutine()
410 saveUrlCoroutine.save(this, this, saveUrlString, fileUri, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
413 // Reset the save URL string.
417 // Define the save webpage archive activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
418 private val saveWebpageArchiveActivityResultLauncher = registerForActivityResult(ActivityResultContracts.CreateDocument("multipart/related")) { fileUri ->
419 // Only save the webpage archive if the file URI is not null, which happens if the user exited the file picker by pressing back.
420 if (fileUri != null) {
421 // Get a cursor from the content resolver.
422 val contentResolverCursor = contentResolver.query(fileUri, null, null, null)!!
424 // Move to the fist row.
425 contentResolverCursor.moveToFirst()
427 // Get the file name from the cursor.
428 val fileNameString = contentResolverCursor.getString(contentResolverCursor.getColumnIndexOrThrow(OpenableColumns.DISPLAY_NAME))
431 contentResolverCursor.close()
433 // Use a coroutine to save the file.
434 CoroutineScope(Dispatchers.Main).launch {
436 // Create the file on the IO thread.
437 withContext(Dispatchers.IO) {
438 // Create a temporary MHT file.
439 val temporaryMhtFile = File.createTempFile(TEMPORARY_MHT_FILE, ".mht", cacheDir)
441 // The WebView must be accessed from the main thread.
442 withContext(Dispatchers.Main) {
443 currentWebView!!.saveWebArchive(temporaryMhtFile.toString(), false) { callbackValue ->
444 if (callbackValue != null) { // The temporary MHT file was saved successfully.
446 // Create a temporary MHT file input stream.
447 val temporaryMhtFileInputStream = FileInputStream(temporaryMhtFile)
449 // Get an output stream for the save webpage file path.
450 val mhtOutputStream = contentResolver.openOutputStream(fileUri)!!
452 // Create a transfer byte array.
453 val transferByteArray = ByteArray(1024)
455 // Create an integer to track the number of bytes read.
458 // Copy the temporary MHT file input stream to the MHT output stream.
459 while (temporaryMhtFileInputStream.read(transferByteArray).also { bytesRead = it } > 0)
460 mhtOutputStream.write(transferByteArray, 0, bytesRead)
462 // Close the streams.
463 mhtOutputStream.close()
464 temporaryMhtFileInputStream.close()
466 // Display a snackbar.
467 Snackbar.make(currentWebView!!, getString(R.string.saved, fileNameString), Snackbar.LENGTH_SHORT).show()
468 } catch (exception: Exception) {
469 // Display snackbar with the exception.
470 Snackbar.make(currentWebView!!, getString(R.string.error_saving_file, fileNameString, exception), Snackbar.LENGTH_INDEFINITE).show()
472 // Delete the temporary MHT file.
473 temporaryMhtFile.delete()
475 } else { // There was an unspecified error while saving the temporary MHT file.
476 // Display a snackbar.
477 Snackbar.make(currentWebView!!, getString(R.string.error_saving_file, fileNameString, getString(R.string.unknown_error)), Snackbar.LENGTH_INDEFINITE).show()
482 } catch (ioException: IOException) {
483 // Display a snackbar with the IO exception.
484 Snackbar.make(currentWebView!!, getString(R.string.error_saving_file, fileNameString, ioException), Snackbar.LENGTH_INDEFINITE).show()
490 // Define the save webpage image activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
491 private val saveWebpageImageActivityResultLauncher = registerForActivityResult(ActivityResultContracts.CreateDocument("image/png")) { fileUri ->
492 // Only save the webpage image if the file URI is not null, which happens if the user exited the file picker by pressing back.
493 if (fileUri != null) {
494 // Instantiate the save webpage image coroutine.
495 val saveWebpageImageCoroutine = SaveWebpageImageCoroutine()
497 // Save the webpage image.
498 saveWebpageImageCoroutine.save(this, fileUri, currentWebView!!)
502 override fun onCreate(savedInstanceState: Bundle?) {
503 // Run the default commands.
504 super.onCreate(savedInstanceState)
506 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
507 PreferenceManager.setDefaultValues(this, R.xml.preferences, false)
509 // Get a handle for the shared preferences.
510 sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
512 // Get the preferences.
513 val appTheme = sharedPreferences.getString(getString(R.string.app_theme_key), getString(R.string.app_theme_default_value))
514 val allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false)
515 bottomAppBar = sharedPreferences.getBoolean(getString(R.string.bottom_app_bar_key), false)
516 displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false)
517 val displayUnderCutouts = sharedPreferences.getBoolean(getString(R.string.display_under_cutouts_key), false)
519 // Display under cutouts if specified. This must be done here as it doesn't appear to work correctly if handled after the app is fully initialized.
520 if (displayUnderCutouts) {
521 if (Build.VERSION.SDK_INT >= 30)
522 window.attributes.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS
523 else if (Build.VERSION.SDK_INT >= 28)
524 window.attributes.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
527 // Get the entry values string arrays.
528 val appThemeEntryValuesStringArray = resources.getStringArray(R.array.app_theme_entry_values)
530 // Get the current theme status.
531 val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
533 // 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.
534 if (appTheme == appThemeEntryValuesStringArray[1]) { // The light theme is selected.
535 // Apply the light theme.
536 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
537 } else if (appTheme == appThemeEntryValuesStringArray[2]) { // The dark theme is selected.
538 // Apply the dark theme.
539 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
540 } else { // The system default theme is selected.
541 if (Build.VERSION.SDK_INT >= 28) { // The system default theme is supported.
542 // Follow the system default theme.
543 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
544 } else { // The system default theme is not supported.
545 // Follow the battery saver mode.
546 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY)
550 // Do not continue if the app theme is different than the OS theme. The app always initially starts in the OS theme.
551 // 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.
552 // 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.
553 // See https://redmine.stoutner.com/issues/952.
554 if ((appTheme == appThemeEntryValuesStringArray[0]) || // The system default theme is used.
555 ((appTheme == appThemeEntryValuesStringArray[1]) && (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO)) || // The app is running in day theme as desired.
556 ((appTheme == appThemeEntryValuesStringArray[2]) && (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES))) { // The app is running in night theme as desired.
558 // Disable screenshots if not allowed.
559 if (!allowScreenshots) {
560 window.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
563 // Check to see if the activity has been restarted.
564 if (savedInstanceState != null) {
565 // Store the saved instance state variables. The deprecated `getParcelableArrayList` can be upgraded once the minimum API >= 33.
566 bookmarksDrawerPinned = savedInstanceState.getBoolean(BOOKMARKS_DRAWER_PINNED)
567 @Suppress("DEPRECATION")
568 savedStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_STATE_ARRAY_LIST)
569 @Suppress("DEPRECATION")
570 savedNestedScrollWebViewStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST)
571 savedTabPosition = savedInstanceState.getInt(SAVED_TAB_POSITION)
572 savedProxyMode = savedInstanceState.getString(PROXY_MODE)
575 // 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.
576 WebView.enableSlowWholeDocumentDraw()
578 // Set the content view according to the position of the app bar.
580 setContentView(R.layout.main_framelayout_bottom_appbar)
582 setContentView(R.layout.main_framelayout_top_appbar)
584 // Get handles for the views.
585 rootFrameLayout = findViewById(R.id.root_framelayout)
586 drawerLayout = findViewById(R.id.drawerlayout)
587 coordinatorLayout = findViewById(R.id.coordinatorlayout)
588 appBarLayout = findViewById(R.id.appbar_layout)
589 toolbar = findViewById(R.id.toolbar)
590 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout)
591 findOnPageEditText = findViewById(R.id.find_on_page_edittext)
592 findOnPageCountTextView = findViewById(R.id.find_on_page_count_textview)
593 tabsLinearLayout = findViewById(R.id.tabs_linearlayout)
594 tabLayout = findViewById(R.id.tablayout)
595 swipeRefreshLayout = findViewById(R.id.swiperefreshlayout)
596 webViewViewPager2 = findViewById(R.id.webview_viewpager2)
597 navigationView = findViewById(R.id.navigationview)
598 bookmarksListView = findViewById(R.id.bookmarks_drawer_listview)
599 bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview)
600 bookmarksDrawerPinnedImageView = findViewById(R.id.bookmarks_drawer_pinned_imageview)
601 fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout)
603 // Get a handle for the navigation menu.
604 val navigationMenu = navigationView.menu
606 // Get handles for the navigation menu items.
607 navigationBackMenuItem = navigationMenu.findItem(R.id.back)
608 navigationForwardMenuItem = navigationMenu.findItem(R.id.forward)
609 navigationScrollToBottomMenuItem = navigationMenu.findItem(R.id.scroll_to_bottom)
610 navigationHistoryMenuItem = navigationMenu.findItem(R.id.history)
611 navigationRequestsMenuItem = navigationMenu.findItem(R.id.requests)
613 // Listen for touches on the navigation menu.
614 navigationView.setNavigationItemSelectedListener(this)
616 // Set the support action bar.
617 setSupportActionBar(toolbar)
619 // Get a handle for the app bar.
620 appBar = supportActionBar!!
622 // Set the custom app bar layout, which shows the URL text bar.
623 appBar.setCustomView(R.layout.url_app_bar)
625 // Display the custom app bar layout.
626 appBar.displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM
628 // Get handles for the views in the URL app bar.
629 urlRelativeLayout = findViewById(R.id.url_relativelayout)
630 urlEditText = findViewById(R.id.url_edittext)
632 // Initially disable the sliding drawers. They will be enabled once the filter lists are loaded.
633 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
635 // Initially hide the user interface so that only the filter list loading screen is shown (if reloading).
636 drawerLayout.visibility = View.GONE
638 // Initialize the WebView state adapter.
639 webViewStateAdapter = WebViewStateAdapter(this, bottomAppBar)
641 // Set the WebView pager adapter.
642 webViewViewPager2.adapter = webViewStateAdapter
644 // Store up to 100 tabs in memory.
645 webViewViewPager2.offscreenPageLimit = 100
647 // Disable swiping between pages in the view pager.
648 webViewViewPager2.isUserInputEnabled = false
650 // Get a handle for the cookie manager.
651 cookieManager = CookieManager.getInstance()
653 // Instantiate the helpers.
654 bookmarksDatabaseHelper = BookmarksDatabaseHelper(this)
655 domainsDatabaseHelper = DomainsDatabaseHelper(this)
656 proxyHelper = ProxyHelper()
658 // Update the bookmarks drawer pinned image view.
659 updateBookmarksDrawerPinnedImageView()
661 // Get the default favorite icon drawable.
662 val favoriteIconDrawable = AppCompatResources.getDrawable(this, R.drawable.world)
664 // Cast the favorite icon drawable to a bitmap drawable.
665 val favoriteIconBitmapDrawable = (favoriteIconDrawable as BitmapDrawable?)!!
667 // Store the default favorite icon bitmap.
668 defaultFavoriteIconBitmap = favoriteIconBitmapDrawable.bitmap
670 // Initialize the app.
673 // Apply the app settings from the shared preferences.
676 // Control what the system back command does.
677 val onBackPressedCallback: OnBackPressedCallback = object : OnBackPressedCallback(true) {
678 override fun handleOnBackPressed() {
679 // Process the different back options.
680 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
681 // Close the navigation drawer.
682 drawerLayout.closeDrawer(GravityCompat.START)
683 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)) { // The bookmarks drawer is open.
684 // close the bookmarks drawer.
685 drawerLayout.closeDrawer(GravityCompat.END)
686 } else if (displayingFullScreenVideo) { // A full screen video is shown.
687 // Exit the full screen video.
688 exitFullScreenVideo()
689 // It shouldn't be possible for the currentWebView to be null, but crash logs indicate it sometimes happens.
690 } else if (currentWebView != null && currentWebView!!.canGoBack()) { // There is at least one item in the current WebView history.
691 // Navigate back one page.
693 } else { // Close the current tab.
694 // A view is required because the method is also called by an XML `onClick`.
700 // Register the on back pressed callback.
701 onBackPressedDispatcher.addCallback(this, onBackPressedCallback)
703 // Instantiate the populate filter lists coroutine.
704 val populateFilterListsCoroutine = PopulateFilterListsCoroutine(this)
706 // Populate the filter lists.
707 populateFilterListsCoroutine.populateFilterLists(this)
711 override fun onNewIntent(intent: Intent) {
712 // Run the default commands.
713 super.onNewIntent(intent)
715 // Close the navigation drawer if it is open.
716 if (drawerLayout.isDrawerVisible(GravityCompat.START))
717 drawerLayout.closeDrawer(GravityCompat.START)
719 // Close the bookmarks drawer if it is open.
720 if (drawerLayout.isDrawerVisible(GravityCompat.END))
721 drawerLayout.closeDrawer(GravityCompat.END)
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 addNewPage(url!!, adjacent = false, moveToTab = true)
766 } else { // Load the URL in the current tab.
768 loadUrl(currentWebView!!, url!!)
771 } else { // The app has been restarted.
772 // Replace the intent that started the app with this one. This will load the tab after the others have been restored.
777 public override fun onRestart() {
778 // Run the default commands.
781 // Apply the app settings if returning from the Settings activity.
782 if (reapplyAppSettingsOnRestart) {
783 // Reset the reapply app settings on restart flag.
784 reapplyAppSettingsOnRestart = false
786 // Apply the app settings.
790 // Apply the domain settings if returning from the settings or domains activity.
791 if (reapplyDomainSettingsOnRestart) {
792 // Reset the reapply domain settings on restart flag.
793 reapplyDomainSettingsOnRestart = false
795 // Update the domains settings set.
796 updateDomainsSettingsSet()
798 // Reapply the domain settings for each tab.
799 for (i in 0 until webViewStateAdapter!!.itemCount) {
800 // Get the WebView tab fragment.
801 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
803 // Get the fragment view.
804 val fragmentView = webViewTabFragment.view
806 // Only reload the WebViews if they exist.
807 if (fragmentView != null) {
808 // Get the nested scroll WebView from the tab fragment.
809 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
811 // Reset the current domain name so the domain settings will be reapplied.
812 nestedScrollWebView.currentDomainName = ""
814 // Reapply the domain settings if the URL is not null, which happens for empty tabs when returning from settings.
815 if (nestedScrollWebView.url != null)
816 applyDomainSettings(nestedScrollWebView, nestedScrollWebView.url, resetTab = false, reloadWebsite = true, loadUrl = false)
821 // Update the bookmarks drawer if returning from the Bookmarks activity.
822 if (restartFromBookmarksActivity) {
823 // Reset the restart from bookmarks activity flag.
824 restartFromBookmarksActivity = false
826 // Close the bookmarks drawer.
827 drawerLayout.closeDrawer(GravityCompat.END)
829 // Reload the bookmarks drawer.
830 loadBookmarksFolder()
833 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
834 updatePrivacyIcons(true)
837 // `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.
838 public override fun onStart() {
839 // Run the default commands.
842 // 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.
843 if (webViewStateAdapter != null) {
844 for (i in 0 until webViewStateAdapter!!.itemCount) {
845 // Get the WebView tab fragment.
846 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
848 // Get the fragment view.
849 val fragmentView = webViewTabFragment.view
851 // Only resume the WebViews if they exist (they won't when the app is first created).
852 if (fragmentView != null) {
853 // Get the nested scroll WebView from the tab fragment.
854 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
856 // Resume the nested scroll WebView.
857 nestedScrollWebView.onResume()
862 // Resume the nested scroll WebView JavaScript timers. This is a global command that resumes JavaScript timers on all WebViews.
863 if (currentWebView != null)
864 currentWebView!!.resumeTimers()
866 // Reapply the proxy settings if the system is using a proxy. This redisplays the appropriate alert dialog.
867 if (proxyMode != ProxyHelper.NONE)
870 // Reapply any system UI flags.
871 if (displayingFullScreenVideo || inFullScreenBrowsingMode) { // The system is displaying a website or a video in full screen mode.
872 /* Hide the system bars.
873 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
874 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
875 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
876 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
879 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
880 @Suppress("DEPRECATION")
881 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
884 // Show any pending dialogs.
885 for (i in pendingDialogsArrayList.indices) {
886 // Get the pending dialog from the array list.
887 val (dialogFragment, tag) = pendingDialogsArrayList[i]
889 // Show the pending dialog.
890 dialogFragment.show(supportFragmentManager, tag)
893 // Clear the pending dialogs array list.
894 pendingDialogsArrayList.clear()
897 public override fun onSaveInstanceState(outState: Bundle) {
898 // Run the default commands.
899 super.onSaveInstanceState(outState)
901 // 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.
902 if (webViewStateAdapter != null) {
903 // Initialize the saved state array lists.
904 savedStateArrayList = ArrayList<Bundle>()
905 savedNestedScrollWebViewStateArrayList = ArrayList<Bundle>()
907 // Get the URLs from each tab.
908 for (i in 0 until webViewStateAdapter!!.itemCount) {
909 // Get the WebView tab fragment.
910 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
912 // Get the fragment view.
913 val fragmentView = webViewTabFragment.view
915 // Save the fragment state if it is not null.
916 if (fragmentView != null) {
917 // Get the nested scroll WebView from the tab fragment.
918 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
920 // Create the saved state bundle.
921 val savedStateBundle = Bundle()
923 // Get the current states.
924 nestedScrollWebView.saveState(savedStateBundle)
925 val savedNestedScrollWebViewStateBundle = nestedScrollWebView.saveNestedScrollWebViewState()
927 // Store the saved states in the array lists.
928 savedStateArrayList!!.add(savedStateBundle)
929 savedNestedScrollWebViewStateArrayList!!.add(savedNestedScrollWebViewStateBundle)
933 // Get the current tab position.
934 val currentTabPosition = tabLayout.selectedTabPosition
936 // Store the saved states in the bundle.
937 outState.putBoolean(BOOKMARKS_DRAWER_PINNED, bookmarksDrawerPinned)
938 outState.putString(PROXY_MODE, proxyMode)
939 outState.putParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST, savedNestedScrollWebViewStateArrayList)
940 outState.putParcelableArrayList(SAVED_STATE_ARRAY_LIST, savedStateArrayList)
941 outState.putInt(SAVED_TAB_POSITION, currentTabPosition)
945 // `onStop()` runs after `onPause()`. It is used instead of `onPause()` so the commands are not called every time the screen is partially hidden.
946 public override fun onStop() {
947 // Run the default commands.
950 // 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.
951 if (webViewStateAdapter != null) {
952 // Pause each web view.
953 for (i in 0 until webViewStateAdapter!!.itemCount) {
954 // Get the WebView tab fragment.
955 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
957 // Get the fragment view.
958 val fragmentView = webViewTabFragment.view
960 // Only pause the WebViews if they exist (they won't when the app is first created).
961 if (fragmentView != null) {
962 // Get the nested scroll WebView from the tab fragment.
963 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
965 // Pause the nested scroll WebView.
966 nestedScrollWebView.onPause()
971 // Pause the WebView JavaScript timers. This is a global command that pauses JavaScript on all WebViews.
972 if (currentWebView != null)
973 currentWebView!!.pauseTimers()
976 public override fun onDestroy() {
977 // Unregister the orbot status broadcast receiver if it exists.
978 if (orbotStatusBroadcastReceiver != null) {
979 unregisterReceiver(orbotStatusBroadcastReceiver)
982 // Close the bookmarks cursor if it exists.
983 bookmarksCursor?.close()
985 // Close the databases if they exist.
986 bookmarksDatabaseHelper?.close()
987 domainsDatabaseHelper?.close()
989 // Run the default commands.
993 override fun onConfigurationChanged(newConfig: Configuration) {
994 // Run the default commands.
995 super.onConfigurationChanged(newConfig)
997 // Reset the navigation drawer first view flag.
998 navigationDrawerFirstView = true
1000 // Get the current page.
1001 val currentPage = webViewViewPager2.currentItem
1003 // Toggle the pages if there is more than one so that the view pager will recalculate their size.
1004 if (currentPage > 0) {
1005 // Switch to the previous page after 25 milliseconds.
1006 webViewViewPager2.postDelayed ({ webViewViewPager2.currentItem = (currentPage - 1) }, 25)
1008 // Switch back to the current page after the view pager has quiesced (which we are deciding should be 25 milliseconds).
1009 webViewViewPager2.postDelayed ({ webViewViewPager2.currentItem = currentPage }, 25)
1012 // Scroll to the current tab position after 25 milliseconds.
1013 tabLayout.postDelayed ({ tabLayout.setScrollPosition(currentPage, 0F, false, false) }, 25)
1016 override fun onCreateOptionsMenu(menu: Menu): Boolean {
1017 // Inflate the menu. This adds items to the app bar if it is present.
1018 menuInflater.inflate(R.menu.webview_options_menu, menu)
1020 // Get handles for the menu items.
1021 optionsPrivacyMenuItem = menu.findItem(R.id.javascript)
1022 optionsRefreshMenuItem = menu.findItem(R.id.refresh)
1023 val optionsBookmarksMenuItem = menu.findItem(R.id.bookmarks)
1024 optionsCookiesMenuItem = menu.findItem(R.id.cookies)
1025 optionsDomStorageMenuItem = menu.findItem(R.id.dom_storage)
1026 optionsClearDataMenuItem = menu.findItem(R.id.clear_data)
1027 optionsClearCookiesMenuItem = menu.findItem(R.id.clear_cookies)
1028 optionsClearDomStorageMenuItem = menu.findItem(R.id.clear_dom_storage)
1029 optionsEasyListMenuItem = menu.findItem(R.id.easylist)
1030 optionsEasyPrivacyMenuItem = menu.findItem(R.id.easyprivacy)
1031 optionsFanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list)
1032 optionsFanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list)
1033 optionsFilterListsMenuItem = menu.findItem(R.id.filterlists)
1034 optionsUltraListMenuItem = menu.findItem(R.id.ultralist)
1035 optionsUltraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy)
1036 optionsBlockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests)
1037 optionsProxyMenuItem = menu.findItem(R.id.proxy)
1038 optionsProxyNoneMenuItem = menu.findItem(R.id.proxy_none)
1039 optionsProxyTorMenuItem = menu.findItem(R.id.proxy_tor)
1040 optionsProxyI2pMenuItem = menu.findItem(R.id.proxy_i2p)
1041 optionsProxyCustomMenuItem = menu.findItem(R.id.proxy_custom)
1042 optionsUserAgentMenuItem = menu.findItem(R.id.user_agent)
1043 optionsUserAgentPrivacyBrowserMenuItem = menu.findItem(R.id.user_agent_privacy_browser)
1044 optionsUserAgentWebViewDefaultMenuItem = menu.findItem(R.id.user_agent_webview_default)
1045 optionsUserAgentFirefoxOnAndroidMenuItem = menu.findItem(R.id.user_agent_firefox_on_android)
1046 optionsUserAgentChromeOnAndroidMenuItem = menu.findItem(R.id.user_agent_chrome_on_android)
1047 optionsUserAgentSafariOnIosMenuItem = menu.findItem(R.id.user_agent_safari_on_ios)
1048 optionsUserAgentFirefoxOnLinuxMenuItem = menu.findItem(R.id.user_agent_firefox_on_linux)
1049 optionsUserAgentChromiumOnLinuxMenuItem = menu.findItem(R.id.user_agent_chromium_on_linux)
1050 optionsUserAgentFirefoxOnWindowsMenuItem = menu.findItem(R.id.user_agent_firefox_on_windows)
1051 optionsUserAgentChromeOnWindowsMenuItem = menu.findItem(R.id.user_agent_chrome_on_windows)
1052 optionsUserAgentEdgeOnWindowsMenuItem = menu.findItem(R.id.user_agent_edge_on_windows)
1053 optionsUserAgentSafariOnMacosMenuItem = menu.findItem(R.id.user_agent_safari_on_macos)
1054 optionsUserAgentCustomMenuItem = menu.findItem(R.id.user_agent_custom)
1055 optionsSwipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh)
1056 optionsWideViewportMenuItem = menu.findItem(R.id.wide_viewport)
1057 optionsDisplayImagesMenuItem = menu.findItem(R.id.display_images)
1058 optionsDarkWebViewMenuItem = menu.findItem(R.id.dark_webview)
1059 optionsFontSizeMenuItem = menu.findItem(R.id.font_size)
1060 optionsViewSourceMenuItem = menu.findItem(R.id.view_source)
1061 optionsAddOrEditDomainMenuItem = menu.findItem(R.id.add_or_edit_domain)
1063 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1064 updatePrivacyIcons(false)
1066 // 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.
1067 if (displayAdditionalAppBarIcons) { // Display the additional icons.
1068 optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
1069 optionsBookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM)
1070 optionsCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM)
1071 } else { //Do not display the additional icons.
1072 optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER)
1073 optionsBookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER)
1074 optionsCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER)
1077 // Replace `Refresh` with `Stop` if a URL is already loading.
1078 if ((currentWebView != null) && (currentWebView!!.progress != 100)) {
1080 optionsRefreshMenuItem.setTitle(R.string.stop)
1082 // Set the icon if it is displayed in the app bar.
1083 if (displayAdditionalAppBarIcons)
1084 optionsRefreshMenuItem.setIcon(R.drawable.close_blue)
1087 // Store a handle for the options menu.
1094 override fun onPrepareOptionsMenu(menu: Menu): Boolean {
1095 // Initialize the current user agent string and the font size.
1096 var currentUserAgent = getString(R.string.user_agent_privacy_browser)
1099 // 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.
1100 if (currentWebView != null) {
1101 // Set the add or edit domain text.
1102 if (currentWebView!!.domainSettingsApplied)
1103 optionsAddOrEditDomainMenuItem.setTitle(R.string.edit_domain_settings)
1105 optionsAddOrEditDomainMenuItem.setTitle(R.string.add_domain_settings)
1107 // Get the current user agent from the WebView.
1108 currentUserAgent = currentWebView!!.settings.userAgentString
1110 // Get the current font size from the the WebView.
1111 fontSize = currentWebView!!.settings.textZoom
1113 // Set the status of the menu item checkboxes.
1114 optionsDomStorageMenuItem.isChecked = currentWebView!!.settings.domStorageEnabled
1115 optionsEasyListMenuItem.isChecked = currentWebView!!.easyListEnabled
1116 optionsEasyPrivacyMenuItem.isChecked = currentWebView!!.easyPrivacyEnabled
1117 optionsFanboysAnnoyanceListMenuItem.isChecked = currentWebView!!.fanboysAnnoyanceListEnabled
1118 optionsFanboysSocialBlockingListMenuItem.isChecked = currentWebView!!.fanboysSocialBlockingListEnabled
1119 optionsUltraListMenuItem.isChecked = currentWebView!!.ultraListEnabled
1120 optionsUltraPrivacyMenuItem.isChecked = currentWebView!!.ultraPrivacyEnabled
1121 optionsBlockAllThirdPartyRequestsMenuItem.isChecked = currentWebView!!.blockAllThirdPartyRequests
1122 optionsSwipeToRefreshMenuItem.isChecked = currentWebView!!.swipeToRefresh
1123 optionsWideViewportMenuItem.isChecked = currentWebView!!.settings.useWideViewPort
1124 optionsDisplayImagesMenuItem.isChecked = currentWebView!!.settings.loadsImagesAutomatically
1126 // Set the display names for the filter lists with the number of blocked requests.
1127 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + currentWebView!!.getRequestsCount(BLOCKED_REQUESTS)
1128 optionsEasyListMenuItem.title = currentWebView!!.getRequestsCount(EASYLIST).toString() + " - " + getString(R.string.easylist)
1129 optionsEasyPrivacyMenuItem.title = currentWebView!!.getRequestsCount(EASYPRIVACY).toString() + " - " + getString(R.string.easyprivacy)
1130 optionsFanboysAnnoyanceListMenuItem.title = currentWebView!!.getRequestsCount(FANBOYS_ANNOYANCE_LIST).toString() + " - " + getString(R.string.fanboys_annoyance_list)
1131 optionsFanboysSocialBlockingListMenuItem.title = currentWebView!!.getRequestsCount(FANBOYS_SOCIAL_BLOCKING_LIST).toString() + " - " + getString(R.string.fanboys_social_blocking_list)
1132 optionsUltraListMenuItem.title = currentWebView!!.getRequestsCount(com.stoutner.privacybrowser.views.ULTRALIST).toString() + " - " + getString(R.string.ultralist)
1133 optionsUltraPrivacyMenuItem.title = currentWebView!!.getRequestsCount(ULTRAPRIVACY).toString() + " - " + getString(R.string.ultraprivacy)
1134 optionsBlockAllThirdPartyRequestsMenuItem.title = currentWebView!!.getRequestsCount(THIRD_PARTY_REQUESTS).toString() + " - " + getString(R.string.block_all_third_party_requests)
1136 // Enable DOM Storage if JavaScript is enabled.
1137 optionsDomStorageMenuItem.isEnabled = currentWebView!!.settings.javaScriptEnabled
1139 // Get the current theme status.
1140 val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
1142 // Enable dark WebView if night mode is enabled.
1143 optionsDarkWebViewMenuItem.isEnabled = (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES)
1145 // Set the checkbox status for dark WebView if algorithmic darkening is supported.
1146 if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING))
1147 optionsDarkWebViewMenuItem.isChecked = WebSettingsCompat.isAlgorithmicDarkeningAllowed(currentWebView!!.settings)
1149 // Set the view source title according to the current URL.
1150 if (currentWebView!!.currentUrl.startsWith("view-source:"))
1151 optionsViewSourceMenuItem.title = getString(R.string.view_rendered_website)
1153 optionsViewSourceMenuItem.title = getString(R.string.view_source)
1156 // Set the cookies menu item checked status.
1157 optionsCookiesMenuItem.isChecked = cookieManager.acceptCookie()
1159 // Enable Clear Cookies if there are any.
1160 optionsClearCookiesMenuItem.isEnabled = cookieManager.hasCookies()
1162 // 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`.
1163 val privateDataDirectoryString = applicationInfo.dataDir
1165 // Get the storage directories.
1166 val localStorageDirectory = File("$privateDataDirectoryString/app_webview/Local Storage/")
1167 val indexedDBDirectory = File("$privateDataDirectoryString/app_webview/IndexedDB")
1169 // Initialize the number of files counters.
1170 var localStorageDirectoryNumberOfFiles = 0
1171 var indexedDBDirectoryNumberOfFiles = 0
1173 // 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.
1174 if (localStorageDirectory.exists())
1175 localStorageDirectoryNumberOfFiles = (localStorageDirectory.list())?.size ?: 0
1177 // Get a count of the number of files in the IndexedDB directory. The list can be null, in which case a `0` is returned.
1178 if (indexedDBDirectory.exists())
1179 indexedDBDirectoryNumberOfFiles = (indexedDBDirectory.list())?.size ?: 0
1181 // Enable Clear DOM Storage if there is any.
1182 optionsClearDomStorageMenuItem.isEnabled = localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0
1184 // Enable Clear Data if any of the submenu items are enabled.
1185 optionsClearDataMenuItem.isEnabled = (optionsClearCookiesMenuItem.isEnabled || optionsClearDomStorageMenuItem.isEnabled)
1187 // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
1188 optionsFanboysSocialBlockingListMenuItem.isEnabled = !optionsFanboysAnnoyanceListMenuItem.isChecked
1190 // Set the proxy title and check the applied proxy.
1192 ProxyHelper.NONE -> {
1193 // Set the proxy title.
1194 optionsProxyMenuItem.title = getString(R.string.proxy) + " - " + getString(R.string.proxy_none)
1196 // Check the proxy None radio button.
1197 optionsProxyNoneMenuItem.isChecked = true
1200 ProxyHelper.TOR -> {
1201 // Set the proxy title.
1202 optionsProxyMenuItem.title = getString(R.string.proxy) + " - " + getString(R.string.proxy_tor)
1204 // Check the proxy Tor radio button.
1205 optionsProxyTorMenuItem.isChecked = true
1208 ProxyHelper.I2P -> {
1209 // Set the proxy title.
1210 optionsProxyMenuItem.title = getString(R.string.proxy) + " - " + getString(R.string.proxy_i2p)
1212 // Check the proxy I2P radio button.
1213 optionsProxyI2pMenuItem.isChecked = true
1216 ProxyHelper.CUSTOM -> {
1217 // Set the proxy title.
1218 optionsProxyMenuItem.title = getString(R.string.proxy) + " - " + getString(R.string.proxy_custom)
1220 // Check the proxy Custom radio button.
1221 optionsProxyCustomMenuItem.isChecked = true
1225 // Select the current user agent menu item.
1226 when (currentUserAgent) {
1227 resources.getStringArray(R.array.user_agent_data)[0] -> { // Privacy Browser.
1228 // Update the user agent menu item title.
1229 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_privacy_browser)
1231 // Select the Privacy Browser radio box.
1232 optionsUserAgentPrivacyBrowserMenuItem.isChecked = true
1235 webViewDefaultUserAgent -> { // WebView Default.
1236 // Update the user agent menu item title.
1237 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_webview_default)
1239 // Select the WebView Default radio box.
1240 optionsUserAgentWebViewDefaultMenuItem.isChecked = true
1243 resources.getStringArray(R.array.user_agent_data)[2] -> { // Firefox on Android.
1244 // Update the user agent menu item title.
1245 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_android)
1247 // Select the Firefox on Android radio box.
1248 optionsUserAgentFirefoxOnAndroidMenuItem.isChecked = true
1251 resources.getStringArray(R.array.user_agent_data)[3] -> { // Chrome on Android.
1252 // Update the user agent menu item title.
1253 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_android)
1255 // Select the Chrome on Android radio box.
1256 optionsUserAgentChromeOnAndroidMenuItem.isChecked = true
1259 resources.getStringArray(R.array.user_agent_data)[4] -> { // Safari on iOS.
1260 // Update the user agent menu item title.
1261 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_ios)
1263 // Select the Safari on iOS radio box.
1264 optionsUserAgentSafariOnIosMenuItem.isChecked = true
1267 resources.getStringArray(R.array.user_agent_data)[5] -> { // Firefox on Linux.
1268 // Update the user agent menu item title.
1269 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_linux)
1271 // Select the Firefox on Linux radio box.
1272 optionsUserAgentFirefoxOnLinuxMenuItem.isChecked = true
1275 resources.getStringArray(R.array.user_agent_data)[6] -> { // Chromium on Linux.
1276 // Update the user agent menu item title.
1277 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chromium_on_linux)
1279 // Select the Chromium on Linux radio box.
1280 optionsUserAgentChromiumOnLinuxMenuItem.isChecked = true
1283 resources.getStringArray(R.array.user_agent_data)[7] -> { // Firefox on Windows.
1284 // Update the user agent menu item title.
1285 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_windows)
1287 // Select the Firefox on Windows radio box.
1288 optionsUserAgentFirefoxOnWindowsMenuItem.isChecked = true
1291 resources.getStringArray(R.array.user_agent_data)[8] -> { // Chrome on Windows.
1292 // Update the user agent menu item title.
1293 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_windows)
1295 // Select the Chrome on Windows radio box.
1296 optionsUserAgentChromeOnWindowsMenuItem.isChecked = true
1299 resources.getStringArray(R.array.user_agent_data)[9] -> { // Edge on Windows.
1300 // Update the user agent menu item title.
1301 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_edge_on_windows)
1303 // Select the Edge on Windows radio box.
1304 optionsUserAgentEdgeOnWindowsMenuItem.isChecked = true
1307 resources.getStringArray(R.array.user_agent_data)[10] -> { // Safari on macOS.
1308 // Update the user agent menu item title.
1309 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_macos)
1311 // Select the Safari on macOS radio box.
1312 optionsUserAgentSafariOnMacosMenuItem.isChecked = true
1315 else -> { // Custom user agent.
1316 // Update the user agent menu item title.
1317 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_custom)
1319 // Select the Custom radio box.
1320 optionsUserAgentCustomMenuItem.isChecked = true
1324 // Set the font size title.
1325 optionsFontSizeMenuItem.title = getString(R.string.font_size) + " - " + fontSize + "%"
1327 // Run all the other default commands.
1328 super.onPrepareOptionsMenu(menu)
1330 // Display the menu.
1334 override fun onOptionsItemSelected(menuItem: MenuItem): Boolean {
1335 // Run the commands that correlate to the selected menu item.
1336 return when (menuItem.itemId) {
1337 R.id.javascript -> { // JavaScript.
1338 // Toggle the JavaScript status.
1339 currentWebView!!.settings.javaScriptEnabled = !currentWebView!!.settings.javaScriptEnabled
1341 // Update the privacy icon.
1342 updatePrivacyIcons(true)
1344 // Display a snackbar.
1345 if (currentWebView!!.settings.javaScriptEnabled) // JavaScrip is enabled.
1346 Snackbar.make(webViewViewPager2, R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show()
1347 else if (cookieManager.acceptCookie()) // JavaScript is disabled, but cookies are enabled.
1348 Snackbar.make(webViewViewPager2, R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show()
1349 else // Privacy mode.
1350 Snackbar.make(webViewViewPager2, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show()
1352 // Reload the current WebView.
1353 currentWebView!!.reload()
1355 // Consume the event.
1359 R.id.refresh -> { // Refresh.
1360 // Run the command that correlates to the current status of the menu item.
1361 if (menuItem.title == getString(R.string.refresh)) // The refresh button was pushed.
1362 currentWebView!!.reload()
1363 else // The stop button was pushed.
1364 currentWebView!!.stopLoading()
1366 // Consume the event.
1370 R.id.bookmarks -> { // Bookmarks.
1371 // Open the bookmarks drawer.
1372 drawerLayout.openDrawer(GravityCompat.END)
1374 // Consume the event.
1378 R.id.cookies -> { // Cookies.
1379 // Toggle the cookie status.
1380 cookieManager.setAcceptCookie(!cookieManager.acceptCookie())
1382 // Store the cookie status.
1383 currentWebView!!.acceptCookies = cookieManager.acceptCookie()
1385 // Update the menu checkbox.
1386 menuItem.isChecked = cookieManager.acceptCookie()
1388 // Update the privacy icon.
1389 updatePrivacyIcons(true)
1391 // Display a snackbar.
1392 if (cookieManager.acceptCookie()) // Cookies are enabled.
1393 Snackbar.make(webViewViewPager2, R.string.cookies_enabled, Snackbar.LENGTH_SHORT).show()
1394 else if (currentWebView!!.settings.javaScriptEnabled) // JavaScript is still enabled.
1395 Snackbar.make(webViewViewPager2, R.string.cookies_disabled, Snackbar.LENGTH_SHORT).show()
1396 else // Privacy mode.
1397 Snackbar.make(webViewViewPager2, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show()
1399 // Reload the current WebView.
1400 currentWebView!!.reload()
1402 // Consume the event.
1406 R.id.dom_storage -> { // DOM storage.
1407 // Toggle the DOM storage status.
1408 currentWebView!!.settings.domStorageEnabled = !currentWebView!!.settings.domStorageEnabled
1410 // Update the menu checkbox.
1411 menuItem.isChecked = currentWebView!!.settings.domStorageEnabled
1413 // Update the privacy icon.
1414 updatePrivacyIcons(true)
1416 // Display a snackbar.
1417 if (currentWebView!!.settings.domStorageEnabled)
1418 Snackbar.make(webViewViewPager2, R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show()
1420 Snackbar.make(webViewViewPager2, R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show()
1422 // Reload the current WebView.
1423 currentWebView!!.reload()
1425 // Consume the event.
1429 R.id.clear_cookies -> { // Clear cookies.
1430 // Create a snackbar.
1431 Snackbar.make(webViewViewPager2, R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1432 .setAction(R.string.undo) {} // Everything will be handled by `onDismissed()` below.
1433 .addCallback(object : Snackbar.Callback() {
1434 override fun onDismissed(snackbar: Snackbar, event: Int) {
1435 if (event != DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1436 // Delete the cookies.
1437 cookieManager.removeAllCookies(null)
1443 // Consume the event.
1447 R.id.clear_dom_storage -> { // Clear DOM storage.
1448 // Create a snackbar.
1449 Snackbar.make(webViewViewPager2, R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1450 .setAction(R.string.undo) {} // Everything will be handled by `onDismissed()` below.
1451 .addCallback(object : Snackbar.Callback() {
1452 override fun onDismissed(snackbar: Snackbar, event: Int) {
1453 if (event != DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1454 // Get a handle for the web storage.
1455 val webStorage = WebStorage.getInstance()
1457 // Delete the DOM Storage.
1458 webStorage.deleteAllData()
1460 // Initialize a handler to manually delete the DOM storage files and directories.
1461 val deleteDomStorageHandler = Handler(Looper.getMainLooper())
1463 // Setup a runnable to manually delete the DOM storage files and directories.
1464 val deleteDomStorageRunnable = Runnable {
1466 // Get a handle for the runtime.
1467 val runtime = Runtime.getRuntime()
1469 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1470 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1471 val privateDataDirectoryString = applicationInfo.dataDir
1473 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1474 val deleteLocalStorageProcess = runtime.exec(arrayOf("rm", "-rf", "$privateDataDirectoryString/app_webview/Local Storage/"))
1476 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1477 val deleteIndexProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview/IndexedDB")
1478 val deleteQuotaManagerProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/QuotaManager")
1479 val deleteQuotaManagerJournalProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/QuotaManager-journal")
1480 val deleteDatabasesProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview/databases")
1482 // Wait for the processes to finish.
1483 deleteLocalStorageProcess.waitFor()
1484 deleteIndexProcess.waitFor()
1485 deleteQuotaManagerProcess.waitFor()
1486 deleteQuotaManagerJournalProcess.waitFor()
1487 deleteDatabasesProcess.waitFor()
1488 } catch (exception: Exception) {
1489 // Do nothing if an error is thrown.
1493 // Manually delete the DOM storage files after 200 milliseconds.
1494 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200)
1500 // Consume the event.
1504 R.id.easylist -> { // EasyList.
1505 // Toggle the EasyList status.
1506 currentWebView!!.easyListEnabled = !currentWebView!!.easyListEnabled
1508 // Update the menu checkbox.
1509 menuItem.isChecked = currentWebView!!.easyListEnabled
1511 // Reload the current WebView.
1512 currentWebView!!.reload()
1514 // Consume the event.
1518 R.id.easyprivacy -> { // EasyPrivacy.
1519 // Toggle the EasyPrivacy status.
1520 currentWebView!!.easyPrivacyEnabled = !currentWebView!!.easyPrivacyEnabled
1522 // Update the menu checkbox.
1523 menuItem.isChecked = currentWebView!!.easyPrivacyEnabled
1525 // Reload the current WebView.
1526 currentWebView!!.reload()
1528 // Consume the event.
1532 R.id.fanboys_annoyance_list -> { // Fanboy's Annoyance List.
1533 // Toggle Fanboy's Annoyance List status.
1534 currentWebView!!.fanboysAnnoyanceListEnabled = !currentWebView!!.fanboysAnnoyanceListEnabled
1536 // Update the menu checkbox.
1537 menuItem.isChecked = currentWebView!!.fanboysAnnoyanceListEnabled
1539 // Update the status of Fanboy's Social Blocking List.
1540 optionsFanboysSocialBlockingListMenuItem.isEnabled = !currentWebView!!.fanboysAnnoyanceListEnabled
1542 // Reload the current WebView.
1543 currentWebView!!.reload()
1545 // Consume the event.
1549 R.id.fanboys_social_blocking_list -> { // Fanboy's Social Blocking List.
1550 // Toggle Fanboy's Social Blocking List status.
1551 currentWebView!!.fanboysSocialBlockingListEnabled = !currentWebView!!.fanboysSocialBlockingListEnabled
1553 // Update the menu checkbox.
1554 menuItem.isChecked = currentWebView!!.fanboysSocialBlockingListEnabled
1556 // Reload the current WebView.
1557 currentWebView!!.reload()
1559 // Consume the event.
1563 R.id.ultralist -> { // UltraList.
1564 // Toggle the UltraList status.
1565 currentWebView!!.ultraListEnabled = !currentWebView!!.ultraListEnabled
1567 // Update the menu checkbox.
1568 menuItem.isChecked = currentWebView!!.ultraListEnabled
1570 // Reload the current WebView.
1571 currentWebView!!.reload()
1573 // Consume the event.
1577 R.id.ultraprivacy -> { // UltraPrivacy.
1578 // Toggle the UltraPrivacy status.
1579 currentWebView!!.ultraPrivacyEnabled = !currentWebView!!.ultraPrivacyEnabled
1581 // Update the menu checkbox.
1582 menuItem.isChecked = currentWebView!!.ultraPrivacyEnabled
1584 // Reload the current WebView.
1585 currentWebView!!.reload()
1587 // Consume the event.
1591 R.id.block_all_third_party_requests -> { // Block all third-party requests.
1592 //Toggle the third-party requests blocker status.
1593 currentWebView!!.blockAllThirdPartyRequests = !currentWebView!!.blockAllThirdPartyRequests
1595 // Update the menu checkbox.
1596 menuItem.isChecked = currentWebView!!.blockAllThirdPartyRequests
1598 // Reload the current WebView.
1599 currentWebView!!.reload()
1601 // Consume the event.
1605 R.id.proxy_none -> { // Proxy - None.
1606 // Update the proxy mode.
1607 proxyMode = ProxyHelper.NONE
1609 // Apply the proxy mode.
1612 // Consume the event.
1616 R.id.proxy_tor -> { // Proxy - Tor.
1617 // Update the proxy mode.
1618 proxyMode = ProxyHelper.TOR
1620 // Apply the proxy mode.
1623 // Consume the event.
1627 R.id.proxy_i2p -> { // Proxy - I2P.
1628 // Update the proxy mode.
1629 proxyMode = ProxyHelper.I2P
1631 // Apply the proxy mode.
1634 // Consume the event.
1638 R.id.proxy_custom -> { // Proxy - Custom.
1639 // Update the proxy mode.
1640 proxyMode = ProxyHelper.CUSTOM
1642 // Apply the proxy mode.
1645 // Consume the event.
1649 R.id.user_agent_privacy_browser -> { // User Agent - Privacy Browser.
1650 // Update the user agent.
1651 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[0]
1653 // Reload the current WebView.
1654 currentWebView!!.reload()
1656 // Consume the event.
1660 R.id.user_agent_webview_default -> { // User Agent - WebView Default.
1661 // Update the user agent.
1662 currentWebView!!.settings.userAgentString = ""
1664 // Reload the current WebView.
1665 currentWebView!!.reload()
1667 // Consume the event.
1671 R.id.user_agent_firefox_on_android -> { // User Agent - Firefox on Android.
1672 // Update the user agent.
1673 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[2]
1675 // Reload the current WebView.
1676 currentWebView!!.reload()
1678 // Consume the event.
1682 R.id.user_agent_chrome_on_android -> { // User Agent - Chrome on Android.
1683 // Update the user agent.
1684 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[3]
1686 // Reload the current WebView.
1687 currentWebView!!.reload()
1689 // Consume the event.
1693 R.id.user_agent_safari_on_ios -> { // User Agent - Safari on iOS.
1694 // Update the user agent.
1695 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[4]
1697 // Reload the current WebView.
1698 currentWebView!!.reload()
1700 // Consume the event.
1704 R.id.user_agent_firefox_on_linux -> { // User Agent - Firefox on Linux.
1705 // Update the user agent.
1706 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[5]
1708 // Reload the current WebView.
1709 currentWebView!!.reload()
1711 // Consume the event.
1715 R.id.user_agent_chromium_on_linux -> { // User Agent - Chromium on Linux.
1716 // Update the user agent.
1717 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[6]
1719 // Reload the current WebView.
1720 currentWebView!!.reload()
1722 // Consume the event.
1726 R.id.user_agent_firefox_on_windows -> { // User Agent - Firefox on Windows.
1727 // Update the user agent.
1728 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[7]
1730 // Reload the current WebView.
1731 currentWebView!!.reload()
1733 // Consume the event.
1737 R.id.user_agent_chrome_on_windows -> { // User Agent - Chrome on Windows.
1738 // Update the user agent.
1739 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[8]
1741 // Reload the current WebView.
1742 currentWebView!!.reload()
1744 // Consume the event.
1748 R.id.user_agent_edge_on_windows -> { // User Agent - Edge on Windows.
1749 // Update the user agent.
1750 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[9]
1752 // Reload the current WebView.
1753 currentWebView!!.reload()
1755 // Consume the event.
1759 R.id.user_agent_safari_on_macos -> { // User Agent - Safari on macOS.
1760 // Update the user agent.
1761 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[10]
1763 // Reload the current WebView.
1764 currentWebView!!.reload()
1766 // Consume the event.
1770 R.id.user_agent_custom -> { // User Agent - Custom.
1771 // Update the user agent.
1772 currentWebView!!.settings.userAgentString = sharedPreferences.getString(getString(R.string.custom_user_agent_key), getString(R.string.custom_user_agent_default_value))
1774 // Reload the current WebView.
1775 currentWebView!!.reload()
1777 // Consume the event.
1781 R.id.font_size -> { // Font size.
1782 // Instantiate the font size dialog.
1783 val fontSizeDialogFragment: DialogFragment = FontSizeDialog.displayDialog(currentWebView!!.settings.textZoom)
1785 // Show the font size dialog.
1786 fontSizeDialogFragment.show(supportFragmentManager, getString(R.string.font_size))
1788 // Consume the event.
1792 R.id.swipe_to_refresh -> { // Swipe to refresh.
1793 // Toggle the stored status of swipe to refresh.
1794 currentWebView!!.swipeToRefresh = !currentWebView!!.swipeToRefresh
1796 // Update the swipe refresh layout.
1797 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.
1798 swipeRefreshLayout.isEnabled = currentWebView!!.scrollY == 0
1799 else // Swipe to refresh is disabled.
1800 swipeRefreshLayout.isEnabled = false
1802 // Consume the event.
1806 R.id.wide_viewport -> { // Wide viewport.
1807 // Toggle the viewport.
1808 currentWebView!!.settings.useWideViewPort = !currentWebView!!.settings.useWideViewPort
1810 // Consume the event.
1814 R.id.display_images -> { // Display images.
1815 // Toggle the displaying of images.
1816 if (currentWebView!!.settings.loadsImagesAutomatically) { // Images are currently loaded automatically.
1817 // Disable loading of images.
1818 currentWebView!!.settings.loadsImagesAutomatically = false
1820 // Reload the website to remove existing images.
1821 currentWebView!!.reload()
1822 } else { // Images are not currently loaded automatically.
1823 // Enable loading of images. Missing images will be loaded without the need for a reload.
1824 currentWebView!!.settings.loadsImagesAutomatically = true
1827 // Consume the event.
1831 R.id.dark_webview -> { // Dark WebView.
1832 // Toggle dark WebView if supported.
1833 if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING))
1834 WebSettingsCompat.setAlgorithmicDarkeningAllowed(currentWebView!!.settings, !WebSettingsCompat.isAlgorithmicDarkeningAllowed(currentWebView!!.settings)
1837 // Consume the event.
1841 R.id.find_on_page -> { // Find on page.
1842 // Set the minimum height of the find on page linear layout to match the toolbar.
1843 findOnPageLinearLayout.minimumHeight = toolbar.height
1845 // Hide the toolbar.
1846 toolbar.visibility = View.GONE
1848 // Show the find on page linear layout.
1849 findOnPageLinearLayout.visibility = View.VISIBLE
1851 // Display the keyboard. The app must wait 200 ms before running the command to work around a bug in Android.
1852 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1853 findOnPageEditText.postDelayed({
1854 // Set the focus on the find on page edit text.
1855 findOnPageEditText.requestFocus()
1857 // Display the keyboard. `0` sets no input flags.
1858 inputMethodManager.showSoftInput(findOnPageEditText, 0)
1861 // Consume the event.
1865 R.id.print -> { // Print.
1866 // Get a print manager instance.
1867 val printManager = (getSystemService(PRINT_SERVICE) as PrintManager)
1869 // Create a print document adapter from the current WebView.
1870 val printDocumentAdapter = currentWebView!!.createPrintDocumentAdapter(getString(R.string.print))
1872 // Print the document.
1873 printManager.print(getString(R.string.privacy_browser_webpage), printDocumentAdapter, null)
1875 // Consume the event.
1879 R.id.save_url -> { // Save URL.
1880 // Check the download preference.
1881 if (downloadWithExternalApp) // Download with an external app.
1882 saveWithExternalApp(currentWebView!!.currentUrl)
1883 else // Handle the download inside of Privacy Browser. The dialog will be displayed once the file size and the content disposition have been acquired.
1884 PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, currentWebView!!.currentUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
1886 // Consume the event.
1890 R.id.save_archive -> {
1891 // Open the file picker with a default file name built from the website title.
1892 saveWebpageArchiveActivityResultLauncher.launch(currentWebView!!.title + ".mht")
1894 // Consume the event.
1898 R.id.save_image -> { // Save image.
1899 // Open the file picker with a default file name built from the current domain name.
1900 saveWebpageImageActivityResultLauncher.launch(currentWebView!!.currentDomainName + ".png")
1902 // Consume the event.
1906 R.id.add_to_homescreen -> { // Add to homescreen.
1907 // Instantiate the create home screen shortcut dialog.
1908 val createHomeScreenShortcutDialogFragment: DialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView!!.title!!, currentWebView!!.url!!, currentWebView!!.getFavoriteIcon())
1910 // Show the create home screen shortcut dialog.
1911 createHomeScreenShortcutDialogFragment.show(supportFragmentManager, getString(R.string.create_shortcut))
1913 // Consume the event.
1917 R.id.view_source -> { // View source.
1918 // Open a new tab according to the current URL.
1919 if (currentWebView!!.currentUrl.startsWith("view-source:")) { // The source is currently viewed.
1920 // Open the rendered website in a new tab.
1921 addNewPage(currentWebView!!.currentUrl.substring(12, currentWebView!!.currentUrl.length), true, moveToTab = true)
1922 } else { // The rendered website is currently viewed.
1923 // Open the source in a new tab.
1924 addNewPage("view-source:${currentWebView!!.currentUrl}", adjacent = true, moveToTab = true)
1927 // Consume the event.
1931 R.id.view_headers -> { // View headers.
1932 // Create an intent to launch the view headers activity.
1933 val viewHeadersIntent = Intent(this, ViewHeadersActivity::class.java)
1935 // Add the variables to the intent.
1936 viewHeadersIntent.putExtra(CURRENT_URL, currentWebView!!.url)
1937 viewHeadersIntent.putExtra(USER_AGENT, currentWebView!!.settings.userAgentString)
1940 startActivity(viewHeadersIntent)
1942 // Consume the event.
1946 R.id.share_message -> { // Share a message.
1947 // Prepare the share string.
1948 val shareString = currentWebView!!.title + " – " + currentWebView!!.url
1950 // Create the share intent.
1951 val shareMessageIntent = Intent(Intent.ACTION_SEND)
1953 // Add the share string to the intent.
1954 shareMessageIntent.putExtra(Intent.EXTRA_TEXT, shareString)
1956 // Set the MIME type.
1957 shareMessageIntent.type = "text/plain"
1959 // Set the intent to open in a new task.
1960 shareMessageIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
1963 startActivity(Intent.createChooser(shareMessageIntent, getString(R.string.share_message)))
1965 // Consume the event.
1969 R.id.share_url -> { // Share URL.
1970 // Create the share intent.
1971 val shareUrlIntent = Intent(Intent.ACTION_SEND)
1973 // Add the URL to the intent.
1974 shareUrlIntent.putExtra(Intent.EXTRA_TEXT, currentWebView!!.url)
1976 // Add the title to the intent.
1977 shareUrlIntent.putExtra(Intent.EXTRA_SUBJECT, currentWebView!!.title)
1979 // Set the MIME type.
1980 shareUrlIntent.type = "text/plain"
1982 // Set the intent to open in a new task.
1983 shareUrlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
1986 startActivity(Intent.createChooser(shareUrlIntent, getString(R.string.share_url)))
1988 // Consume the event.
1992 R.id.open_with_app -> { // Open with app.
1993 // Open the URL with an outside app.
1994 openWithApp(currentWebView!!.url!!)
1996 // Consume the event.
2000 R.id.open_with_browser -> { // Open with browser.
2001 // Open the URL with an outside browser.
2002 openWithBrowser(currentWebView!!.url!!)
2004 // Consume the event.
2008 R.id.add_or_edit_domain -> { // Add or edit domain.
2009 // Reapply the domain settings on returning to the main WebView activity.
2010 reapplyDomainSettingsOnRestart = true
2012 // Check if domain settings are currently applied.
2013 if (currentWebView!!.domainSettingsApplied) { // Edit the current domain settings.
2014 // Create an intent to launch the domains activity.
2015 val domainsIntent = Intent(this, DomainsActivity::class.java)
2017 // Add the extra information to the intent.
2018 domainsIntent.putExtra(LOAD_DOMAIN, currentWebView!!.domainSettingsDatabaseId)
2019 domainsIntent.putExtra(CLOSE_ON_BACK, true)
2020 domainsIntent.putExtra(CURRENT_IP_ADDRESSES, currentWebView!!.currentIpAddresses)
2022 // Get the current certificate.
2023 val sslCertificate = currentWebView!!.certificate
2025 // Check to see if the SSL certificate is populated.
2026 if (sslCertificate != null) {
2027 // Extract the certificate to strings.
2028 val issuedToCName = sslCertificate.issuedTo.cName
2029 val issuedToOName = sslCertificate.issuedTo.oName
2030 val issuedToUName = sslCertificate.issuedTo.uName
2031 val issuedByCName = sslCertificate.issuedBy.cName
2032 val issuedByOName = sslCertificate.issuedBy.oName
2033 val issuedByUName = sslCertificate.issuedBy.uName
2034 val startDateLong = sslCertificate.validNotBeforeDate.time
2035 val endDateLong = sslCertificate.validNotAfterDate.time
2037 // Add the certificate to the intent.
2038 domainsIntent.putExtra(SSL_ISSUED_TO_CNAME, issuedToCName)
2039 domainsIntent.putExtra(SSL_ISSUED_TO_ONAME, issuedToOName)
2040 domainsIntent.putExtra(SSL_ISSUED_TO_UNAME, issuedToUName)
2041 domainsIntent.putExtra(SSL_ISSUED_BY_CNAME, issuedByCName)
2042 domainsIntent.putExtra(SSL_ISSUED_BY_ONAME, issuedByOName)
2043 domainsIntent.putExtra(SSL_ISSUED_BY_UNAME, issuedByUName)
2044 domainsIntent.putExtra(SSL_START_DATE, startDateLong)
2045 domainsIntent.putExtra(SSL_END_DATE, endDateLong)
2049 startActivity(domainsIntent)
2050 } else { // Add a new domain.
2051 // Get the current URI.
2052 val currentUri = Uri.parse(currentWebView!!.url)
2054 // Get the current domain from the URI. Use an empty string if it is null.
2055 val currentDomain = currentUri.host?: ""
2057 // Get the current settings status.
2058 val javaScriptInt = calculateSettingsInt(currentWebView!!.settings.javaScriptEnabled, sharedPreferences.getBoolean(getString(R.string.javascript_key), false))
2059 val cookiesInt = calculateSettingsInt(currentWebView!!.acceptCookies, sharedPreferences.getBoolean(getString(R.string.cookies_key), false))
2060 val domStorageInt = calculateSettingsInt(currentWebView!!.settings.domStorageEnabled, sharedPreferences.getBoolean(getString(R.string.dom_storage_key), false))
2061 val easyListInt = calculateSettingsInt(currentWebView!!.easyListEnabled, sharedPreferences.getBoolean(getString(R.string.easylist_key), true))
2062 val easyPrivacyInt = calculateSettingsInt(currentWebView!!.easyPrivacyEnabled, sharedPreferences.getBoolean(getString(R.string.easyprivacy_key), true))
2063 val fanboysAnnoyanceListInt = calculateSettingsInt(currentWebView!!.fanboysAnnoyanceListEnabled, sharedPreferences.getBoolean(getString(R.string.fanboys_annoyance_list_key), true))
2064 val fanboysSocialBlockingListInt = calculateSettingsInt(currentWebView!!.fanboysSocialBlockingListEnabled, sharedPreferences.getBoolean(getString(R.string.fanboys_social_blocking_list_key), true))
2065 val ultraListInt = calculateSettingsInt(currentWebView!!.ultraListEnabled, sharedPreferences.getBoolean(getString(R.string.ultralist_key), true))
2066 val ultraPrivacyInt = calculateSettingsInt(currentWebView!!.ultraPrivacyEnabled, sharedPreferences.getBoolean(getString(R.string.ultraprivacy_key), true))
2067 val blockAllThirdPartyRequestsInt = calculateSettingsInt(currentWebView!!.blockAllThirdPartyRequests, sharedPreferences.getBoolean(getString(R.string.block_all_third_party_requests_key), true))
2068 val swipeToRefreshInt = calculateSettingsInt(currentWebView!!.swipeToRefresh, sharedPreferences.getBoolean(getString(R.string.swipe_to_refresh_key), true))
2069 val wideViewportInt = calculateSettingsInt(currentWebView!!.settings.useWideViewPort, sharedPreferences.getBoolean(getString(R.string.wide_viewport_key), true))
2070 val displayImagesInt = calculateSettingsInt(currentWebView!!.settings.loadsImagesAutomatically, sharedPreferences.getBoolean(getString(R.string.display_webpage_images_key), true))
2072 // Get the current user agent string.
2073 val currentUserAgentString = currentWebView!!.settings.userAgentString
2075 // Get the user agent string array position.
2076 val userAgentStringArrayPosition = userAgentDataArrayAdapter.getPosition(currentUserAgentString)
2078 // Set the user agent name.
2079 val userAgentName = if ((userAgentStringArrayPosition >= 0) && (defaultUserAgentName == userAgentNamesArray[userAgentStringArrayPosition])) { // The system default user agent is in use.
2080 getString(R.string.system_default_user_agent)
2081 } else { // An on-the-fly user agent is being used (or the WebView default user agent is applied).
2082 when (userAgentStringArrayPosition) {
2083 UNRECOGNIZED_USER_AGENT -> { // The user agent is unrecognized.
2084 if (currentUserAgentString == webViewDefaultUserAgent) { // The WebView default user agent is being used.
2085 if (defaultUserAgentName == getString(R.string.webview_default)) { // The WebView default user agent is the system default.
2086 // Set the user agent name to be the system default.
2087 getString(R.string.system_default_user_agent)
2088 } else { // The WebView default user agent is set as an on-the-fly setting.
2089 // Set the default user agent name.
2090 getString(R.string.webview_default)
2092 } else { // A custom user agent is being used.
2093 if (defaultUserAgentName == getString(R.string.custom_user_agent_non_translatable)) { // The system custom user agent is in use.
2094 // Set the user agent name to be the system default.
2095 getString(R.string.system_default_user_agent)
2096 } else { // An on-the-fly custom user agent is in use.
2097 // Store the user agent as currently applied.
2098 currentUserAgentString
2103 else -> // Store the standard user agent name.
2104 userAgentNamesArray[userAgentStringArrayPosition]
2108 // Get the current text zoom integer.
2109 val textZoomInt = currentWebView!!.settings.textZoom
2111 // Set the font size integer.
2112 val fontSizeInt = if (textZoomInt == defaultFontSizeString.toInt()) // The current system default is used, which is encoded as a zoom of `0`.
2114 else // A custom font size is used.
2117 // Get the current WebView dark theme status.
2118 val webViewDarkThemeCurrentlyEnabled = if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) // Algorithmic darkening is supported.
2119 WebSettingsCompat.isAlgorithmicDarkeningAllowed(currentWebView!!.settings)
2120 else // Algorithmic darkening is not supported.
2123 // Get the default WebView dark theme setting.
2124 val defaultWebViewDarkThemeEnabled = if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) { // Algorithmic darkening is supported.
2125 when (defaultWebViewTheme) {
2126 webViewThemeEntryValuesStringArray[1] -> // The dark theme is disabled by default.
2129 webViewThemeEntryValuesStringArray[2] -> // The dark theme is enabled by default.
2132 else -> { // The system default theme is selected.
2133 // Get the current app theme status.
2134 val currentAppThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
2136 // Check if the current app theme is dark.
2137 currentAppThemeStatus == Configuration.UI_MODE_NIGHT_YES
2140 } else { // Algorithmic darkening is not supported.
2144 // Set the WebView theme int.
2145 val webViewThemeInt = if (webViewDarkThemeCurrentlyEnabled == defaultWebViewDarkThemeEnabled) // The current WebView theme matches the default.
2147 else if (webViewDarkThemeCurrentlyEnabled) // The current WebView theme is dark and that is not the default.
2149 else // The current WebView theme is light and that is not the default.
2152 // Create the domain and store the database ID.
2153 val newDomainDatabaseId = domainsDatabaseHelper!!.addDomain(currentDomain, javaScriptInt, cookiesInt, domStorageInt, userAgentName, easyListInt, easyPrivacyInt,
2154 fanboysAnnoyanceListInt, fanboysSocialBlockingListInt, ultraListInt, ultraPrivacyInt, blockAllThirdPartyRequestsInt, fontSizeInt,
2155 swipeToRefreshInt, webViewThemeInt, wideViewportInt, displayImagesInt)
2157 // Create an intent to launch the domains activity.
2158 val domainsIntent = Intent(this, DomainsActivity::class.java)
2160 // Add the extra information to the intent.
2161 domainsIntent.putExtra(LOAD_DOMAIN, newDomainDatabaseId)
2162 domainsIntent.putExtra(CLOSE_ON_BACK, true)
2163 domainsIntent.putExtra(CURRENT_IP_ADDRESSES, currentWebView!!.currentIpAddresses)
2165 // Get the current certificate.
2166 val sslCertificate = currentWebView!!.certificate
2168 // Check to see if the SSL certificate is populated.
2169 if (sslCertificate != null) {
2170 // Extract the certificate to strings.
2171 val issuedToCName = sslCertificate.issuedTo.cName
2172 val issuedToOName = sslCertificate.issuedTo.oName
2173 val issuedToUName = sslCertificate.issuedTo.uName
2174 val issuedByCName = sslCertificate.issuedBy.cName
2175 val issuedByOName = sslCertificate.issuedBy.oName
2176 val issuedByUName = sslCertificate.issuedBy.uName
2177 val startDateLong = sslCertificate.validNotBeforeDate.time
2178 val endDateLong = sslCertificate.validNotAfterDate.time
2180 // Add the certificate to the intent.
2181 domainsIntent.putExtra(SSL_ISSUED_TO_CNAME, issuedToCName)
2182 domainsIntent.putExtra(SSL_ISSUED_TO_ONAME, issuedToOName)
2183 domainsIntent.putExtra(SSL_ISSUED_TO_UNAME, issuedToUName)
2184 domainsIntent.putExtra(SSL_ISSUED_BY_CNAME, issuedByCName)
2185 domainsIntent.putExtra(SSL_ISSUED_BY_ONAME, issuedByOName)
2186 domainsIntent.putExtra(SSL_ISSUED_BY_UNAME, issuedByUName)
2187 domainsIntent.putExtra(SSL_START_DATE, startDateLong)
2188 domainsIntent.putExtra(SSL_END_DATE, endDateLong)
2192 startActivity(domainsIntent)
2195 // Consume the event.
2199 else -> { // There is no match with the options menu. Pass the event up to the parent method.
2200 // Don't consume the event.
2201 super.onOptionsItemSelected(menuItem)
2206 override fun onNavigationItemSelected(menuItem: MenuItem): Boolean {
2207 // Run the commands that correspond to the selected menu item.
2208 when (menuItem.itemId) {
2209 R.id.clear_and_exit -> { // Clear and exit.
2210 // Clear and exit Privacy Browser.
2214 R.id.home -> { // Home.
2215 // Load the homepage.
2216 loadUrl(currentWebView!!, sharedPreferences.getString(getString(R.string.homepage_key), getString(R.string.homepage_default_value))!!)
2219 R.id.back -> { // Back.
2220 // Check if the WebView can go back.
2221 if (currentWebView!!.canGoBack()) {
2222 // Navigate back one page.
2227 R.id.forward -> { // Forward.
2228 // Check if the WebView can go forward.
2229 if (currentWebView!!.canGoForward()) {
2230 // Navigate forward one page.
2235 R.id.scroll_to_bottom -> { // Scroll to Bottom.
2236 // Check if the WebView is scrolled to the top.
2237 if (currentWebView!!.scrollY == 0) { // The WebView is at the top; scroll to the bottom. Using a large Y number is more efficient than trying to calculate the exact WebView length.
2238 currentWebView!!.scrollTo(0, 1_000_000_000)
2239 } else { // The WebView is not at the top; scroll to the top.
2240 currentWebView!!.scrollTo(0, 0)
2244 R.id.history -> { // History.
2245 // Instantiate the URL history dialog.
2246 val urlHistoryDialogFragment: DialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView!!.webViewFragmentId)
2248 // Show the URL history dialog.
2249 urlHistoryDialogFragment.show(supportFragmentManager, getString(R.string.history))
2252 R.id.open -> { // Open.
2253 // Instantiate the open file dialog.
2254 val openDialogFragment: DialogFragment = OpenDialog()
2256 // Show the open file dialog.
2257 openDialogFragment.show(supportFragmentManager, getString(R.string.open))
2260 R.id.requests -> { // Requests.
2261 // Populate the resource requests.
2262 RequestsActivity.resourceRequests = currentWebView!!.getResourceRequests()
2264 // Create an intent to launch the Requests activity.
2265 val requestsIntent = Intent(this, RequestsActivity::class.java)
2267 // Add the block third-party requests status to the intent.
2268 requestsIntent.putExtra(BLOCK_ALL_THIRD_PARTY_REQUESTS, currentWebView!!.blockAllThirdPartyRequests)
2271 startActivity(requestsIntent)
2274 R.id.downloads -> { // Downloads.
2275 // Try the default system download manager.
2277 // Launch the default system Download Manager.
2278 val defaultDownloadManagerIntent = Intent(DownloadManager.ACTION_VIEW_DOWNLOADS)
2280 // Launch as a new task so that the download manager and Privacy Browser show as separate windows in the recent tasks list.
2281 defaultDownloadManagerIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2284 startActivity(defaultDownloadManagerIntent)
2285 } catch (defaultDownloadManagerException: Exception) { // The system download manager is not available.
2286 // Try a generic file manager.
2288 // Create a generic file manager intent.
2289 val genericFileManagerIntent = Intent(Intent.ACTION_VIEW)
2291 // Open the download directory.
2292 genericFileManagerIntent.setDataAndType(Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()), DocumentsContract.Document.MIME_TYPE_DIR)
2294 // Launch as a new task so that the file manager and Privacy Browser show as separate windows in the recent tasks list.
2295 genericFileManagerIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2298 startActivity(genericFileManagerIntent)
2299 } catch (genericFileManagerException: Exception) { // A generic file manager is not available.
2300 // Try an alternate file manager.
2302 // Create an alternate file manager intent.
2303 val alternateFileManagerIntent = Intent(Intent.ACTION_VIEW)
2305 // Open the download directory.
2306 alternateFileManagerIntent.setDataAndType(Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()), "resource/folder")
2308 // Launch as a new task so that the file manager and Privacy Browser show as separate windows in the recent tasks list.
2309 alternateFileManagerIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2311 // Open the alternate file manager.
2312 startActivity(alternateFileManagerIntent)
2313 } catch (alternateFileManagerException: Exception) {
2314 // Display a snackbar.
2315 Snackbar.make(currentWebView!!, R.string.no_file_manager_detected, Snackbar.LENGTH_INDEFINITE).show()
2321 R.id.domains -> { // Domains.
2322 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2323 reapplyDomainSettingsOnRestart = true
2325 // Create a domains activity intent.
2326 val domainsIntent = Intent(this, DomainsActivity::class.java)
2328 // Add the extra information to the intent.
2329 domainsIntent.putExtra(CURRENT_IP_ADDRESSES, currentWebView!!.currentIpAddresses)
2331 // Get the current certificate.
2332 val sslCertificate = currentWebView!!.certificate
2334 // Check to see if the SSL certificate is populated.
2335 if (sslCertificate != null) {
2336 // Extract the certificate to strings.
2337 val issuedToCName = sslCertificate.issuedTo.cName
2338 val issuedToOName = sslCertificate.issuedTo.oName
2339 val issuedToUName = sslCertificate.issuedTo.uName
2340 val issuedByCName = sslCertificate.issuedBy.cName
2341 val issuedByOName = sslCertificate.issuedBy.oName
2342 val issuedByUName = sslCertificate.issuedBy.uName
2343 val startDateLong = sslCertificate.validNotBeforeDate.time
2344 val endDateLong = sslCertificate.validNotAfterDate.time
2346 // Add the certificate to the intent.
2347 domainsIntent.putExtra(SSL_ISSUED_TO_CNAME, issuedToCName)
2348 domainsIntent.putExtra(SSL_ISSUED_TO_ONAME, issuedToOName)
2349 domainsIntent.putExtra(SSL_ISSUED_TO_UNAME, issuedToUName)
2350 domainsIntent.putExtra(SSL_ISSUED_BY_CNAME, issuedByCName)
2351 domainsIntent.putExtra(SSL_ISSUED_BY_ONAME, issuedByOName)
2352 domainsIntent.putExtra(SSL_ISSUED_BY_UNAME, issuedByUName)
2353 domainsIntent.putExtra(SSL_START_DATE, startDateLong)
2354 domainsIntent.putExtra(SSL_END_DATE, endDateLong)
2358 startActivity(domainsIntent)
2361 R.id.settings -> { // Settings.
2362 // Set the reapply on restart flags.
2363 reapplyAppSettingsOnRestart = true
2364 reapplyDomainSettingsOnRestart = true
2366 // Create a settings intent.
2367 val settingsIntent = Intent(this, SettingsActivity::class.java)
2370 startActivity(settingsIntent)
2373 R.id.import_export -> { // Import/Export.
2374 // Create an intent to launch the import/export activity.
2375 val importExportIntent = Intent(this, ImportExportActivity::class.java)
2378 startActivity(importExportIntent)
2381 R.id.logcat -> { // Logcat.
2382 // Create an intent to launch the logcat activity.
2383 val logcatIntent = Intent(this, LogcatActivity::class.java)
2386 startActivity(logcatIntent)
2389 R.id.webview_devtools -> { // WebView DevTools.
2390 // Create a WebView DevTools intent.
2391 val webViewDevToolsIntent = Intent("com.android.webview.SHOW_DEV_UI")
2393 // Launch as a new task so that the WebView DevTools and Privacy Browser show as a separate windows in the recent tasks list.
2394 webViewDevToolsIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2397 startActivity(webViewDevToolsIntent)
2400 R.id.guide -> { // Guide.
2401 // Create an intent to launch the guide activity.
2402 val guideIntent = Intent(this, GuideActivity::class.java)
2405 startActivity(guideIntent)
2408 R.id.about -> { // About
2409 // Create an intent to launch the about activity.
2410 val aboutIntent = Intent(this, AboutActivity::class.java)
2412 // Create a string array for the filter list versions.
2413 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])
2415 // Add the filter list versions to the intent.
2416 aboutIntent.putExtra(FILTERLIST_VERSIONS, filterListVersions)
2419 startActivity(aboutIntent)
2423 // Close the navigation drawer.
2424 drawerLayout.closeDrawer(GravityCompat.START)
2430 override fun onCreateContextMenu(contextMenu: ContextMenu, view: View, contextMenuInfo: ContextMenu.ContextMenuInfo?) {
2431 // Get the hit test result.
2432 val hitTestResult = currentWebView!!.hitTestResult
2434 // Define the URL strings.
2435 val imageUrl: String?
2436 val linkUrl: String?
2438 // Get a handle for the clipboard manager.
2439 val clipboardManager = (getSystemService(CLIPBOARD_SERVICE) as ClipboardManager)
2441 // Process the link according to the type.
2442 when (hitTestResult.type) {
2443 // `SRC_ANCHOR_TYPE` is a link.
2444 WebView.HitTestResult.SRC_ANCHOR_TYPE -> {
2445 // Get the target URL.
2446 linkUrl = hitTestResult.extra!!
2448 // Set the target URL as the context menu title.
2449 contextMenu.setHeaderTitle(linkUrl)
2451 // Add an open in new tab entry.
2452 contextMenu.add(R.string.open_in_new_tab).setOnMenuItemClickListener {
2453 // Load the link URL in a new tab and move to it.
2454 addNewPage(linkUrl, adjacent = true, moveToTab = true)
2456 // Consume the event.
2460 // Add an open in background entry.
2461 contextMenu.add(R.string.open_in_background).setOnMenuItemClickListener {
2462 // Load the link URL in a new tab but do not move to it.
2463 addNewPage(linkUrl, adjacent = true, moveToTab = false)
2465 // Consume the event.
2469 // Add an open with app entry.
2470 contextMenu.add(R.string.open_with_app).setOnMenuItemClickListener {
2471 // Open the URL with another app.
2472 openWithApp(linkUrl)
2474 // Consume the event.
2478 // Add an open with browser entry.
2479 contextMenu.add(R.string.open_with_browser).setOnMenuItemClickListener {
2480 // Open the URL with another browser.
2481 openWithBrowser(linkUrl)
2483 // Consume the event.
2487 // Add a copy URL entry.
2488 contextMenu.add(R.string.copy_url).setOnMenuItemClickListener {
2489 // Save the link URL in a clip data.
2490 val srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl)
2492 // Set the clip data as the clipboard's primary clip.
2493 clipboardManager.setPrimaryClip(srcAnchorTypeClipData)
2495 // Consume the event.
2499 // Add a Save URL entry.
2500 contextMenu.add(R.string.save_url).setOnMenuItemClickListener {
2501 // Check the download preference.
2502 if (downloadWithExternalApp) // Download with an external app.
2503 saveWithExternalApp(linkUrl)
2504 else // Handle the download inside of Privacy Browser. The dialog will be displayed once the file size and the content disposition have been acquired.
2505 PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, linkUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
2507 // Consume the event.
2511 // Add a Share URL entry.
2512 contextMenu.add(R.string.share_url).setOnMenuItemClickListener {
2513 // Create the share intent.
2514 val shareUrlIntent = Intent(Intent.ACTION_SEND)
2516 // Add the URL to the intent.
2517 shareUrlIntent.putExtra(Intent.EXTRA_TEXT, linkUrl)
2519 // Set the MIME type.
2520 shareUrlIntent.type = "text/plain"
2522 // Set the intent to open in a new task.
2523 shareUrlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
2526 startActivity(Intent.createChooser(shareUrlIntent, getString(R.string.share_url)))
2528 // Consume the event.
2532 // Add an empty cancel entry, which by default closes the context menu.
2533 contextMenu.add(R.string.cancel)
2536 // `IMAGE_TYPE` is an image.
2537 WebView.HitTestResult.IMAGE_TYPE -> {
2538 // Get the image URL.
2539 imageUrl = hitTestResult.extra!!
2541 // Set the context menu title.
2542 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.
2543 contextMenu.setHeaderTitle(imageUrl.substring(0, 100))
2544 else // The image URL does not contain the full image data. Set the image URL as the title of the context menu.
2545 contextMenu.setHeaderTitle(imageUrl)
2547 // Add an open in new tab entry.
2548 contextMenu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener {
2549 // Load the image in a new tab.
2550 addNewPage(imageUrl, adjacent = true, moveToTab = true)
2552 // Consume the event.
2556 // Add an open with app entry.
2557 contextMenu.add(R.string.open_with_app).setOnMenuItemClickListener {
2558 // Open the image URL with an external app.
2559 openWithApp(imageUrl)
2561 // Consume the event.
2565 // Add an open with browser entry.
2566 contextMenu.add(R.string.open_with_browser).setOnMenuItemClickListener {
2567 // Open the image URL with an external browser.
2568 openWithBrowser(imageUrl)
2570 // Consume the event.
2574 // Add a view image entry.
2575 contextMenu.add(R.string.view_image).setOnMenuItemClickListener {
2576 // Load the image in the current tab.
2577 loadUrl(currentWebView!!, imageUrl)
2579 // Consume the event.
2583 // Add a save image entry.
2584 contextMenu.add(R.string.save_image).setOnMenuItemClickListener {
2585 // Check the download preference.
2586 if (downloadWithExternalApp) { // Download with an external app.
2587 saveWithExternalApp(imageUrl)
2588 } else { // Handle the download inside of Privacy Browser. The dialog will be displayed once the file size and the content disposition have been acquired.
2589 PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, imageUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
2592 // Consume the event.
2596 // Add a copy URL entry.
2597 contextMenu.add(R.string.copy_url).setOnMenuItemClickListener {
2598 // Save the image URL in a clip data.
2599 val imageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl)
2601 // Set the clip data as the clipboard's primary clip.
2602 clipboardManager.setPrimaryClip(imageTypeClipData)
2604 // Consume the event.
2608 // Add a Share URL entry.
2609 contextMenu.add(R.string.share_url).setOnMenuItemClickListener {
2610 // Create the share intent.
2611 val shareUrlIntent = Intent(Intent.ACTION_SEND)
2613 // Add the URL to the intent.
2614 shareUrlIntent.putExtra(Intent.EXTRA_TEXT, imageUrl)
2616 // Set the MIME type.
2617 shareUrlIntent.type = "text/plain"
2619 // Set the intent to open in a new task.
2620 shareUrlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
2623 startActivity(Intent.createChooser(shareUrlIntent, getString(R.string.share_url)))
2625 // Consume the event.
2629 // Add an empty cancel entry, which by default closes the context menu.
2630 contextMenu.add(R.string.cancel)
2633 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2634 WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE -> {
2635 // Get the image URL.
2636 imageUrl = hitTestResult.extra!!
2638 // Instantiate a handler.
2639 val handler = Handler(Looper.getMainLooper())
2641 // Get a handle for the handler message.
2642 val message = handler.obtainMessage()
2644 // Request the image details from the last touched node be returned in the message.
2645 currentWebView!!.requestFocusNodeHref(message)
2647 // Get the link URL from the message data.
2648 linkUrl = message.data.getString("url")!!
2650 // Set the link URL as the title of the context menu.
2651 contextMenu.setHeaderTitle(linkUrl)
2653 // Add an open in new tab entry.
2654 contextMenu.add(R.string.open_in_new_tab).setOnMenuItemClickListener {
2655 // Load the link URL in a new tab and move to it.
2656 addNewPage(linkUrl, adjacent = true, moveToTab = true)
2658 // Consume the event.
2662 // Add an open in background entry.
2663 contextMenu.add(R.string.open_in_background).setOnMenuItemClickListener {
2664 // Lod the link URL in a new tab but do not move to it.
2665 addNewPage(linkUrl, adjacent = true, moveToTab = false)
2667 // Consume the event.
2671 // Add an open image in new tab entry.
2672 contextMenu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener {
2673 // Load the image in a new tab and move to it.
2674 addNewPage(imageUrl, adjacent = true, moveToTab = true)
2676 // Consume the event.
2680 // Add an open with app entry.
2681 contextMenu.add(R.string.open_with_app).setOnMenuItemClickListener {
2682 // Open the link URL with an external app.
2683 openWithApp(linkUrl)
2685 // Consume the event.
2689 // Add an open with browser entry.
2690 contextMenu.add(R.string.open_with_browser).setOnMenuItemClickListener {
2691 // Open the link URL with an external browser.
2692 openWithBrowser(linkUrl)
2694 // Consume the event.
2698 // Add a view image entry.
2699 contextMenu.add(R.string.view_image).setOnMenuItemClickListener {
2700 // View the image in the current tab.
2701 loadUrl(currentWebView!!, imageUrl)
2703 // Consume the event.
2707 // Add a Save Image entry.
2708 contextMenu.add(R.string.save_image).setOnMenuItemClickListener {
2709 // Check the download preference.
2710 if (downloadWithExternalApp) // Download with an external app.
2711 saveWithExternalApp(imageUrl)
2712 else // Handle the download inside of Privacy Browser. The dialog will be displayed once the file size and the content disposition have been acquired.
2713 PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, imageUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
2715 // Consume the event.
2719 // Add a Share Image entry.
2720 contextMenu.add(R.string.share_image).setOnMenuItemClickListener {
2721 // Create the share intent.
2722 val shareUrlIntent = Intent(Intent.ACTION_SEND)
2724 // Add the URL to the intent.
2725 shareUrlIntent.putExtra(Intent.EXTRA_TEXT, imageUrl)
2727 // Set the MIME type.
2728 shareUrlIntent.type = "text/plain"
2730 // Set the intent to open in a new task.
2731 shareUrlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
2734 startActivity(Intent.createChooser(shareUrlIntent, getString(R.string.share_url)))
2736 // Consume the event.
2740 // Add a copy URL entry.
2741 contextMenu.add(R.string.copy_url).setOnMenuItemClickListener {
2742 // Save the link URL in a clip data.
2743 val srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl)
2745 // Set the clip data as the clipboard's primary clip.
2746 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData)
2748 // Consume the event.
2752 // Add a save URL entry.
2753 contextMenu.add(R.string.save_url).setOnMenuItemClickListener {
2754 // Check the download preference.
2755 if (downloadWithExternalApp) // Download with an external app.
2756 saveWithExternalApp(linkUrl)
2757 else // Handle the download inside of Privacy Browser. The dialog will be displayed once the file size and the content disposition have been acquired.
2758 PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, linkUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
2760 // Consume the event.
2764 // Add a Share URL entry.
2765 contextMenu.add(R.string.share_url).setOnMenuItemClickListener {
2766 // Create the share intent.
2767 val shareUrlIntent = Intent(Intent.ACTION_SEND)
2769 // Add the URL to the intent.
2770 shareUrlIntent.putExtra(Intent.EXTRA_TEXT, linkUrl)
2772 // Set the MIME type.
2773 shareUrlIntent.type = "text/plain"
2775 // Set the intent to open in a new task.
2776 shareUrlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
2779 startActivity(Intent.createChooser(shareUrlIntent, getString(R.string.share_url)))
2781 // Consume the event.
2785 // Add an empty cancel entry, which by default closes the context menu.
2786 contextMenu.add(R.string.cancel)
2789 WebView.HitTestResult.EMAIL_TYPE -> {
2790 // Get the target URL.
2791 linkUrl = hitTestResult.extra
2793 // Set the target URL as the title of the context menu.
2794 contextMenu.setHeaderTitle(linkUrl)
2796 // Add a write email entry.
2797 contextMenu.add(R.string.write_email).setOnMenuItemClickListener {
2798 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2799 val emailIntent = Intent(Intent.ACTION_SENDTO)
2801 // Parse the url and set it as the data for the intent.
2802 emailIntent.data = Uri.parse("mailto:$linkUrl")
2804 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2805 emailIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2809 startActivity(emailIntent)
2810 } catch (exception: ActivityNotFoundException) {
2811 // Display a snackbar.
2812 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
2815 // Consume the event.
2819 // Add a copy email address entry.
2820 contextMenu.add(R.string.copy_email_address).setOnMenuItemClickListener {
2821 // Save the email address in a clip data.
2822 val srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl)
2824 // Set the clip data as the clipboard's primary clip.
2825 clipboardManager.setPrimaryClip(srcEmailTypeClipData)
2827 // Consume the event.
2831 // Add an empty cancel entry, which by default closes the context menu.
2832 contextMenu.add(R.string.cancel)
2837 // The view parameter cannot be removed because it is called from the layout onClick.
2838 fun addTab(@Suppress("UNUSED_PARAMETER")view: View?) {
2839 // Add a new tab with a blank URL.
2840 addNewPage(urlString = "", adjacent = true, moveToTab = true)
2843 private fun addNewPage(urlString: String, adjacent: Boolean, moveToTab: Boolean) {
2844 // Clear the focus from the URL edit text, so that it will be populated with the information from the new tab.
2845 urlEditText.clearFocus()
2847 // Add the new tab after the tab layout has quiesced.
2848 // Otherwise, there can be problems when restoring a large number of tabs and processing a new intent at the same time. <https://redmine.stoutner.com/issues/1136>
2850 // Get the new tab position.
2851 val newTabPosition = if (adjacent) // The new tab position is immediately to the right of the current tab position.
2852 tabLayout.selectedTabPosition + 1
2853 else // The new tab position is at the end. The tab positions are 0 indexed, so the new page number will match the current count.
2856 // Add the new WebView page.
2857 webViewStateAdapter!!.addPage(newTabPosition, urlString)
2860 addNewTab(newTabPosition, moveToTab)
2864 private fun addNewTab(newTabPosition: Int, moveToTab: Boolean) {
2865 // Check to see if the new page is ready.
2866 if (webViewStateAdapter!!.itemCount >= tabLayout.tabCount) { // The new page is ready.
2867 // Create a new tab.
2868 val newTab = tabLayout.newTab()
2870 // Set a custom view on the new tab.
2871 newTab.setCustomView(R.layout.tab_custom_view)
2874 tabLayout.addTab(newTab, newTabPosition, moveToTab)
2876 // Select the new tab if it is the first one. For some odd reason, Android doesn't select the first tab if it is the only one, which causes problems with the new tab position logic above.
2877 if (newTabPosition == 0)
2878 tabLayout.selectTab(newTab)
2880 // Scroll to the new tab position if moving to the new tab.
2883 tabLayout.setScrollPosition(newTabPosition, 0F, false, false)
2886 // Show the app bar if it is at the bottom of the screen and the new tab is taking focus.
2887 if (bottomAppBar && moveToTab && appBarLayout.translationY != 0f) {
2888 // Animate the bottom app bar onto the screen.
2889 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0f)
2892 objectAnimator.start()
2894 } else { // The new page is not ready.
2895 // Create a new tab handler.
2896 val newTabHandler = Handler(Looper.getMainLooper())
2898 // Create a new tab runnable.
2899 val newTabRunnable = Runnable {
2900 // Create the new tab.
2901 addNewTab(newTabPosition, moveToTab)
2904 // Try adding the new tab again after 50 milliseconds.
2905 newTabHandler.postDelayed(newTabRunnable, 50)
2909 private fun applyAppSettings() {
2910 // 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.
2911 defaultJavaScript = sharedPreferences.getBoolean(getString(R.string.javascript_key), false)
2912 defaultCookies = sharedPreferences.getBoolean(getString(R.string.cookies_key), false)
2913 defaultDomStorage = sharedPreferences.getBoolean(getString(R.string.dom_storage_key), false)
2914 defaultEasyList = sharedPreferences.getBoolean(getString(R.string.easylist_key), true)
2915 defaultEasyPrivacy = sharedPreferences.getBoolean(getString(R.string.easyprivacy_key), true)
2916 defaultFanboysAnnoyanceList = sharedPreferences.getBoolean(getString(R.string.fanboys_annoyance_list_key), true)
2917 defaultFanboysSocialBlockingList = sharedPreferences.getBoolean(getString(R.string.fanboys_social_blocking_list_key), true)
2918 defaultUltraList = sharedPreferences.getBoolean(getString(R.string.ultralist_key), true)
2919 defaultUltraPrivacy = sharedPreferences.getBoolean(getString(R.string.ultraprivacy_key), true)
2920 defaultBlockAllThirdPartyRequests = sharedPreferences.getBoolean(getString(R.string.block_all_third_party_requests_key), false)
2921 defaultFontSizeString = sharedPreferences.getString(getString(R.string.font_size_key), getString(R.string.font_size_default_value))!!
2922 defaultUserAgentName = sharedPreferences.getString(getString(R.string.user_agent_key), getString(R.string.user_agent_default_value))!!
2923 defaultSwipeToRefresh = sharedPreferences.getBoolean(getString(R.string.swipe_to_refresh_key), true)
2924 defaultWebViewTheme = sharedPreferences.getString(getString(R.string.webview_theme_key), getString(R.string.webview_theme_default_value))!!
2925 defaultWideViewport = sharedPreferences.getBoolean(getString(R.string.wide_viewport_key), true)
2926 defaultDisplayWebpageImages = sharedPreferences.getBoolean(getString(R.string.display_webpage_images_key), true)
2928 // Get the string arrays. These are done here so that expensive resource requests are not made each time a domain is loaded.
2929 webViewThemeEntryValuesStringArray = resources.getStringArray(R.array.webview_theme_entry_values)
2930 userAgentDataArray = resources.getStringArray(R.array.user_agent_data)
2931 userAgentNamesArray = resources.getStringArray(R.array.user_agent_names)
2932 val downloadProviderEntryValuesStringArray = resources.getStringArray(R.array.download_provider_entry_values)
2934 // Get the user agent array adapters. These are done here so that expensive resource requests are not made each time a domain is loaded.
2935 userAgentDataArrayAdapter = ArrayAdapter.createFromResource(this, R.array.user_agent_data, R.layout.spinner_item)
2936 userAgentNamesArrayAdapter = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item)
2938 // Store the values from the shared preferences in variables.
2939 incognitoModeEnabled = sharedPreferences.getBoolean(getString(R.string.incognito_mode_key), false)
2940 sanitizeTrackingQueries = sharedPreferences.getBoolean(getString(R.string.tracking_queries_key), true)
2941 sanitizeAmpRedirects = sharedPreferences.getBoolean(getString(R.string.amp_redirects_key), true)
2942 proxyMode = sharedPreferences.getString(getString(R.string.proxy_key), getString(R.string.proxy_default_value))!!
2943 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean(getString(R.string.full_screen_browsing_mode_key), false)
2944 hideAppBar = sharedPreferences.getBoolean(getString(R.string.hide_app_bar_key), true)
2945 val downloadProvider = sharedPreferences.getString(getString(R.string.download_provider_key), getString(R.string.download_provider_default_value))!!
2946 scrollAppBar = sharedPreferences.getBoolean(getString(R.string.scroll_app_bar_key), false)
2948 // Determine if downloading should be handled by an external app.
2949 downloadWithExternalApp = (downloadProvider == downloadProviderEntryValuesStringArray[2])
2951 // Apply the saved proxy mode if the app has been restarted.
2952 if (savedProxyMode != null) {
2953 // Apply the saved proxy mode.
2954 proxyMode = savedProxyMode!!
2956 // Reset the saved proxy mode.
2957 savedProxyMode = null
2960 // Get the search string.
2961 val searchString = sharedPreferences.getString(getString(R.string.search_key), getString(R.string.search_default_value))!!
2963 // Set the search string, using the custom search URL if specified.
2964 searchURL = if (searchString == getString(R.string.custom_url_item))
2965 sharedPreferences.getString(getString(R.string.search_custom_url_key), getString(R.string.search_custom_url_default_value))!!
2972 // Adjust the layout and scrolling parameters according to the position of the app bar.
2973 if (bottomAppBar) { // The app bar is on the bottom.
2975 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) { // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
2976 // Reset the WebView padding to fill the available space.
2977 swipeRefreshLayout.setPadding(0, 0, 0, 0)
2978 } else { // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
2979 // Move the WebView above the app bar layout.
2980 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
2982 // Show the app bar if it is scrolled off the screen.
2983 if (appBarLayout.translationY != 0f) {
2984 // Animate the bottom app bar onto the screen.
2985 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0f)
2988 objectAnimator.start()
2991 } else { // The app bar is on the top.
2992 // Get the current layout parameters. Using coordinator layout parameters allows the `setBehavior()` command and using app bar layout parameters allows the `setScrollFlags()` command.
2993 val swipeRefreshLayoutParams = swipeRefreshLayout.layoutParams as CoordinatorLayout.LayoutParams
2994 val toolbarLayoutParams = toolbar.layoutParams as AppBarLayout.LayoutParams
2995 val findOnPageLayoutParams = findOnPageLinearLayout.layoutParams as AppBarLayout.LayoutParams
2996 val tabsLayoutParams = tabsLinearLayout.layoutParams as AppBarLayout.LayoutParams
2998 // Add the scrolling behavior to the layout parameters.
3000 // Enable scrolling of the app bar.
3001 swipeRefreshLayoutParams.behavior = AppBarLayout.ScrollingViewBehavior()
3002 toolbarLayoutParams.scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS or AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP
3003 findOnPageLayoutParams.scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS or AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP
3004 tabsLayoutParams.scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS or AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP
3006 // Disable scrolling of the app bar.
3007 swipeRefreshLayoutParams.behavior = null
3008 toolbarLayoutParams.scrollFlags = 0
3009 findOnPageLayoutParams.scrollFlags = 0
3010 tabsLayoutParams.scrollFlags = 0
3012 // Expand the app bar if it is currently collapsed.
3013 appBarLayout.setExpanded(true)
3016 // Set the app bar scrolling for each WebView.
3017 for (i in 0 until webViewStateAdapter!!.itemCount) {
3018 // Get the WebView tab fragment.
3019 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
3021 // Get the fragment view.
3022 val fragmentView = webViewTabFragment.view
3024 // Only modify the WebViews if they exist.
3025 if (fragmentView != null) {
3026 // Get the nested scroll WebView from the tab fragment.
3027 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
3029 // Set the app bar scrolling.
3030 nestedScrollWebView.isNestedScrollingEnabled = scrollAppBar
3035 // Update the full screen browsing mode settings.
3036 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
3037 // Update the visibility of the app bar, which might have changed in the settings.
3039 // Hide the tab linear layout.
3040 tabsLinearLayout.visibility = View.GONE
3042 // Hide the app bar.
3045 // Show the tab linear layout.
3046 tabsLinearLayout.visibility = View.VISIBLE
3048 // Show the app bar.
3052 /* Hide the system bars.
3053 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3054 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
3055 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3056 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3059 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
3060 @Suppress("DEPRECATION")
3061 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
3062 } else { // Privacy Browser is not in full screen browsing mode.
3063 // 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.
3064 inFullScreenBrowsingMode = false
3066 // Show the tab linear layout.
3067 tabsLinearLayout.visibility = View.VISIBLE
3069 // Show the app bar.
3072 // Remove the `SYSTEM_UI` flags from the root frame layout. The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
3073 @Suppress("DEPRECATION")
3074 rootFrameLayout.systemUiVisibility = 0
3078 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
3079 @SuppressLint("SetJavaScriptEnabled")
3080 private fun applyDomainSettings(nestedScrollWebView: NestedScrollWebView, url: String?, resetTab: Boolean, reloadWebsite: Boolean, loadUrl: Boolean) {
3081 // Store the current URL.
3082 nestedScrollWebView.currentUrl = url!!
3084 // Parse the URL into a URI.
3085 val uri = Uri.parse(url)
3087 // Extract the domain from the URI.
3088 var newHostName = uri.host
3090 // Strings don't like to be null.
3091 if (newHostName == null)
3094 // 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.
3095 if ((nestedScrollWebView.currentDomainName != newHostName) || (newHostName == "")) { // A new domain is being loaded.
3096 // Set the new host name as the current domain name.
3097 nestedScrollWebView.currentDomainName = newHostName
3099 // Reset the ignoring of pinned domain information.
3100 nestedScrollWebView.ignorePinnedDomainInformation = false
3102 // Clear any pinned SSL certificate or IP addresses.
3103 nestedScrollWebView.clearPinnedSslCertificate()
3104 nestedScrollWebView.pinnedIpAddresses = ""
3106 // Reset the tab if specified.
3108 // Initialize the favorite icon.
3109 nestedScrollWebView.resetFavoriteIcon()
3111 // Get the current page position.
3112 val currentPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
3114 // Get the corresponding tab.
3115 val tab = tabLayout.getTabAt(currentPagePosition)
3117 // Update the tab if it isn't null, which sometimes happens when restarting from the background.
3119 // Get the tab custom view.
3120 val tabCustomView = tab.customView!!
3122 // Get the tab views.
3123 val tabFavoriteIconImageView = tabCustomView.findViewById<ImageView>(R.id.favorite_icon_imageview)
3124 val tabTitleTextView = tabCustomView.findViewById<TextView>(R.id.title_textview)
3126 // Store the current values in case they need to be restored.
3127 nestedScrollWebView.previousFavoriteIconDrawable = tabFavoriteIconImageView.drawable
3128 nestedScrollWebView.previousWebpageTitle = tabTitleTextView.text.toString()
3130 // Set the default favorite icon as the favorite icon for this tab.
3131 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nestedScrollWebView.getFavoriteIcon(), 128, 128, true))
3133 // Set the loading title text.
3134 tabTitleTextView.setText(R.string.loading)
3138 // Initialize the domain name in database variable.
3139 var domainNameInDatabase: String? = null
3141 // Check the hostname against the domain settings set.
3142 if (domainsSettingsSet.contains(newHostName)) { // The hostname is contained in the domain settings set.
3143 // Record the domain name in the database.
3144 domainNameInDatabase = newHostName
3146 // Set the domain settings applied tracker to true.
3147 nestedScrollWebView.domainSettingsApplied = true
3148 } else { // The hostname is not contained in the domain settings set.
3149 // Set the domain settings applied tracker to false.
3150 nestedScrollWebView.domainSettingsApplied = false
3153 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3154 while (!nestedScrollWebView.domainSettingsApplied && newHostName!!.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the hostname.
3155 if (domainsSettingsSet.contains("*.$newHostName")) { // Check the host name prepended by `*.`.
3156 // Set the domain settings applied tracker to true.
3157 nestedScrollWebView.domainSettingsApplied = true
3159 // Store the applied domain names as it appears in the database.
3160 domainNameInDatabase = "*.$newHostName"
3163 // Strip out the lowest subdomain of of the host name.
3164 newHostName = newHostName.substring(newHostName.indexOf(".") + 1)
3167 // Apply either the domain settings or the default settings.
3168 if (nestedScrollWebView.domainSettingsApplied) { // The url has custom domain settings.
3169 // Get a cursor for the current host.
3170 val currentDomainSettingsCursor = domainsDatabaseHelper!!.getCursorForDomainName(domainNameInDatabase!!)
3172 // Move to the first position.
3173 currentDomainSettingsCursor.moveToFirst()
3175 // Get the settings from the cursor.
3176 nestedScrollWebView.domainSettingsDatabaseId = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ID))
3177 val javaScriptInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_JAVASCRIPT))
3178 val cookiesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(COOKIES))
3179 val domStorageInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_DOM_STORAGE))
3180 val easyListInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_EASYLIST))
3181 val easyPrivacyInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_EASYPRIVACY))
3182 val fanboysAnnoyanceListInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_FANBOYS_ANNOYANCE_LIST))
3183 val fanboysSocialBlockingListInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST))
3184 val ultraListInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.ULTRALIST))
3185 val ultraPrivacyInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_ULTRAPRIVACY))
3186 val blockAllThirdPartyRequestsInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.BLOCK_ALL_THIRD_PARTY_REQUESTS))
3187 val userAgentName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.USER_AGENT))
3188 val fontSize = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(FONT_SIZE))
3189 val swipeToRefreshInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(SWIPE_TO_REFRESH))
3190 val webViewThemeInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(WEBVIEW_THEME))
3191 val wideViewportInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(WIDE_VIEWPORT))
3192 val displayWebpageImagesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DISPLAY_IMAGES))
3193 val pinnedSslCertificate = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(PINNED_SSL_CERTIFICATE)) == 1)
3194 val pinnedSslIssuedToCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_TO_COMMON_NAME))
3195 val pinnedSslIssuedToOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_TO_ORGANIZATION))
3196 val pinnedSslIssuedToUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_TO_ORGANIZATIONAL_UNIT))
3197 val pinnedSslIssuedByCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_BY_COMMON_NAME))
3198 val pinnedSslIssuedByOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_BY_ORGANIZATION))
3199 val pinnedSslIssuedByUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_BY_ORGANIZATIONAL_UNIT))
3200 val pinnedSslStartDate = Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.SSL_START_DATE)))
3201 val pinnedSslEndDate = Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.SSL_END_DATE)))
3202 val pinnedIpAddresses = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(PINNED_IP_ADDRESSES)) == 1)
3203 val pinnedHostIpAddresses = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(IP_ADDRESSES))
3205 // Close the current host domain settings cursor.
3206 currentDomainSettingsCursor.close()
3208 // Set the JavaScript status.
3209 when (javaScriptInt) {
3210 SYSTEM_DEFAULT -> nestedScrollWebView.settings.javaScriptEnabled = defaultJavaScript
3211 ENABLED -> nestedScrollWebView.settings.javaScriptEnabled = true
3212 DISABLED -> nestedScrollWebView.settings.javaScriptEnabled = false
3215 // Store the cookies status.
3217 SYSTEM_DEFAULT -> nestedScrollWebView.acceptCookies = defaultCookies
3218 ENABLED -> nestedScrollWebView.acceptCookies = true
3219 DISABLED -> nestedScrollWebView.acceptCookies = false
3222 // Apply the cookies status.
3223 cookieManager.setAcceptCookie(nestedScrollWebView.acceptCookies)
3225 // Set the DOM storage status.
3226 when (domStorageInt) {
3227 SYSTEM_DEFAULT -> nestedScrollWebView.settings.domStorageEnabled = defaultDomStorage
3228 ENABLED -> nestedScrollWebView.settings.domStorageEnabled = true
3229 DISABLED -> nestedScrollWebView.settings.domStorageEnabled = false
3232 // Set the EasyList status.
3233 when (easyListInt) {
3234 SYSTEM_DEFAULT -> nestedScrollWebView.easyListEnabled = defaultEasyList
3235 ENABLED -> nestedScrollWebView.easyListEnabled = true
3236 DISABLED -> nestedScrollWebView.easyListEnabled = false
3239 // Set the EasyPrivacy status.
3240 when (easyPrivacyInt) {
3241 SYSTEM_DEFAULT -> nestedScrollWebView.easyPrivacyEnabled = defaultEasyPrivacy
3242 ENABLED -> nestedScrollWebView.easyPrivacyEnabled = true
3243 DISABLED -> nestedScrollWebView.easyPrivacyEnabled = false
3246 // Set the Fanboy's Annoyance List status.
3247 when (fanboysAnnoyanceListInt) {
3248 SYSTEM_DEFAULT -> nestedScrollWebView.fanboysAnnoyanceListEnabled = defaultFanboysAnnoyanceList
3249 ENABLED -> nestedScrollWebView.fanboysAnnoyanceListEnabled = true
3250 DISABLED -> nestedScrollWebView.fanboysAnnoyanceListEnabled = false
3253 // Set the Fanboy's Social Blocking List status.
3254 when (fanboysSocialBlockingListInt) {
3255 SYSTEM_DEFAULT -> nestedScrollWebView.fanboysSocialBlockingListEnabled = defaultFanboysSocialBlockingList
3256 ENABLED -> nestedScrollWebView.fanboysSocialBlockingListEnabled = true
3257 DISABLED -> nestedScrollWebView.fanboysSocialBlockingListEnabled = false
3260 // Set the UltraList status.
3261 when (ultraListInt) {
3262 SYSTEM_DEFAULT -> nestedScrollWebView.ultraListEnabled = defaultUltraList
3263 ENABLED -> nestedScrollWebView.ultraListEnabled = true
3264 DISABLED -> nestedScrollWebView.ultraListEnabled = false
3267 // Set the UltraPrivacy status.
3268 when (ultraPrivacyInt) {
3269 SYSTEM_DEFAULT -> nestedScrollWebView.ultraPrivacyEnabled = defaultUltraPrivacy
3270 ENABLED -> nestedScrollWebView.ultraPrivacyEnabled = true
3271 DISABLED -> nestedScrollWebView.ultraPrivacyEnabled = false
3274 // Set the block all third-party requests status.
3275 when (blockAllThirdPartyRequestsInt) {
3276 SYSTEM_DEFAULT -> nestedScrollWebView.blockAllThirdPartyRequests = defaultBlockAllThirdPartyRequests
3277 ENABLED -> nestedScrollWebView.blockAllThirdPartyRequests = true
3278 DISABLED -> nestedScrollWebView.blockAllThirdPartyRequests = false
3281 // Set the user agent.
3282 if (userAgentName == getString(R.string.system_default_user_agent)) { // Use the system default user agent.
3283 // Set the user agent according to the system default.
3284 when (val defaultUserAgentArrayPosition = userAgentNamesArrayAdapter.getPosition(defaultUserAgentName)) {
3285 UNRECOGNIZED_USER_AGENT -> // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3286 nestedScrollWebView.settings.userAgentString = defaultUserAgentName
3288 SETTINGS_WEBVIEW_DEFAULT_USER_AGENT -> // Set the user agent to `""`, which uses the default value.
3289 nestedScrollWebView.settings.userAgentString = ""
3291 SETTINGS_CUSTOM_USER_AGENT -> // Set the default custom user agent.
3292 nestedScrollWebView.settings.userAgentString = sharedPreferences.getString(getString(R.string.custom_user_agent_key), getString(R.string.custom_user_agent_default_value))
3294 else -> // Get the user agent string from the user agent data array
3295 nestedScrollWebView.settings.userAgentString = userAgentDataArray[defaultUserAgentArrayPosition]
3297 } else { // Set the user agent according to the stored name.
3298 // Set the user agent.
3299 when (val userAgentArrayPosition = userAgentNamesArrayAdapter.getPosition(userAgentName)) {
3300 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3301 UNRECOGNIZED_USER_AGENT ->
3302 nestedScrollWebView.settings.userAgentString = userAgentName
3304 // Set the user agent to `""`, which uses the default value.
3305 SETTINGS_WEBVIEW_DEFAULT_USER_AGENT ->
3306 nestedScrollWebView.settings.userAgentString = ""
3308 // Get the user agent string from the user agent data array.
3310 nestedScrollWebView.settings.userAgentString = userAgentDataArray[userAgentArrayPosition]
3314 // Apply the font size.
3315 try { // Try the specified font size to see if it is valid.
3316 if (fontSize == 0) { // Apply the default font size.
3317 // Set the font size from the value in the app settings.
3318 nestedScrollWebView.settings.textZoom = defaultFontSizeString.toInt()
3319 } else { // Apply the font size from domain settings.
3320 nestedScrollWebView.settings.textZoom = fontSize
3322 } catch (exception: Exception) { // The specified font size is invalid
3323 // Set the font size to be 100%
3324 nestedScrollWebView.settings.textZoom = 100
3327 // Set swipe to refresh.
3328 when (swipeToRefreshInt) {
3330 // Store the swipe to refresh status in the nested scroll WebView.
3331 nestedScrollWebView.swipeToRefresh = defaultSwipeToRefresh
3333 // Update the swipe refresh layout.
3334 if (defaultSwipeToRefresh) { // Swipe to refresh is enabled.
3335 // 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).
3336 if (currentWebView != null) {
3337 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
3338 swipeRefreshLayout.isEnabled = (currentWebView!!.scrollY == 0)
3340 } else { // Swipe to refresh is disabled.
3341 // Disable the swipe refresh layout.
3342 swipeRefreshLayout.isEnabled = false
3347 // Store the swipe to refresh status in the nested scroll WebView.
3348 nestedScrollWebView.swipeToRefresh = true
3350 // 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).
3351 if (currentWebView != null) {
3352 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
3353 swipeRefreshLayout.isEnabled = (currentWebView!!.scrollY == 0)
3358 // Store the swipe to refresh status in the nested scroll WebView.
3359 nestedScrollWebView.swipeToRefresh = false
3361 // Disable swipe to refresh.
3362 swipeRefreshLayout.isEnabled = false
3366 // Set the WebView theme if algorithmic darkening is supported.
3367 if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {
3368 // Set the WebView theme.
3369 when (webViewThemeInt) {
3370 SYSTEM_DEFAULT -> // Set the WebView theme.
3371 when (defaultWebViewTheme) {
3372 webViewThemeEntryValuesStringArray[1] -> // The light theme is selected. Turn off algorithmic darkening.
3373 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
3375 webViewThemeEntryValuesStringArray[2] -> // The dark theme is selected. Turn on algorithmic darkening.
3376 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
3378 else -> { // The system default theme is selected.
3379 // Get the current system theme status.
3380 val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
3382 // Set the algorithmic darkening according to the current system theme status.
3383 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, currentThemeStatus == Configuration.UI_MODE_NIGHT_YES)
3387 LIGHT_THEME -> // Turn off algorithmic darkening.
3388 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
3390 DARK_THEME -> // Turn on algorithmic darkening.
3391 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
3395 // Set the wide viewport status.
3396 when (wideViewportInt) {
3397 SYSTEM_DEFAULT -> nestedScrollWebView.settings.useWideViewPort = defaultWideViewport
3398 ENABLED -> nestedScrollWebView.settings.useWideViewPort = true
3399 DISABLED -> nestedScrollWebView.settings.useWideViewPort = false
3402 // Set the display webpage images status.
3403 when (displayWebpageImagesInt) {
3404 SYSTEM_DEFAULT -> nestedScrollWebView.settings.loadsImagesAutomatically = defaultDisplayWebpageImages
3405 ENABLED -> nestedScrollWebView.settings.loadsImagesAutomatically = true
3406 DISABLED -> nestedScrollWebView.settings.loadsImagesAutomatically = false
3409 // If there is a pinned SSL certificate, store it in the WebView.
3410 if (pinnedSslCertificate)
3411 nestedScrollWebView.setPinnedSslCertificate(pinnedSslIssuedToCName, pinnedSslIssuedToOName, pinnedSslIssuedToUName, pinnedSslIssuedByCName, pinnedSslIssuedByOName, pinnedSslIssuedByUName,
3412 pinnedSslStartDate, pinnedSslEndDate)
3414 // If there is a pinned IP address, store it in the WebView.
3415 if (pinnedIpAddresses)
3416 nestedScrollWebView.pinnedIpAddresses = pinnedHostIpAddresses
3418 // Set a background on the URL relative layout to indicate that custom domain settings are being used.
3419 urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.drawable.domain_settings_url_background)
3420 } else { // The new URL does not have custom domain settings. Load the defaults.
3421 // Store the values from the shared preferences.
3422 nestedScrollWebView.settings.javaScriptEnabled = defaultJavaScript
3423 nestedScrollWebView.acceptCookies = defaultCookies
3424 nestedScrollWebView.settings.domStorageEnabled = defaultDomStorage
3425 nestedScrollWebView.easyListEnabled = defaultEasyList
3426 nestedScrollWebView.easyPrivacyEnabled = defaultEasyPrivacy
3427 nestedScrollWebView.fanboysAnnoyanceListEnabled = defaultFanboysAnnoyanceList
3428 nestedScrollWebView.fanboysSocialBlockingListEnabled = defaultFanboysSocialBlockingList
3429 nestedScrollWebView.ultraListEnabled = defaultUltraList
3430 nestedScrollWebView.ultraPrivacyEnabled = defaultUltraPrivacy
3431 nestedScrollWebView.blockAllThirdPartyRequests = defaultBlockAllThirdPartyRequests
3433 // Apply the default cookie setting.
3434 cookieManager.setAcceptCookie(nestedScrollWebView.acceptCookies)
3436 // Apply the default font size setting.
3438 // Try to set the font size from the value in the app settings.
3439 nestedScrollWebView.settings.textZoom = defaultFontSizeString.toInt()
3440 } catch (exception: Exception) {
3441 // If the app settings value is invalid, set the font size to 100%.
3442 nestedScrollWebView.settings.textZoom = 100
3445 // Store the swipe to refresh status in the nested scroll WebView.
3446 nestedScrollWebView.swipeToRefresh = defaultSwipeToRefresh
3448 // Update the swipe refresh layout.
3449 if (defaultSwipeToRefresh) { // Swipe to refresh is enabled.
3450 // 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).
3451 if (currentWebView != null) {
3452 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
3453 swipeRefreshLayout.isEnabled = currentWebView!!.scrollY == 0
3455 } else { // Swipe to refresh is disabled.
3456 // Disable the swipe refresh layout.
3457 swipeRefreshLayout.isEnabled = false
3460 // Reset the domain settings database ID.
3461 nestedScrollWebView.domainSettingsDatabaseId = -1
3463 // Set the user agent.
3464 when (val userAgentArrayPosition = userAgentNamesArrayAdapter.getPosition(defaultUserAgentName)) {
3465 UNRECOGNIZED_USER_AGENT -> // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3466 nestedScrollWebView.settings.userAgentString = defaultUserAgentName
3468 SETTINGS_WEBVIEW_DEFAULT_USER_AGENT -> // Set the user agent to `""`, which uses the default value.
3469 nestedScrollWebView.settings.userAgentString = ""
3471 SETTINGS_CUSTOM_USER_AGENT -> // Set the default custom user agent.
3472 nestedScrollWebView.settings.userAgentString = sharedPreferences.getString(getString(R.string.custom_user_agent_key), getString(R.string.custom_user_agent_default_value))
3474 else -> // Get the user agent string from the user agent data array
3475 nestedScrollWebView.settings.userAgentString = userAgentDataArray[userAgentArrayPosition]
3478 // Set the WebView theme if algorithmic darkening is supported.
3479 if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {
3480 // Set the WebView theme.
3481 when (defaultWebViewTheme) {
3482 webViewThemeEntryValuesStringArray[1] -> // The light theme is selected. Turn off algorithmic darkening.
3483 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
3485 webViewThemeEntryValuesStringArray[2] -> // The dark theme is selected. Turn on algorithmic darkening.
3486 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
3488 else -> { // The system default theme is selected. Get the current system theme status.
3489 // Get the current theme status.
3490 val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
3492 // Set the algorithmic darkening according to the current system theme status.
3493 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, currentThemeStatus == Configuration.UI_MODE_NIGHT_YES)
3498 // Set the viewport.
3499 nestedScrollWebView.settings.useWideViewPort = defaultWideViewport
3501 // Set the loading of webpage images.
3502 nestedScrollWebView.settings.loadsImagesAutomatically = defaultDisplayWebpageImages
3504 // Set a transparent background on the URL relative layout.
3505 urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.color.transparent)
3508 // Update the privacy icons.
3509 updatePrivacyIcons(true)
3512 // Reload the website if returning from the Domains activity.
3514 nestedScrollWebView.reload()
3516 // Disable the wide viewport if the source is being viewed.
3517 if (url.startsWith("view-source:"))
3518 nestedScrollWebView.settings.useWideViewPort = false
3520 // 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.
3522 nestedScrollWebView.loadUrl(url)
3525 private fun applyProxy(reloadWebViews: Boolean) {
3526 // Set the proxy according to the mode.
3527 proxyHelper.setProxy(applicationContext, appBarLayout, proxyMode)
3529 // Reset the waiting for proxy tracker.
3530 waitingForProxy = false
3534 ProxyHelper.NONE -> {
3535 // Initialize a color background typed value.
3536 val colorBackgroundTypedValue = TypedValue()
3538 // Get the color background from the theme.
3539 theme.resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true)
3541 // Get the color background int from the typed value.
3542 val colorBackgroundInt = colorBackgroundTypedValue.data
3544 // Set the default app bar layout background.
3545 appBarLayout.setBackgroundColor(colorBackgroundInt)
3548 ProxyHelper.TOR -> {
3549 // Set the app bar background to indicate proxying is enabled.
3550 appBarLayout.setBackgroundResource(R.color.blue_background)
3552 // Check to see if Orbot is installed.
3554 // Get the package manager.
3555 val packageManager = packageManager
3557 // 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.
3558 packageManager.getPackageInfo("org.torproject.android", 0)
3560 // Check to see if the proxy is ready.
3561 if (orbotStatus != ProxyHelper.ORBOT_STATUS_ON) { // Orbot is not ready.
3562 // Set the waiting for proxy status.
3563 waitingForProxy = true
3565 // Show the waiting for proxy dialog if it isn't already displayed.
3566 if (supportFragmentManager.findFragmentByTag(getString(R.string.waiting_for_proxy_dialog)) == null) {
3567 // Get a handle for the waiting for proxy alert dialog.
3568 val waitingForProxyDialogFragment = WaitingForProxyDialog()
3570 // Try to show the dialog. Sometimes the window is not yet active if returning from Settings.
3572 // Show the waiting for proxy alert dialog.
3573 waitingForProxyDialogFragment.show(supportFragmentManager, getString(R.string.waiting_for_proxy_dialog))
3574 } catch (waitingForTorException: Exception) {
3575 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
3576 pendingDialogsArrayList.add(PendingDialogDataClass(waitingForProxyDialogFragment, getString(R.string.waiting_for_proxy_dialog)))
3580 } catch (exception: PackageManager.NameNotFoundException) { // Orbot is not installed.
3581 // Show the Orbot not installed dialog if it is not already displayed.
3582 if (supportFragmentManager.findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
3583 // Get a handle for the Orbot not installed alert dialog.
3584 val orbotNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode)
3586 // Try to show the dialog. Sometimes the window is not yet active if returning from Settings.
3588 // Display the Orbot not installed alert dialog.
3589 orbotNotInstalledDialogFragment.show(supportFragmentManager, getString(R.string.proxy_not_installed_dialog))
3590 } catch (orbotNotInstalledException: Exception) {
3591 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
3592 pendingDialogsArrayList.add(PendingDialogDataClass(orbotNotInstalledDialogFragment, getString(R.string.proxy_not_installed_dialog)))
3598 ProxyHelper.I2P -> {
3599 // Set the app bar background to indicate proxying is enabled.
3600 appBarLayout.setBackgroundResource(R.color.blue_background)
3602 // Check to see if I2P is installed.
3604 // 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.
3605 packageManager.getPackageInfo("net.i2p.android.router", 0)
3606 } catch (fdroidException: PackageManager.NameNotFoundException) { // The F-Droid flavor is not installed.
3608 // 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.
3609 packageManager.getPackageInfo("net.i2p.android", 0)
3610 } catch (googlePlayException: PackageManager.NameNotFoundException) { // The Google Play flavor is not installed.
3611 // Sow the I2P not installed dialog if it is not already displayed.
3612 if (supportFragmentManager.findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
3613 // Get a handle for the waiting for proxy alert dialog.
3614 val i2pNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode)
3616 // Try to show the dialog. Sometimes the window is not yet active if returning from Settings.
3618 // Display the I2P not installed alert dialog.
3619 i2pNotInstalledDialogFragment.show(supportFragmentManager, getString(R.string.proxy_not_installed_dialog))
3620 } catch (i2pNotInstalledException: Exception) {
3621 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
3622 pendingDialogsArrayList.add(PendingDialogDataClass(i2pNotInstalledDialogFragment, getString(R.string.proxy_not_installed_dialog)))
3629 ProxyHelper.CUSTOM ->
3630 // Set the app bar background to indicate proxying is enabled.
3631 appBarLayout.setBackgroundResource(R.color.blue_background)
3634 // Reload the WebViews if requested and not waiting for the proxy.
3635 if (reloadWebViews && !waitingForProxy) {
3636 // Reload the WebViews.
3637 for (i in 0 until webViewStateAdapter!!.itemCount) {
3638 // Get the WebView tab fragment.
3639 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
3641 // Get the fragment view.
3642 val fragmentView = webViewTabFragment.view
3644 // Only reload the WebViews if they exist.
3645 if (fragmentView != null) {
3646 // Get the nested scroll WebView from the tab fragment.
3647 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
3649 // Reload the WebView.
3650 nestedScrollWebView.reload()
3656 // The view parameter cannot be removed because it is called from the layout onClick.
3657 fun bookmarksBack(@Suppress("UNUSED_PARAMETER")view: View?) {
3658 if (currentBookmarksFolderId == HOME_FOLDER_ID) { // The home folder is displayed.
3659 // close the bookmarks drawer.
3660 drawerLayout.closeDrawer(GravityCompat.END)
3661 } else { // A subfolder is displayed.
3662 // Set the former parent folder as the current folder.
3663 currentBookmarksFolderId = bookmarksDatabaseHelper!!.getParentFolderId(currentBookmarksFolderId)
3665 // Load the new folder.
3666 loadBookmarksFolder()
3670 private fun calculateSettingsInt(settingCurrentlyEnabled: Boolean, settingEnabledByDefault: Boolean): Int {
3671 return if (settingCurrentlyEnabled == settingEnabledByDefault) // The current system default is used.
3673 else if (settingCurrentlyEnabled) // The setting is enabled, which is different from the system default.
3675 else // The setting is disabled, which is different from the system default.
3679 private fun clearAndExit() {
3680 // Close the bookmarks cursor if it exists.
3681 bookmarksCursor?.close()
3683 // Close the databases helpers if they exist.
3684 bookmarksDatabaseHelper?.close()
3685 domainsDatabaseHelper?.close()
3687 // Get the status of the clear everything preference.
3688 val clearEverything = sharedPreferences.getBoolean(getString(R.string.clear_everything_key), true)
3690 // Get a handle for the runtime.
3691 val runtime = Runtime.getRuntime()
3693 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
3694 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
3695 val privateDataDirectoryString = applicationInfo.dataDir
3698 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_cookies_key), true)) {
3699 // Ass the cookie manager to delete all the cookies.
3700 cookieManager.removeAllCookies(null)
3702 // Ask the cookie manager to flush the cookie database.
3703 cookieManager.flush()
3705 // Manually delete the cookies database, as the cookie manager sometimes will not flush its changes to disk before system exit is run.
3707 // Two commands must be used because `Runtime.exec()` does not like `*`.
3708 val deleteCookiesProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/Cookies")
3709 val deleteCookiesJournalProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/Cookies-journal")
3711 // Wait until the processes have finished.
3712 deleteCookiesProcess.waitFor()
3713 deleteCookiesJournalProcess.waitFor()
3714 } catch (exception: Exception) {
3715 // Do nothing if an error is thrown.
3719 // Clear DOM storage.
3720 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_dom_storage_key), true)) {
3721 // Ask web storage to clear the DOM storage.
3722 WebStorage.getInstance().deleteAllData()
3724 // Manually delete the DOM storage files and directories, as web storage sometimes will not flush its changes to disk before system exit is run.
3726 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
3727 val deleteLocalStorageProcess = runtime.exec(arrayOf("rm", "-rf", "$privateDataDirectoryString/app_webview/Local Storage/"))
3729 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
3730 val deleteIndexProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview/IndexedDB")
3731 val deleteQuotaManagerProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/QuotaManager")
3732 val deleteQuotaManagerJournalProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/QuotaManager-journal")
3733 val deleteDatabaseProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview/databases")
3735 // Wait until the processes have finished.
3736 deleteLocalStorageProcess.waitFor()
3737 deleteIndexProcess.waitFor()
3738 deleteQuotaManagerProcess.waitFor()
3739 deleteQuotaManagerJournalProcess.waitFor()
3740 deleteDatabaseProcess.waitFor()
3741 } catch (exception: Exception) {
3742 // Do nothing if an error is thrown.
3746 // Clear the logcat.
3747 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_logcat_key), true)) {
3749 // Clear the logcat. `-c` clears the logcat. `-b all` clears all the buffers (instead of just crash, main, and system).
3750 val process = Runtime.getRuntime().exec("logcat -b all -c")
3752 // Wait for the process to finish.
3754 } catch (exception: IOException) {
3756 } catch (exception: InterruptedException) {
3762 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_cache_key), true)) {
3763 // Clear the cache from each WebView.
3764 for (i in 0 until webViewStateAdapter!!.itemCount) {
3765 // Get the WebView tab fragment.
3766 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
3768 // Get the WebView fragment view.
3769 val webViewFragmentView = webViewTabFragment.view
3771 // Only clear the cache if the WebView exists.
3772 if (webViewFragmentView != null) {
3773 // Get the nested scroll WebView from the tab fragment.
3774 val nestedScrollWebView = webViewFragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
3776 // Clear the cache for this WebView.
3777 nestedScrollWebView.clearCache(true)
3781 // Manually delete the cache directories.
3783 // Delete the main cache directory.
3784 val deleteCacheProcess = runtime.exec("rm -rf $privateDataDirectoryString/cache")
3786 // Delete the secondary `Service Worker` cache directory.
3787 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
3788 val deleteServiceWorkerProcess = runtime.exec(arrayOf("rm", "-rf", "$privateDataDirectoryString/app_webview/Default/Service Worker/"))
3790 // Wait until the processes have finished.
3791 deleteCacheProcess.waitFor()
3792 deleteServiceWorkerProcess.waitFor()
3793 } catch (exception: Exception) {
3794 // Do nothing if an error is thrown.
3798 // Wipe out each WebView.
3799 for (i in 0 until webViewStateAdapter!!.itemCount) {
3800 // Get the WebView tab fragment.
3801 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
3803 // Get the WebView frame layout.
3804 val webViewFrameLayout = webViewTabFragment.view as FrameLayout?
3806 // Only wipe out the WebView if it exists.
3807 if (webViewFrameLayout != null) {
3808 // Get the nested scroll WebView from the tab fragment.
3809 val nestedScrollWebView = webViewFrameLayout.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
3811 // Clear SSL certificate preferences for this WebView.
3812 nestedScrollWebView.clearSslPreferences()
3814 // Clear the back/forward history for this WebView.
3815 nestedScrollWebView.clearHistory()
3817 // Remove all the views from the frame layout.
3818 webViewFrameLayout.removeAllViews()
3820 // Destroy the internal state of the WebView.
3821 nestedScrollWebView.destroy()
3825 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
3826 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
3827 if (clearEverything) {
3829 // Delete the folder.
3830 val deleteAppWebviewProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview")
3832 // Wait until the process has finished.
3833 deleteAppWebviewProcess.waitFor()
3834 } catch (exception: Exception) {
3835 // Do nothing if an error is thrown.
3839 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
3840 finishAndRemoveTask()
3842 // Remove the terminated program from RAM. The status code is `0`.
3846 // The view parameter cannot be removed because it is called from the layout onClick.
3847 fun closeFindOnPage(@Suppress("UNUSED_PARAMETER")view: View?) {
3848 // Delete the contents of the find on page edit text.
3849 findOnPageEditText.text = null
3851 // Clear the highlighted phrases if the WebView is not null.
3852 currentWebView?.clearMatches()
3854 // Hide the find on page linear layout.
3855 findOnPageLinearLayout.visibility = View.GONE
3857 // Show the toolbar.
3858 toolbar.visibility = View.VISIBLE
3860 // Hide the keyboard.
3861 inputMethodManager.hideSoftInputFromWindow(toolbar.windowToken, 0)
3864 // The view parameter cannot be removed because it is called from the layout onClick.
3865 fun closeTab(@Suppress("UNUSED_PARAMETER")view: View?) {
3866 // Run the command according to the number of tabs.
3867 if (tabLayout.tabCount > 1) { // There is more than one tab open.
3868 // Get the current tab number.
3869 val currentTabNumber = tabLayout.selectedTabPosition
3871 // Delete the current tab.
3872 tabLayout.removeTabAt(currentTabNumber)
3874 // 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,
3875 // meaning that the current WebView must be reset. Otherwise it will happen automatically as the selected tab number changes.
3876 if (webViewStateAdapter!!.deletePage(currentTabNumber, webViewViewPager2))
3877 setCurrentWebView(currentTabNumber)
3878 } else { // There is only one tab open.
3883 override fun createBookmark(dialogFragment: DialogFragment) {
3885 val dialog = dialogFragment.dialog!!
3887 // Get the views from the dialog fragment.
3888 val webpageFavoriteIconRadioButton = dialog.findViewById<RadioButton>(R.id.webpage_favorite_icon_radiobutton)
3889 val webpageFavoriteIconImageView = dialog.findViewById<ImageView>(R.id.webpage_favorite_icon_imageview)
3890 val customIconImageView = dialog.findViewById<ImageView>(R.id.custom_icon_imageview)
3891 val bookmarkNameEditText = dialog.findViewById<EditText>(R.id.bookmark_name_edittext)
3892 val bookmarkUrlEditText = dialog.findViewById<EditText>(R.id.bookmark_url_edittext)
3894 // Extract the strings from the edit texts.
3895 val bookmarkNameString = bookmarkNameEditText.text.toString()
3896 val bookmarkUrlString = bookmarkUrlEditText.text.toString()
3898 // Get the selected favorite icon drawable.
3899 val favoriteIconDrawable = if (webpageFavoriteIconRadioButton.isChecked) // Use the webpage favorite icon.
3900 webpageFavoriteIconImageView.drawable
3901 else // Use the custom icon.
3902 customIconImageView.drawable
3904 // Cast the favorite icon bitmap to a bitmap drawable
3905 val favoriteIconBitmapDrawable = favoriteIconDrawable as BitmapDrawable
3907 // Convert the favorite icon bitmap drawable to a bitmap.
3908 val favoriteIconBitmap = favoriteIconBitmapDrawable.bitmap
3910 // Create a favorite icon byte array output stream.
3911 val favoriteIconByteArrayOutputStream = ByteArrayOutputStream()
3913 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
3914 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream)
3916 // Convert the favorite icon byte array stream to a byte array.
3917 val favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray()
3919 // Display the new bookmark below the current items in the (0 indexed) list.
3920 val newBookmarkDisplayOrder = bookmarksListView.count
3922 // Create the bookmark.
3923 bookmarksDatabaseHelper!!.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolderId, newBookmarkDisplayOrder, favoriteIconByteArray)
3925 // Update the bookmarks cursor with the current contents of this folder.
3926 bookmarksCursor = bookmarksDatabaseHelper!!.getBookmarksByDisplayOrder(currentBookmarksFolderId)
3928 // Update the list view.
3929 bookmarksCursorAdapter.changeCursor(bookmarksCursor)
3931 // Scroll to the new bookmark.
3932 bookmarksListView.setSelection(newBookmarkDisplayOrder)
3935 override fun createBookmarkFolder(dialogFragment: DialogFragment) {
3937 val dialog = dialogFragment.dialog!!
3939 // Get handles for the views in the dialog fragment.
3940 val defaultFolderIconRadioButton = dialog.findViewById<RadioButton>(R.id.default_folder_icon_radiobutton)
3941 val defaultFolderIconImageView = dialog.findViewById<ImageView>(R.id.default_folder_icon_imageview)
3942 val webpageFavoriteIconRadioButton = dialog.findViewById<RadioButton>(R.id.webpage_favorite_icon_radiobutton)
3943 val webpageFavoriteIconImageView = dialog.findViewById<ImageView>(R.id.webpage_favorite_icon_imageview)
3944 val customIconImageView = dialog.findViewById<ImageView>(R.id.custom_icon_imageview)
3945 val folderNameEditText = dialog.findViewById<EditText>(R.id.folder_name_edittext)
3947 // Get new folder name string.
3948 val folderNameString = folderNameEditText.text.toString()
3950 // Set the folder icon bitmap according to the dialog.
3951 val folderIconDrawable = if (defaultFolderIconRadioButton.isChecked) // Use the default folder icon.
3952 defaultFolderIconImageView.drawable
3953 else if (webpageFavoriteIconRadioButton.isChecked) // Use the webpage favorite icon.
3954 webpageFavoriteIconImageView.drawable
3955 else // Use the custom icon.
3956 customIconImageView.drawable
3958 // Cast the folder icon bitmap to a bitmap drawable.
3959 val folderIconBitmapDrawable = folderIconDrawable as BitmapDrawable
3961 // Convert the folder icon bitmap drawable to a bitmap.
3962 val folderIconBitmap = folderIconBitmapDrawable.bitmap
3964 // Create a folder icon byte array output stream.
3965 val folderIconByteArrayOutputStream = ByteArrayOutputStream()
3967 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
3968 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream)
3970 // Convert the folder icon byte array stream to a byte array.
3971 val folderIconByteArray = folderIconByteArrayOutputStream.toByteArray()
3973 // Move all the bookmarks down one in the display order.
3974 for (i in 0 until bookmarksListView.count) {
3975 // Get the bookmark database id.
3976 val databaseId = bookmarksListView.getItemIdAtPosition(i).toInt()
3978 // Move the bookmark down one slot.
3979 bookmarksDatabaseHelper!!.updateDisplayOrder(databaseId, displayOrder = i + 1)
3982 // Create the folder, which will be placed at the top of the list view.
3983 bookmarksDatabaseHelper!!.createFolder(folderNameString, currentBookmarksFolderId, displayOrder = 0, folderIconByteArray)
3985 // Update the bookmarks cursor with the current contents of this folder.
3986 bookmarksCursor = bookmarksDatabaseHelper!!.getBookmarksByDisplayOrder(currentBookmarksFolderId)
3988 // Update the list view.
3989 bookmarksCursorAdapter.changeCursor(bookmarksCursor)
3991 // Scroll to the new folder.
3992 bookmarksListView.setSelection(0)
3995 private fun exitFullScreenVideo() {
3996 // Re-enable the screen timeout.
3997 fullScreenVideoFrameLayout.keepScreenOn = false
3999 // Unset the full screen video flag.
4000 displayingFullScreenVideo = false
4002 // Remove all the views from the full screen video frame layout.
4003 fullScreenVideoFrameLayout.removeAllViews()
4005 // Hide the full screen video frame layout.
4006 fullScreenVideoFrameLayout.visibility = View.GONE
4008 // Enable the sliding drawers.
4009 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED)
4011 // Show the coordinator layout.
4012 coordinatorLayout.visibility = View.VISIBLE
4014 // Apply the appropriate full screen mode flags.
4015 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
4016 // Hide the app bar if specified.
4018 // Hide the tab linear layout.
4019 tabsLinearLayout.visibility = View.GONE
4021 // Hide the app bar.
4025 /* Hide the system bars.
4026 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4027 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4028 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4029 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4032 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4033 @Suppress("DEPRECATION")
4034 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
4035 } else { // Switch to normal viewing mode.
4036 // Remove the `SYSTEM_UI` flags from the root frame layout. The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4037 @Suppress("DEPRECATION")
4038 rootFrameLayout.systemUiVisibility = 0
4042 // The view parameter cannot be removed because it is called from the layout onClick.
4043 fun findNextOnPage(@Suppress("UNUSED_PARAMETER")view: View?) {
4044 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
4045 currentWebView!!.findNext(true)
4048 // The view parameter cannot be removed because it is called from the layout onClick.
4049 fun findPreviousOnPage(@Suppress("UNUSED_PARAMETER")view: View?) {
4050 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
4051 currentWebView!!.findNext(false)
4054 override fun finishedPopulatingFilterLists(combinedFilterLists: ArrayList<ArrayList<List<Array<String>>>>) {
4055 // Store the filter lists.
4056 easyList = combinedFilterLists[0]
4057 easyPrivacy = combinedFilterLists[1]
4058 fanboysAnnoyanceList = combinedFilterLists[2]
4059 fanboysSocialList = combinedFilterLists[3]
4060 ultraList = combinedFilterLists[4]
4061 ultraPrivacy = combinedFilterLists[5]
4063 // Check to see if the activity has been restarted with a saved state.
4064 if ((savedStateArrayList == null) || (savedStateArrayList!!.size == 0)) { // The activity has not been restarted or it was restarted on start to change the theme.
4065 // Add the first tab.
4066 addNewPage(urlString = "", adjacent = false, moveToTab = false)
4067 } else { // The activity has been restarted with a saved state.
4068 // Restore each tab.
4069 for (i in savedStateArrayList!!.indices) {
4071 tabLayout.addTab(tabLayout.newTab())
4074 val newTab = tabLayout.getTabAt(i)!!
4076 // Set a custom view on the new tab.
4077 newTab.setCustomView(R.layout.tab_custom_view)
4079 // Add the new page.
4080 webViewStateAdapter!!.restorePage(savedStateArrayList!![i], savedNestedScrollWebViewStateArrayList!![i])
4083 // Reset the saved state variables.
4084 savedStateArrayList = null
4085 savedNestedScrollWebViewStateArrayList = null
4087 // Get the intent that started the app.
4090 // Reset the intent. This prevents a duplicate tab from being created on restart.
4093 // Get the information from the intent.
4094 val intentAction = intent.action
4095 val intentUriData = intent.data
4096 val intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT)
4098 // Determine if this is a web search.
4099 val isWebSearch = (intentAction != null) && (intentAction == Intent.ACTION_WEB_SEARCH)
4101 // 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.
4102 if ((intentUriData != null) || (intentStringExtra != null) || isWebSearch) { // A new tab is being loaded.
4103 // Get the URL string.
4104 val urlString = if (isWebSearch) { // The intent is a web search.
4105 // Sanitize the search input.
4106 val encodedSearchString: String = try {
4107 URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8")
4108 } catch (exception: UnsupportedEncodingException) {
4112 // Add the base search URL.
4113 searchURL + encodedSearchString
4114 } else { // The intent contains a URL formatted as a URI or a URL in the string extra.
4115 // Get the URL string.
4116 intentUriData?.toString() ?: intentStringExtra!!
4119 // Add a new tab if specified in the preferences.
4120 if (sharedPreferences.getBoolean(getString(R.string.open_intents_in_new_tab_key), true)) { // Load the URL in a new tab.
4121 // Set the loading new intent flag.
4122 loadingNewIntent = true
4125 addNewPage(urlString, adjacent = false, moveToTab = true)
4126 } else { // Load the URL in the current tab.
4128 loadUrl(currentWebView!!, urlString)
4130 } else { // A new tab is not being loaded.
4131 // Restore the selected tab position.
4132 if (savedTabPosition == 0) { // The first tab is selected.
4133 // Set the first page as the current WebView.
4134 setCurrentWebView(0)
4135 } else { // The first tab is not selected.
4136 // Select the tab when the layout has finished populating.
4138 // Get a handle for the tab.
4139 val tab = tabLayout.getTabAt(savedTabPosition)!!
4149 // Remove the warning that `OnTouchListener()` needs to override `performClick()`, as the only purpose of setting the `OnTouchListener()` is to make it do nothing.
4150 @SuppressLint("ClickableViewAccessibility")
4151 private fun initializeApp() {
4152 // Get a handle for the input method.
4153 inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
4155 // Initialize the color spans for highlighting the URLs.
4156 initialGrayColorSpan = ForegroundColorSpan(getColor(R.color.gray_500))
4157 finalGrayColorSpan = ForegroundColorSpan(getColor(R.color.gray_500))
4158 redColorSpan = ForegroundColorSpan(getColor(R.color.red_text))
4160 // Remove the formatting from the URL edit text when the user is editing the text.
4161 urlEditText.onFocusChangeListener = View.OnFocusChangeListener { _: View?, hasFocus: Boolean ->
4162 if (hasFocus) { // The user is editing the URL text box.
4163 // Remove the syntax highlighting.
4164 urlEditText.text.removeSpan(redColorSpan)
4165 urlEditText.text.removeSpan(initialGrayColorSpan)
4166 urlEditText.text.removeSpan(finalGrayColorSpan)
4167 } else { // The user has stopped editing the URL text box.
4168 // Move to the beginning of the string.
4169 urlEditText.setSelection(0)
4171 // Reapply the syntax highlighting.
4172 UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
4176 // Set the go button on the keyboard to load the URL in url text box.
4177 urlEditText.setOnKeyListener { _: View?, keyCode: Int, keyEvent: KeyEvent ->
4178 // If the event is a key-down event on the `enter` button, load the URL.
4179 if ((keyEvent.action == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The enter key was pressed.
4181 loadUrlFromTextBox()
4183 // Consume the event.
4184 return@setOnKeyListener true
4185 } else { // Some other key was pressed.
4186 // Do not consume the event.
4187 return@setOnKeyListener false
4191 // Create an Orbot status broadcast receiver.
4192 orbotStatusBroadcastReceiver = object : BroadcastReceiver() {
4193 override fun onReceive(context: Context, intent: Intent) {
4194 // Get the content of the status message.
4195 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS")!!
4197 // If Privacy Browser is waiting on the proxy, load the website now that Orbot is connected.
4198 if ((orbotStatus == ProxyHelper.ORBOT_STATUS_ON) && waitingForProxy) {
4199 // Reset the waiting for proxy status.
4200 waitingForProxy = false
4202 // Get a list of the current fragments.
4203 val fragmentList = supportFragmentManager.fragments
4205 // Check each fragment to see if it is a waiting for proxy dialog. Sometimes more than one is displayed.
4206 for (i in fragmentList.indices) {
4207 // Get the fragment tag.
4208 val fragmentTag = fragmentList[i].tag
4210 // Check to see if it is the waiting for proxy dialog.
4211 if (fragmentTag != null && fragmentTag == getString(R.string.waiting_for_proxy_dialog)) {
4212 // Dismiss the waiting for proxy dialog.
4213 (fragmentList[i] as DialogFragment).dismiss()
4217 // Reload existing URLs and load any URLs that are waiting for the proxy.
4218 for (i in 0 until webViewStateAdapter!!.itemCount) {
4219 // Get the WebView tab fragment.
4220 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
4222 // Get the fragment view.
4223 val fragmentView = webViewTabFragment.view
4225 // Only process the WebViews if they exist.
4226 if (fragmentView != null) {
4227 // Get the nested scroll WebView from the tab fragment.
4228 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
4230 // Get the waiting for proxy URL string.
4231 val waitingForProxyUrlString = nestedScrollWebView.waitingForProxyUrlString
4233 // Load the pending URL if it exists.
4234 if (waitingForProxyUrlString.isNotEmpty()) { // A URL is waiting to be loaded.
4236 loadUrl(nestedScrollWebView, waitingForProxyUrlString)
4238 // Reset the waiting for proxy URL string.
4239 nestedScrollWebView.waitingForProxyUrlString = ""
4240 } else { // No URL is waiting to be loaded.
4241 // Reload the existing URL.
4242 nestedScrollWebView.reload()
4250 // Register the Orbot status broadcast receiver. `ContextCompat` must be used until the minimum API >= 34.
4251 ContextCompat.registerReceiver(this, orbotStatusBroadcastReceiver, IntentFilter("org.torproject.android.intent.action.STATUS"), ContextCompat.RECEIVER_EXPORTED)
4253 // Get handles for views that need to be modified.
4254 val bookmarksHeaderLinearLayout = findViewById<LinearLayout>(R.id.bookmarks_header_linearlayout)
4255 val launchBookmarksActivityFab = findViewById<FloatingActionButton>(R.id.launch_bookmarks_activity_fab)
4256 val createBookmarkFolderFab = findViewById<FloatingActionButton>(R.id.create_bookmark_folder_fab)
4257 val createBookmarkFab = findViewById<FloatingActionButton>(R.id.create_bookmark_fab)
4259 // Handle tab selections.
4260 tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
4261 override fun onTabSelected(tab: TabLayout.Tab) {
4262 // Close the find on page bar if it is open.
4263 closeFindOnPage(null)
4265 // Update the view pager when it has quiesced. Otherwise, if a page launched by a new intent on restart has not yet been created, the view pager will not be updated to match the tab layout.
4266 webViewViewPager2.post {
4267 // Select the same page in the view pager.
4268 webViewViewPager2.currentItem = tab.position
4270 // Set the current WebView after the tab layout has quiesced (otherwise, sometimes the wong WebView might be used). See <https://redmine.stoutner.com/issues/1136>
4272 setCurrentWebView(tab.position)
4277 override fun onTabUnselected(tab: TabLayout.Tab) {}
4279 override fun onTabReselected(tab: TabLayout.Tab) {
4280 // Only display the view SSL certificate dialog if the current WebView is not null.
4281 // This can happen if the tab is programmatically reselected while the app is being restarted and is not yet populated.
4282 if (currentWebView != null) {
4283 // Instantiate the View SSL Certificate dialog.
4284 val viewSslCertificateDialogFragment: DialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView!!.webViewFragmentId, currentWebView!!.getFavoriteIcon())
4286 // Display the View SSL Certificate dialog.
4287 viewSslCertificateDialogFragment.show(supportFragmentManager, getString(R.string.view_ssl_certificate))
4292 // Set a touch listener on the bookmarks header linear layout so that touches don't pass through to the button underneath.
4293 bookmarksHeaderLinearLayout.setOnTouchListener { _: View?, _: MotionEvent? -> true }
4295 // Set the launch bookmarks activity floating action button to launch the bookmarks activity.
4296 launchBookmarksActivityFab.setOnClickListener {
4297 // Get a copy of the favorite icon bitmap.
4298 val currentFavoriteIconBitmap = currentWebView!!.getFavoriteIcon()
4300 // Create a favorite icon byte array output stream.
4301 val currentFavoriteIconByteArrayOutputStream = ByteArrayOutputStream()
4303 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
4304 currentFavoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, currentFavoriteIconByteArrayOutputStream)
4306 // Convert the favorite icon byte array stream to a byte array.
4307 val currentFavoriteIconByteArray = currentFavoriteIconByteArrayOutputStream.toByteArray()
4309 // Create an intent to launch the bookmarks activity.
4310 val bookmarksIntent = Intent(applicationContext, BookmarksActivity::class.java)
4312 // Add the extra information to the intent.
4313 bookmarksIntent.putExtra(CURRENT_FOLDER_ID, currentBookmarksFolderId)
4314 bookmarksIntent.putExtra(CURRENT_TITLE, currentWebView!!.title)
4315 bookmarksIntent.putExtra(CURRENT_URL, currentWebView!!.url)
4316 bookmarksIntent.putExtra(CURRENT_FAVORITE_ICON_BYTE_ARRAY, currentFavoriteIconByteArray)
4319 startActivity(bookmarksIntent)
4322 // Set the create new bookmark folder floating action button to display an alert dialog.
4323 createBookmarkFolderFab.setOnClickListener {
4324 // Create a create bookmark folder dialog.
4325 val createBookmarkFolderDialog: DialogFragment = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView!!.getFavoriteIcon())
4327 // Show the create bookmark folder dialog.
4328 createBookmarkFolderDialog.show(supportFragmentManager, getString(R.string.create_folder))
4331 // Set the create new bookmark floating action button to display an alert dialog.
4332 createBookmarkFab.setOnClickListener {
4333 // Instantiate the create bookmark dialog.
4334 val createBookmarkDialog: DialogFragment = CreateBookmarkDialog.createBookmark(currentWebView!!.url!!, currentWebView!!.title!!, currentWebView!!.getFavoriteIcon())
4336 // Display the create bookmark dialog.
4337 createBookmarkDialog.show(supportFragmentManager, getString(R.string.create_bookmark))
4340 // Search for the string on the page whenever a character changes in the find on page edit text.
4341 findOnPageEditText.addTextChangedListener(object : TextWatcher {
4342 override fun beforeTextChanged(charSequence: CharSequence, start: Int, count: Int, after: Int) {
4346 override fun onTextChanged(charSequence: CharSequence, start: Int, before: Int, count: Int) {
4350 override fun afterTextChanged(editable: Editable) {
4351 // 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.
4352 currentWebView?.findAllAsync(findOnPageEditText.text.toString())
4356 // Set the `check mark` button for the find on page edit text keyboard to close the soft keyboard.
4357 findOnPageEditText.setOnKeyListener { _: View?, keyCode: Int, keyEvent: KeyEvent ->
4358 if ((keyEvent.action == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
4359 // Hide the soft keyboard.
4360 inputMethodManager.hideSoftInputFromWindow(currentWebView!!.windowToken, 0)
4362 // Consume the event.
4363 return@setOnKeyListener true
4364 } else { // A different key was pressed.
4365 // Do not consume the event.
4366 return@setOnKeyListener false
4370 // Implement swipe to refresh.
4371 swipeRefreshLayout.setOnRefreshListener {
4372 // Reload the website.
4373 currentWebView!!.reload()
4376 // Store the default progress view offsets.
4377 defaultProgressViewStartOffset = swipeRefreshLayout.progressViewStartOffset
4378 defaultProgressViewEndOffset = swipeRefreshLayout.progressViewEndOffset
4380 // Set the refresh color scheme according to the theme.
4381 swipeRefreshLayout.setColorSchemeResources(R.color.blue_text)
4383 // Initialize a color background typed value.
4384 val colorBackgroundTypedValue = TypedValue()
4386 // Get the color background from the theme.
4387 theme.resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true)
4389 // Get the color background int from the typed value.
4390 val colorBackgroundInt = colorBackgroundTypedValue.data
4392 // Set the swipe refresh background color.
4393 swipeRefreshLayout.setProgressBackgroundColorSchemeColor(colorBackgroundInt)
4395 // Set the drawer titles, which identify the drawer layouts in accessibility mode.
4396 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer))
4397 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks))
4399 // Load the bookmarks folder.
4400 loadBookmarksFolder()
4402 // Handle clicks on bookmarks.
4403 bookmarksListView.onItemClickListener = AdapterView.OnItemClickListener { _: AdapterView<*>?, _: View?, _: Int, id: Long ->
4404 // Convert the id from long to int to match the format of the bookmarks database.
4405 val databaseId = id.toInt()
4407 // Get the bookmark cursor for this ID.
4408 val bookmarkCursor = bookmarksDatabaseHelper!!.getBookmark(databaseId)
4410 // Move the bookmark cursor to the first row.
4411 bookmarkCursor.moveToFirst()
4413 // Act upon the bookmark according to the type.
4414 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndexOrThrow(IS_FOLDER)) == 1) { // The selected bookmark is a folder.
4415 // Store the folder ID.
4416 currentBookmarksFolderId = bookmarkCursor.getLong(bookmarkCursor.getColumnIndexOrThrow(FOLDER_ID))
4418 // Load the new folder.
4419 loadBookmarksFolder()
4420 } else { // The selected bookmark is not a folder.
4421 // Load the bookmark URL.
4422 loadUrl(currentWebView!!, bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BOOKMARK_URL)))
4424 // Close the bookmarks drawer if it is not pinned.
4425 if (!bookmarksDrawerPinned)
4426 drawerLayout.closeDrawer(GravityCompat.END)
4429 // Close the cursor.
4430 bookmarkCursor.close()
4433 // Handle long-presses on bookmarks.
4434 bookmarksListView.onItemLongClickListener = AdapterView.OnItemLongClickListener { _: AdapterView<*>?, _: View?, _: Int, id: Long ->
4435 // Convert the database ID from `long` to `int`.
4436 val databaseId = id.toInt()
4438 // Run the commands associated with the type.
4439 if (bookmarksDatabaseHelper!!.isFolder(databaseId)) { // The bookmark is a folder.
4440 // Get the folder ID.
4441 val folderId = bookmarksDatabaseHelper!!.getFolderId(databaseId)
4443 // Get a cursor of all the bookmarks in the folder.
4444 val bookmarksCursor = bookmarksDatabaseHelper!!.getFolderBookmarks(folderId)
4446 // Move to the first entry in the cursor.
4447 bookmarksCursor.moveToFirst()
4449 // Open each bookmark
4450 for (i in 0 until bookmarksCursor.count) {
4451 // Load the bookmark in a new tab, moving to the tab for the first bookmark if the drawer is not pinned.
4452 addNewPage(bookmarksCursor.getString(bookmarksCursor.getColumnIndexOrThrow(BOOKMARK_URL)), adjacent = false, moveToTab = !bookmarksDrawerPinned && (i == 0))
4454 // Move to the next bookmark.
4455 bookmarksCursor.moveToNext()
4458 // Close the cursor.
4459 bookmarksCursor.close()
4460 } else { // The bookmark is not a folder.
4461 // Get the bookmark cursor for this ID.
4462 val bookmarkCursor = bookmarksDatabaseHelper!!.getBookmark(databaseId)
4464 // Move the bookmark cursor to the first row.
4465 bookmarkCursor.moveToFirst()
4467 // Load the bookmark in a new tab and move to the tab if the drawer is not pinned.
4468 addNewPage(bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BOOKMARK_URL)), adjacent = true, moveToTab = !bookmarksDrawerPinned)
4470 // Close the cursor.
4471 bookmarkCursor.close()
4474 // Close the bookmarks drawer if it is not pinned.
4475 if (!bookmarksDrawerPinned)
4476 drawerLayout.closeDrawer(GravityCompat.END)
4478 // Consume the event.
4482 // The drawer listener is used to update the navigation menu.
4483 drawerLayout.addDrawerListener(object : DrawerLayout.DrawerListener {
4484 override fun onDrawerSlide(drawerView: View, slideOffset: Float) {}
4486 override fun onDrawerOpened(drawerView: View) {}
4488 override fun onDrawerClosed(drawerView: View) {}
4490 override fun onDrawerStateChanged(newState: Int) {
4491 if (newState == DrawerLayout.STATE_SETTLING || newState == DrawerLayout.STATE_DRAGGING) { // A drawer is opening or closing.
4492 // Update the navigation menu items if the WebView is not null.
4493 if (currentWebView != null) {
4494 // Set the enabled status of the menu items.
4495 navigationBackMenuItem.isEnabled = currentWebView!!.canGoBack()
4496 navigationForwardMenuItem.isEnabled = currentWebView!!.canGoForward()
4497 navigationScrollToBottomMenuItem.isEnabled = (currentWebView!!.canScrollVertically(-1) || currentWebView!!.canScrollVertically(1))
4498 navigationHistoryMenuItem.isEnabled = currentWebView!!.canGoBack() || currentWebView!!.canGoForward()
4500 // Update the scroll menu item.
4501 if (currentWebView!!.scrollY == 0) { // The WebView is scrolled to the top.
4503 navigationScrollToBottomMenuItem.title = getString(R.string.scroll_to_bottom)
4506 navigationScrollToBottomMenuItem.icon = AppCompatResources.getDrawable(applicationContext, R.drawable.move_down_enabled)
4507 } else { // The WebView is not scrolled to the top.
4509 navigationScrollToBottomMenuItem.title = getString(R.string.scroll_to_top)
4512 navigationScrollToBottomMenuItem.icon = AppCompatResources.getDrawable(applicationContext, R.drawable.move_up_enabled)
4515 // Display the number of blocked requests.
4516 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + currentWebView!!.getRequestsCount(BLOCKED_REQUESTS)
4518 // Hide the keyboard (if displayed).
4519 inputMethodManager.hideSoftInputFromWindow(currentWebView!!.windowToken, 0)
4522 // 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.
4523 urlEditText.clearFocus()
4525 // 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.
4526 // Clearing the focus from the WebView removes any text selection markers and context menus, which otherwise draw above the open drawers.
4527 currentWebView?.clearFocus()
4529 if (bottomAppBar && navigationDrawerFirstView) {
4530 // Reset the navigation drawer first view flag.
4531 navigationDrawerFirstView = false
4533 // Get a handle for the navigation recycler view.
4534 val navigationRecyclerView = navigationView.getChildAt(0) as RecyclerView
4536 // Get the navigation linear layout manager.
4537 val navigationLinearLayoutManager = navigationRecyclerView.layoutManager as LinearLayoutManager
4539 // Scroll the navigation drawer to the bottom.
4540 navigationLinearLayoutManager.scrollToPositionWithOffset(13, 0)
4546 // Inflate a bare WebView to get the default user agent. It is not used to render content on the screen.
4547 @SuppressLint("InflateParams") val webViewLayout = layoutInflater.inflate(R.layout.bare_webview, null, false)
4549 // Get a handle for the WebView.
4550 val bareWebView = webViewLayout.findViewById<WebView>(R.id.bare_webview)
4552 // Store the default user agent.
4553 webViewDefaultUserAgent = bareWebView.settings.userAgentString
4555 // Destroy the bare WebView.
4556 bareWebView.destroy()
4558 // Update the domains settings set.
4559 updateDomainsSettingsSet()
4561 // Instantiate the check filter list helper.
4562 checkFilterListHelper = CheckFilterListHelper()
4565 @SuppressLint("ClickableViewAccessibility")
4566 override fun initializeWebView(nestedScrollWebView: NestedScrollWebView, pagePosition: Int, progressBar: ProgressBar, urlString: String, restoringState: Boolean) {
4567 // Get the WebView theme.
4568 val webViewTheme = sharedPreferences.getString(getString(R.string.webview_theme_key), getString(R.string.webview_theme_default_value))
4570 // Get the WebView theme entry values string array.
4571 val webViewThemeEntryValuesStringArray = resources.getStringArray(R.array.webview_theme_entry_values)
4573 // Set the WebView theme if algorithmic darkening is supported.
4574 if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {
4575 // Set the WebView them. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
4576 if (webViewTheme == webViewThemeEntryValuesStringArray[1]) { // The light theme is selected.
4577 // Turn off algorithmic darkening.
4578 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
4580 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
4581 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
4582 nestedScrollWebView.visibility = View.VISIBLE
4583 } else if (webViewTheme == webViewThemeEntryValuesStringArray[2]) { // The dark theme is selected.
4584 // Turn on algorithmic darkening.
4585 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
4586 } else { // The system default theme is selected.
4587 // Get the current theme status.
4588 val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
4590 // Set the algorithmic darkening according to the current system theme status.
4591 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) { // The system is in day mode.
4592 // Turn off algorithmic darkening.
4593 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
4595 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
4596 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
4597 nestedScrollWebView.visibility = View.VISIBLE
4598 } else { // The system is in night mode.
4599 // Turn on algorithmic darkening.
4600 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
4605 // Set the app bar scrolling.
4606 nestedScrollWebView.isNestedScrollingEnabled = scrollAppBar
4608 // Allow pinch to zoom.
4609 nestedScrollWebView.settings.builtInZoomControls = true
4611 // Hide zoom controls.
4612 nestedScrollWebView.settings.displayZoomControls = false
4614 // Don't allow mixed content (HTTP and HTTPS) on the same website.
4615 nestedScrollWebView.settings.mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW
4617 // Set the WebView to load in overview mode (zoomed out to the maximum width).
4618 nestedScrollWebView.settings.loadWithOverviewMode = true
4620 // Explicitly disable geolocation.
4621 nestedScrollWebView.settings.setGeolocationEnabled(false)
4623 // Allow loading of file:// URLs. This is necessary for opening MHT web archives, which are copied into a temporary cache location.
4624 nestedScrollWebView.settings.allowFileAccess = true
4626 // Create a double-tap gesture detector to toggle full-screen mode.
4627 val doubleTapGestureDetector = GestureDetector(this, object : GestureDetector.SimpleOnGestureListener() {
4628 // Override `onDoubleTap()`. All other events are handled using the default settings.
4629 override fun onDoubleTap(motionEvent: MotionEvent): Boolean {
4630 return if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
4631 // Toggle the full screen browsing mode tracker.
4632 inFullScreenBrowsingMode = !inFullScreenBrowsingMode
4634 // Toggle the full screen browsing mode.
4635 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
4636 // Hide the app bar if specified.
4637 if (hideAppBar) { // App bar hiding is enabled.
4638 // Close the find on page bar if it is visible.
4639 closeFindOnPage(null)
4641 // Hide the tab linear layout.
4642 tabsLinearLayout.visibility = View.GONE
4644 // Hide the app bar.
4647 // Set layout and scrolling parameters according to the position of the app bar.
4648 if (bottomAppBar) { // The app bar is at the bottom.
4649 // Reset the WebView padding to fill the available space.
4650 swipeRefreshLayout.setPadding(0, 0, 0, 0)
4651 } else { // The app bar is at the top.
4652 // Check to see if the app bar is normally scrolled.
4653 if (scrollAppBar) { // The app bar is scrolled when it is displayed.
4654 // Get the swipe refresh layout parameters.
4655 val swipeRefreshLayoutParams = swipeRefreshLayout.layoutParams as CoordinatorLayout.LayoutParams
4657 // Remove the off-screen scrolling layout.
4658 swipeRefreshLayoutParams.behavior = null
4659 } else { // The app bar is not scrolled when it is displayed.
4660 // Remove the padding from the top of the swipe refresh layout.
4661 swipeRefreshLayout.setPadding(0, 0, 0, 0)
4663 // The swipe refresh circle must be moved above the now removed status bar location.
4664 swipeRefreshLayout.setProgressViewOffset(false, -200, defaultProgressViewEndOffset)
4667 } else { // App bar hiding is not enabled.
4668 // Adjust the UI for the bottom app bar.
4670 // Adjust the UI according to the scrolling of the app bar.
4672 // Reset the WebView padding to fill the available space.
4673 swipeRefreshLayout.setPadding(0, 0, 0, 0)
4675 // Move the WebView above the app bar layout.
4676 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
4681 /* Hide the system bars.
4682 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4683 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4684 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4685 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4688 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4689 @Suppress("DEPRECATION")
4690 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
4691 } else { // Switch to normal viewing mode.
4692 // Show the app bar if it was hidden.
4694 // Show the tab linear layout.
4695 tabsLinearLayout.visibility = View.VISIBLE
4697 // Show the app bar.
4701 // Set layout and scrolling parameters according to the position of the app bar.
4702 if (bottomAppBar) { // The app bar is at the bottom.
4705 // Reset the WebView padding to fill the available space.
4706 swipeRefreshLayout.setPadding(0, 0, 0, 0)
4708 // Move the WebView above the app bar layout.
4709 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
4711 } else { // The app bar is at the top.
4712 // Check to see if the app bar is normally scrolled.
4713 if (scrollAppBar) { // The app bar is scrolled when it is displayed.
4714 // Get the swipe refresh layout parameters.
4715 val swipeRefreshLayoutParams = swipeRefreshLayout.layoutParams as CoordinatorLayout.LayoutParams
4717 // Add the off-screen scrolling layout.
4718 swipeRefreshLayoutParams.behavior = AppBarLayout.ScrollingViewBehavior()
4719 } else { // The app bar is not scrolled when it is displayed.
4720 // The swipe refresh layout must be manually moved below the app bar layout.
4721 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0)
4723 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
4724 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight)
4728 // Remove the `SYSTEM_UI` flags from the root frame layout. The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4729 @Suppress("DEPRECATION")
4730 rootFrameLayout.systemUiVisibility = 0
4733 // Consume the double-tap.
4735 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
4741 override fun onFling(motionEvent1: MotionEvent?, motionEvent2: MotionEvent, velocityX: Float, velocityY: Float): Boolean {
4742 // Scroll the bottom app bar if enabled.
4743 if (bottomAppBar && scrollAppBar && !objectAnimator.isRunning && (motionEvent1 != null)) {
4744 // Calculate the Y change.
4745 val motionY = motionEvent2.y - motionEvent1.y
4747 // Scroll the app bar if the change is greater than 50 pixels.
4749 // Animate the bottom app bar onto the screen.
4750 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0f)
4751 } else if (motionY < -50) {
4752 // Animate the bottom app bar off the screen.
4753 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", appBarLayout.height.toFloat())
4757 objectAnimator.start()
4760 // Do not consume the event.
4765 // Pass all touch events on the WebView through the double-tap gesture detector.
4766 nestedScrollWebView.setOnTouchListener { view: View, motionEvent: MotionEvent? ->
4767 // Call `performClick()` on the view, which is required for accessibility.
4770 // Check for double-taps.
4771 doubleTapGestureDetector.onTouchEvent(motionEvent!!)
4774 // Register the WebView for a context menu. This is used to see link targets and download images.
4775 registerForContextMenu(nestedScrollWebView)
4777 // Allow the downloading of files.
4778 nestedScrollWebView.setDownloadListener { downloadUrlString: String, userAgent: String, contentDisposition: String, mimetype: String, contentLength: Long ->
4779 // Use the specified download provider.
4780 if (downloadWithExternalApp) { // Download with an external app.
4781 // Download with an external app.
4782 saveWithExternalApp(downloadUrlString)
4783 } else { // Download with Privacy Browser or Android's download manager.
4784 // Process the content length if it contains data.
4785 val formattedFileSizeString = if (contentLength > 0) { // The content length is greater than 0.
4786 // Format the content length as a string.
4787 NumberFormat.getInstance().format(contentLength) + " " + getString(R.string.bytes)
4788 } else { // The content length is not greater than 0.
4789 // Set the formatted file size string to be `unknown size`.
4790 getString(R.string.unknown_size)
4793 // Get the file name from the content disposition.
4794 val fileNameString = UrlHelper.getFileName(this, contentDisposition, mimetype, downloadUrlString)
4796 // Instantiate the save dialog according.
4797 val saveDialogFragment = SaveDialog.saveUrl(downloadUrlString, fileNameString, formattedFileSizeString, userAgent, nestedScrollWebView.acceptCookies)
4799 // 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.
4801 // Show the save dialog.
4802 saveDialogFragment.show(supportFragmentManager, getString(R.string.save_dialog))
4803 } catch (exception: Exception) { // The dialog could not be shown.
4804 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
4805 pendingDialogsArrayList.add(PendingDialogDataClass(saveDialogFragment, getString(R.string.save_dialog)))
4809 // Get the current page position.
4810 val currentPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
4812 // Get the corresponding tab.
4813 val tab = tabLayout.getTabAt(currentPagePosition)!!
4815 // Get the tab custom view.
4816 val tabCustomView = tab.customView!!
4818 // Get the tab views.
4819 val tabFavoriteIconImageView = tabCustomView.findViewById<ImageView>(R.id.favorite_icon_imageview)
4820 val tabTitleTextView = tabCustomView.findViewById<TextView>(R.id.title_textview)
4822 // Restore the previous webpage favorite icon and title if the title is currently set to `Loading...`.
4823 if (tabTitleTextView.text.toString() == getString(R.string.loading)) {
4824 // Restore the previous webpage title text.
4825 tabTitleTextView.text = nestedScrollWebView.previousWebpageTitle
4827 // Restore the previous webpage favorite icon if it is not null.
4828 if (nestedScrollWebView.previousFavoriteIconDrawable != null)
4829 tabFavoriteIconImageView.setImageDrawable(nestedScrollWebView.previousFavoriteIconDrawable)
4833 // Update the find on page count.
4834 nestedScrollWebView.setFindListener { activeMatchOrdinal, numberOfMatches, isDoneCounting ->
4835 if (isDoneCounting && (numberOfMatches == 0)) { // There are no matches.
4836 // Set the find on page count text view to be `0/0`.
4837 findOnPageCountTextView.setText(R.string.zero_of_zero)
4838 } else if (isDoneCounting) { // There are matches.
4839 // The active match ordinal is zero-based.
4840 val activeMatch = activeMatchOrdinal + 1
4842 // Build the match string.
4843 val matchString = "$activeMatch/$numberOfMatches"
4845 // Update the find on page count text view.
4846 findOnPageCountTextView.text = matchString
4850 // Process scroll changes.
4851 nestedScrollWebView.setOnScrollChangeListener { _: View?, _: Int, _: Int, _: Int, _: Int ->
4852 // Set the swipe to refresh status.
4853 if (nestedScrollWebView.swipeToRefresh) // Only enable swipe to refresh if the WebView is scrolled to the top.
4854 swipeRefreshLayout.isEnabled = nestedScrollWebView.scrollY == 0
4855 else // Disable swipe to refresh.
4856 swipeRefreshLayout.isEnabled = false
4858 // Reinforce the system UI visibility flags if in full screen browsing mode.
4859 // This hides the status and navigation bars, which are displayed if other elements are shown, like dialog boxes, the options menu, or the keyboard.
4860 if (inFullScreenBrowsingMode) {
4861 /* Hide the system bars.
4862 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4863 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4864 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4865 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4868 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4869 @Suppress("DEPRECATION")
4870 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
4874 // Set the web chrome client.
4875 nestedScrollWebView.webChromeClient = object : WebChromeClient() {
4876 // Update the progress bar when a page is loading.
4877 override fun onProgressChanged(view: WebView, progress: Int) {
4878 // Update the progress bar.
4879 progressBar.progress = progress
4881 // Set the visibility of the progress bar.
4882 if (progress < 100) {
4883 // Show the progress bar.
4884 progressBar.visibility = View.VISIBLE
4886 // Hide the progress bar.
4887 progressBar.visibility = View.GONE
4889 //Stop the swipe to refresh indicator if it is running
4890 swipeRefreshLayout.isRefreshing = false
4892 // 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.
4893 nestedScrollWebView.visibility = View.VISIBLE
4897 // Set the favorite icon when it changes.
4898 override fun onReceivedIcon(view: WebView, icon: Bitmap) {
4899 // 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.
4900 // This prevents low resolution icons from replacing high resolution one.
4901 // The check for the visibility of the progress bar can possibly be removed once https://redmine.stoutner.com/issues/747 is fixed.
4902 if ((progressBar.visibility == View.GONE) && (icon.height > nestedScrollWebView.getFavoriteIconHeight())) {
4903 // Store the new favorite icon.
4904 nestedScrollWebView.setFavoriteIcon(icon)
4906 // Get the current page position.
4907 val currentPosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
4909 // Get the current tab.
4910 val tab = tabLayout.getTabAt(currentPosition)
4912 // Check to see if the tab has been populated.
4914 // Get the custom view from the tab.
4915 val tabView = tab.customView
4917 // Check to see if the custom tab view has been populated.
4918 if (tabView != null) {
4919 // Get the favorite icon image view from the tab.
4920 val tabFavoriteIconImageView = tabView.findViewById<ImageView>(R.id.favorite_icon_imageview)
4922 // Display the favorite icon in the tab.
4923 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 128, 128, true))
4929 // Save a copy of the title when it changes.
4930 override fun onReceivedTitle(view: WebView, title: String) {
4931 // Get the current page position.
4932 val currentPosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
4934 // Get the current tab.
4935 val tab = tabLayout.getTabAt(currentPosition)
4937 // Only populate the title text view if the tab has been fully created.
4939 // Get the custom view from the tab.
4940 val tabView = tab.customView
4942 // Only populate the title text view if the tab view has been fully populated.
4943 if (tabView != null) {
4944 // Get the title text view from the tab.
4945 val tabTitleTextView = tabView.findViewById<TextView>(R.id.title_textview)
4947 // Set the title according to the URL.
4948 if (title == "about:blank") {
4949 // Set the title to indicate a new tab.
4950 tabTitleTextView.setText(R.string.new_tab)
4952 // Set the title as the tab text.
4953 tabTitleTextView.text = title
4959 // Enter full screen video.
4960 override fun onShowCustomView(video: View, callback: CustomViewCallback) {
4961 // Set the full screen video flag.
4962 displayingFullScreenVideo = true
4964 // Hide the keyboard.
4965 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.windowToken, 0)
4967 // Hide the coordinator layout.
4968 coordinatorLayout.visibility = View.GONE
4970 /* Hide the system bars.
4971 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4972 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4973 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4974 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4977 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4978 @Suppress("DEPRECATION")
4979 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
4981 // Disable the sliding drawers.
4982 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
4984 // Add the video view to the full screen video frame layout.
4985 fullScreenVideoFrameLayout.addView(video)
4987 // Show the full screen video frame layout.
4988 fullScreenVideoFrameLayout.visibility = View.VISIBLE
4990 // Disable the screen timeout while the video is playing. YouTube does this automatically, but not all other videos do.
4991 fullScreenVideoFrameLayout.keepScreenOn = true
4994 // Exit full screen video.
4995 override fun onHideCustomView() {
4996 // Exit the full screen video.
4997 exitFullScreenVideo()
5001 override fun onShowFileChooser(webView: WebView, filePathCallback: ValueCallback<Array<Uri>>, fileChooserParams: FileChooserParams): Boolean {
5002 // Store the file path callback.
5003 fileChooserCallback = filePathCallback
5005 // Create a file chooser intent.
5006 val fileChooserIntent = Intent(Intent.ACTION_GET_CONTENT)
5008 // Request an openable file.
5009 fileChooserIntent.addCategory(Intent.CATEGORY_OPENABLE)
5011 // Set the file type to everything. The file chooser params cannot be used to create the intent because it only selects the first specified file type. See <https://redmine.stoutner.com/issues/1197>.
5012 fileChooserIntent.type = "*/*"
5014 // Launch the file chooser intent.
5015 browseFileUploadActivityResultLauncher.launch(fileChooserIntent)
5017 // Handle the event.
5021 nestedScrollWebView.webViewClient = object : WebViewClient() {
5022 // `shouldOverrideUrlLoading` makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
5023 override fun shouldOverrideUrlLoading(view: WebView, webResourceRequest: WebResourceRequest): Boolean {
5024 // Get the URL from the web resource request.
5025 var requestUrlString = webResourceRequest.url.toString()
5027 // Sanitize the url.
5028 requestUrlString = sanitizeUrl(requestUrlString)
5030 // Handle the URL according to the type.
5031 return if (requestUrlString.startsWith("http")) { // Load the URL in Privacy Browser.
5032 // Load the URL. By using `loadUrl()`, instead of `loadUrlFromBase()`, the Referer header will never be sent.
5033 loadUrl(nestedScrollWebView, requestUrlString)
5035 // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
5036 // Custom headers cannot be added if false is returned and the WebView handles the loading of the URL.
5038 } else if (requestUrlString.startsWith("mailto:")) { // Load the email address in an external email program.
5039 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
5040 val emailIntent = Intent(Intent.ACTION_SENDTO)
5042 // Parse the url and set it as the data for the intent.
5043 emailIntent.data = Uri.parse(requestUrlString)
5045 // Open the email program in a new task instead of as part of Privacy Browser.
5046 emailIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
5050 startActivity(emailIntent)
5051 } catch (exception: ActivityNotFoundException) {
5052 // Display a snackbar.
5053 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
5056 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5058 } else if (requestUrlString.startsWith("tel:")) { // Load the phone number in the dialer.
5059 // Create a dial intent.
5060 val dialIntent = Intent(Intent.ACTION_DIAL)
5062 // Add the phone number to the intent.
5063 dialIntent.data = Uri.parse(requestUrlString)
5065 // Open the dialer in a new task instead of as part of Privacy Browser.
5066 dialIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
5070 startActivity(dialIntent)
5071 } catch (exception: ActivityNotFoundException) {
5072 // Display a snackbar.
5073 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
5076 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5078 } else { // Load a system chooser to select an app that can handle the URL.
5079 // Create a generic intent to open an app.
5080 val genericIntent = Intent(Intent.ACTION_VIEW)
5082 // Add the URL to the intent.
5083 genericIntent.data = Uri.parse(requestUrlString)
5085 // List all apps that can handle the URL instead of just opening the first one.
5086 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE)
5088 // Open the app in a new task instead of as part of Privacy Browser.
5089 genericIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
5093 startActivity(genericIntent)
5094 } catch (exception: ActivityNotFoundException) {
5095 // Display a snackbar.
5096 Snackbar.make(nestedScrollWebView, getString(R.string.unrecognized_url, requestUrlString), Snackbar.LENGTH_SHORT).show()
5099 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5104 // Check requests against the block lists.
5105 override fun shouldInterceptRequest(view: WebView, webResourceRequest: WebResourceRequest): WebResourceResponse? {
5107 val requestUrlString = webResourceRequest.url.toString()
5109 // Check to see if the resource request is for the main URL.
5110 if (requestUrlString == nestedScrollWebView.currentUrl) {
5111 // `return null` loads the resource request, which should never be blocked if it is the main URL.
5115 // 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.
5116 while (ultraPrivacy == null) {
5118 // Check to see if the filter lists have been populated after 100 ms.
5120 } catch (exception: InterruptedException) {
5125 // Create an empty web resource response to be used if the resource request is blocked.
5126 val emptyWebResourceResponse = WebResourceResponse("text/plain", "utf8", ByteArrayInputStream("".toByteArray()))
5128 // Initialize the variables.
5129 var allowListResultStringArray: Array<String>? = null
5130 var isThirdPartyRequest = false
5132 // Get the current URL. `.getUrl()` throws an error because operations on the WebView cannot be made from this thread.
5133 var currentBaseDomain = nestedScrollWebView.currentDomainName
5135 // Store a copy of the current domain for use in later requests.
5136 val currentDomain = currentBaseDomain
5138 // Get the request host name.
5139 var requestBaseDomain = webResourceRequest.url.host
5141 // Only check for third-party requests if the current base domain is not empty and the request domain is not null.
5142 if (currentBaseDomain.isNotEmpty() && (requestBaseDomain != null)) {
5143 // Determine the current base domain.
5144 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5145 // Remove the first subdomain.
5146 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1)
5149 // Determine the request base domain.
5150 while (requestBaseDomain!!.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5151 // Remove the first subdomain.
5152 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1)
5155 // Update the third party request tracker.
5156 isThirdPartyRequest = currentBaseDomain != requestBaseDomain
5159 // Get the current WebView page position.
5160 val webViewPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
5162 // Determine if the WebView is currently displayed.
5163 val webViewDisplayed = (webViewPagePosition == tabLayout.selectedTabPosition)
5165 // Block third-party requests if enabled.
5166 if (isThirdPartyRequest && nestedScrollWebView.blockAllThirdPartyRequests) {
5167 // Add the result to the resource requests.
5168 nestedScrollWebView.addResourceRequest(arrayOf(REQUEST_THIRD_PARTY, requestUrlString))
5170 // Increment the blocked requests counters.
5171 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5172 nestedScrollWebView.incrementRequestsCount(THIRD_PARTY_REQUESTS)
5174 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5175 if (webViewDisplayed) {
5176 // Updating the UI must be run from the UI thread.
5178 // Update the menu item titles.
5179 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5181 // Update the options menu if it has been populated.
5182 if (optionsMenu != null) {
5183 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5184 optionsBlockAllThirdPartyRequestsMenuItem.title =
5185 nestedScrollWebView.getRequestsCount(THIRD_PARTY_REQUESTS).toString() + " - " + getString(R.string.block_all_third_party_requests)
5190 // The resource request was blocked. Return an empty web resource response.
5191 return emptyWebResourceResponse
5194 // Check UltraList if it is enabled.
5195 if (nestedScrollWebView.ultraListEnabled) {
5196 // Check the URL against UltraList.
5197 val ultraListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, ultraList)
5199 // Process the UltraList results.
5200 if (ultraListResults[0] == REQUEST_BLOCKED) { // The resource request matched UltraList's block list.
5201 // Add the result to the resource requests.
5202 nestedScrollWebView.addResourceRequest(arrayOf(ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]))
5204 // Increment the blocked requests counters.
5205 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5206 nestedScrollWebView.incrementRequestsCount(com.stoutner.privacybrowser.views.ULTRALIST)
5208 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5209 if (webViewDisplayed) {
5210 // Updating the UI must be run from the UI thread.
5212 // Update the menu item titles.
5213 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5215 // Update the options menu if it has been populated.
5216 if (optionsMenu != null) {
5217 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5218 optionsUltraListMenuItem.title = nestedScrollWebView.getRequestsCount(com.stoutner.privacybrowser.views.ULTRALIST).toString() + " - " + getString(R.string.ultralist)
5223 // The resource request was blocked. Return an empty web resource response.
5224 return emptyWebResourceResponse
5225 } else if (ultraListResults[0] == REQUEST_ALLOWED) { // The resource request matched UltraList's allow list.
5226 // Add an allow list entry to the resource requests array.
5227 nestedScrollWebView.addResourceRequest(arrayOf(ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]))
5229 // The resource request has been allowed by UltraList. `return null` loads the requested resource.
5234 // Check UltraPrivacy if it is enabled.
5235 if (nestedScrollWebView.ultraPrivacyEnabled) {
5236 // Check the URL against UltraPrivacy.
5237 val ultraPrivacyResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, ultraPrivacy!!)
5239 // Process the UltraPrivacy results.
5240 if (ultraPrivacyResults[0] == REQUEST_BLOCKED) { // The resource request matched UltraPrivacy's block list.
5241 // Add the result to the resource requests.
5242 nestedScrollWebView.addResourceRequest(arrayOf(ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5243 ultraPrivacyResults[5]))
5245 // Increment the blocked requests counters.
5246 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5247 nestedScrollWebView.incrementRequestsCount(ULTRAPRIVACY)
5249 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5250 if (webViewDisplayed) {
5251 // Updating the UI must be run from the UI thread.
5253 // Update the menu item titles.
5254 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5256 // Update the options menu if it has been populated.
5257 if (optionsMenu != null) {
5258 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5259 optionsUltraPrivacyMenuItem.title = nestedScrollWebView.getRequestsCount(ULTRAPRIVACY).toString() + " - " + getString(R.string.ultraprivacy)
5264 // The resource request was blocked. Return an empty web resource response.
5265 return emptyWebResourceResponse
5266 } else if (ultraPrivacyResults[0] == REQUEST_ALLOWED) { // The resource request matched UltraPrivacy's allow list.
5267 // Add an allow list entry to the resource requests array.
5268 nestedScrollWebView.addResourceRequest(arrayOf(ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5269 ultraPrivacyResults[5]))
5271 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
5276 // Check EasyList if it is enabled.
5277 if (nestedScrollWebView.easyListEnabled) {
5278 // Check the URL against EasyList.
5279 val easyListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, easyList)
5281 // Process the EasyList results.
5282 if (easyListResults[0] == REQUEST_BLOCKED) { // The resource request matched EasyList's block list.
5283 // Add the result to the resource requests.
5284 nestedScrollWebView.addResourceRequest(arrayOf(easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]))
5286 // Increment the blocked requests counters.
5287 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5288 nestedScrollWebView.incrementRequestsCount(EASYLIST)
5290 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5291 if (webViewDisplayed) {
5292 // Updating the UI must be run from the UI thread.
5294 // Update the menu item titles.
5295 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5297 // Update the options menu if it has been populated.
5298 if (optionsMenu != null) {
5299 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5300 optionsEasyListMenuItem.title = nestedScrollWebView.getRequestsCount(EASYLIST).toString() + " - " + getString(R.string.easylist)
5305 // The resource request was blocked. Return an empty web resource response.
5306 return emptyWebResourceResponse
5307 } else if (easyListResults[0] == REQUEST_ALLOWED) { // The resource request matched EasyList's allow list.
5308 // Update the allow list result string array tracker.
5309 allowListResultStringArray = arrayOf(easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5])
5313 // Check EasyPrivacy if it is enabled.
5314 if (nestedScrollWebView.easyPrivacyEnabled) {
5315 // Check the URL against EasyPrivacy.
5316 val easyPrivacyResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, easyPrivacy)
5318 // Process the EasyPrivacy results.
5319 if (easyPrivacyResults[0] == REQUEST_BLOCKED) { // The resource request matched EasyPrivacy's block list.
5320 // Add the result to the resource requests.
5321 nestedScrollWebView.addResourceRequest(arrayOf(easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5]))
5323 // Increment the blocked requests counters.
5324 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5325 nestedScrollWebView.incrementRequestsCount(EASYPRIVACY)
5327 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5328 if (webViewDisplayed) {
5329 // Updating the UI must be run from the UI thread.
5331 // Update the menu item titles.
5332 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5334 // Update the options menu if it has been populated.
5335 if (optionsMenu != null) {
5336 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5337 optionsEasyPrivacyMenuItem.title = nestedScrollWebView.getRequestsCount(EASYPRIVACY).toString() + " - " + getString(R.string.easyprivacy)
5342 // The resource request was blocked. Return an empty web resource response.
5343 return emptyWebResourceResponse
5344 } else if (easyPrivacyResults[0] == REQUEST_ALLOWED) { // The resource request matched EasyPrivacy's allow list.
5345 // Update the allow list result string array tracker.
5346 allowListResultStringArray = arrayOf(easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5])
5350 // Check Fanboy’s Annoyance List if it is enabled.
5351 if (nestedScrollWebView.fanboysAnnoyanceListEnabled) {
5352 // Check the URL against Fanboy's Annoyance List.
5353 val fanboysAnnoyanceListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, fanboysAnnoyanceList)
5355 // Process the Fanboy's Annoyance List results.
5356 if (fanboysAnnoyanceListResults[0] == REQUEST_BLOCKED) { // The resource request matched Fanboy's Annoyance List's block list.
5357 // Add the result to the resource requests.
5358 nestedScrollWebView.addResourceRequest(arrayOf(fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5359 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]))
5361 // Increment the blocked requests counters.
5362 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5363 nestedScrollWebView.incrementRequestsCount(FANBOYS_ANNOYANCE_LIST)
5365 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5366 if (webViewDisplayed) {
5367 // Updating the UI must be run from the UI thread.
5369 // Update the menu item titles.
5370 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5372 // Update the options menu if it has been populated.
5373 if (optionsMenu != null) {
5374 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5375 optionsFanboysAnnoyanceListMenuItem.title = nestedScrollWebView.getRequestsCount(FANBOYS_ANNOYANCE_LIST).toString() + " - " + getString(R.string.fanboys_annoyance_list)
5380 // The resource request was blocked. Return an empty web resource response.
5381 return emptyWebResourceResponse
5382 } else if (fanboysAnnoyanceListResults[0] == REQUEST_ALLOWED) { // The resource request matched Fanboy's Annoyance List's allow list.
5383 // Update the allow list result string array tracker.
5384 allowListResultStringArray = arrayOf(fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5385 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5])
5387 } else if (nestedScrollWebView.fanboysSocialBlockingListEnabled) { // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
5388 // Check the URL against Fanboy's Annoyance List.
5389 val fanboysSocialListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, fanboysSocialList)
5391 // Process the Fanboy's Social Blocking List results.
5392 if (fanboysSocialListResults[0] == REQUEST_BLOCKED) { // The resource request matched Fanboy's Social Blocking List's block list.
5393 // Add the result to the resource requests.
5394 nestedScrollWebView.addResourceRequest(arrayOf(fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5395 fanboysSocialListResults[4], fanboysSocialListResults[5]))
5397 // Increment the blocked requests counters.
5398 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5399 nestedScrollWebView.incrementRequestsCount(FANBOYS_SOCIAL_BLOCKING_LIST)
5401 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5402 if (webViewDisplayed) {
5403 // Updating the UI must be run from the UI thread.
5405 // Update the menu item titles.
5406 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5408 // Update the options menu if it has been populated.
5409 if (optionsMenu != null) {
5410 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5411 optionsFanboysSocialBlockingListMenuItem.title =
5412 nestedScrollWebView.getRequestsCount(FANBOYS_SOCIAL_BLOCKING_LIST).toString() + " - " + getString(R.string.fanboys_social_blocking_list)
5417 // The resource request was blocked. Return an empty web resource response.
5418 return emptyWebResourceResponse
5419 } else if (fanboysSocialListResults[0] == REQUEST_ALLOWED) { // The resource request matched Fanboy's Social Blocking List's allow list.
5420 // Update the allow list result string array tracker.
5421 allowListResultStringArray = arrayOf(fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3], fanboysSocialListResults[4],
5422 fanboysSocialListResults[5])
5426 // Add the request to the log because it hasn't been processed by any of the previous checks.
5427 if (allowListResultStringArray != null) { // The request was processed by an allow list.
5428 nestedScrollWebView.addResourceRequest(allowListResultStringArray)
5429 } else { // The request didn't match any filter list entry. Log it as a default request.
5430 nestedScrollWebView.addResourceRequest(arrayOf(REQUEST_DEFAULT, requestUrlString))
5433 // The resource request has not been blocked. `return null` loads the requested resource.
5437 // Handle HTTP authentication requests.
5438 override fun onReceivedHttpAuthRequest(view: WebView, handler: HttpAuthHandler, host: String, realm: String) {
5439 // Store the handler.
5440 nestedScrollWebView.httpAuthHandler = handler
5442 // Instantiate an HTTP authentication dialog.
5443 val httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm, nestedScrollWebView.webViewFragmentId)
5445 // Try to show the dialog. WebView can receive an HTTP authentication request even after the app has been paused. Attempting to display a dialog in that state leads to a crash.
5447 // Show the HTTP authentication dialog.
5448 httpAuthenticationDialogFragment.show(supportFragmentManager, getString(R.string.http_authentication))
5449 } catch (exception: Exception) { // The dialog could not be shown.
5450 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
5451 pendingDialogsArrayList.add(PendingDialogDataClass(httpAuthenticationDialogFragment, getString(R.string.http_authentication)))
5455 override fun onPageStarted(webView: WebView, url: String, favicon: Bitmap?) {
5456 // Get the app bar layout height. This can't be done in `applyAppSettings()` because the app bar is not yet populated there.
5457 // 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.
5458 if (appBarLayout.height > 0)
5459 appBarHeight = appBarLayout.height
5461 // Set the padding and layout settings according to the position of the app bar.
5462 if (bottomAppBar) { // The app bar is on the bottom.
5464 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) { // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
5465 // Reset the WebView padding to fill the available space.
5466 swipeRefreshLayout.setPadding(0, 0, 0, 0)
5467 } else { // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
5468 // Move the WebView above the app bar layout.
5469 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
5471 } else { // The app bar is on the top.
5472 // 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.
5473 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) { // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
5474 // No padding is needed because it will automatically be placed below the app bar layout due to the scrolling layout behavior.
5475 swipeRefreshLayout.setPadding(0, 0, 0, 0)
5477 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5478 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10, defaultProgressViewEndOffset)
5479 } else { // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
5480 // The swipe refresh layout must be manually moved below the app bar layout.
5481 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0)
5483 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5484 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight)
5488 // Reset the list of resource requests.
5489 nestedScrollWebView.clearResourceRequests()
5491 // Reset the requests counters.
5492 nestedScrollWebView.resetRequestsCounters()
5494 // Get the current page position.
5495 val currentPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
5497 // Update the URL text bar if the page is currently selected and the URL edit text is not currently being edited.
5498 if ((tabLayout.selectedTabPosition == currentPagePosition) && !urlEditText.hasFocus()) {
5499 // Display the formatted URL text. The nested scroll WebView current URL preserves any initial `view-source:`, and opposed to the method URL variable.
5500 urlEditText.setText(nestedScrollWebView.currentUrl)
5502 // Highlight the URL syntax.
5503 UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
5505 // Hide the keyboard.
5506 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.windowToken, 0)
5509 // Reset the list of host IP addresses.
5510 nestedScrollWebView.currentIpAddresses = ""
5512 // Get a URI for the current URL.
5513 val currentUri = Uri.parse(url)
5515 // Get the current domain name.
5516 val currentDomainName = currentUri.host
5518 // Get the IP addresses for the current domain.
5519 if (!currentDomainName.isNullOrEmpty())
5520 GetHostIpAddressesCoroutine.checkPinnedMismatch(currentDomainName, nestedScrollWebView, supportFragmentManager, getString(R.string.pinned_mismatch))
5522 // 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.)
5523 if ((optionsMenu != null) && (webView == currentWebView)) {
5525 optionsRefreshMenuItem.setTitle(R.string.stop)
5527 // Set the icon if it is displayed in the AppBar.
5528 if (displayAdditionalAppBarIcons)
5529 optionsRefreshMenuItem.setIcon(R.drawable.close_blue)
5533 override fun onPageFinished(webView: WebView, url: String) {
5534 // Flush any cookies to persistent storage. The cookie manager has become very lazy about flushing cookies in recent versions.
5535 if (nestedScrollWebView.acceptCookies)
5536 cookieManager.flush()
5538 // Update the Refresh menu item if the options menu has been created and the WebView is currently displayed.
5539 if (optionsMenu != null && (webView == currentWebView)) {
5540 // Reset the Refresh title.
5541 optionsRefreshMenuItem.setTitle(R.string.refresh)
5543 // Reset the icon if it is displayed in the app bar.
5544 if (displayAdditionalAppBarIcons)
5545 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled)
5548 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
5549 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
5550 val privateDataDirectoryString = applicationInfo.dataDir
5552 // Clear the cache, history, and logcat if Incognito Mode is enabled.
5553 if (incognitoModeEnabled) {
5554 // Clear the cache. `true` includes disk files.
5555 nestedScrollWebView.clearCache(true)
5557 // Clear the back/forward history.
5558 nestedScrollWebView.clearHistory()
5560 // Manually delete cache folders.
5562 // Delete the main cache directory.
5563 Runtime.getRuntime().exec("rm -rf $privateDataDirectoryString/cache")
5564 } catch (exception: IOException) {
5565 // Do nothing if an error is thrown.
5568 // Clear the logcat.
5570 // Clear the logcat. `-c` clears the logcat. `-b all` clears all the buffers (instead of just crash, main, and system).
5571 Runtime.getRuntime().exec("logcat -b all -c")
5572 } catch (exception: IOException) {
5577 // Clear the `Service Worker` directory.
5579 // A string array must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
5580 Runtime.getRuntime().exec(arrayOf("rm", "-rf", "$privateDataDirectoryString/app_webview/Default/Service Worker/"))
5581 } catch (exception: IOException) {
5585 // Get the current page position.
5586 val currentPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
5588 // 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.
5589 val currentUrl = nestedScrollWebView.url
5591 // Get the current tab.
5592 val tab = tabLayout.getTabAt(currentPagePosition)
5594 // Update the URL text bar if the page is currently selected and the user is not currently typing in the URL edit text.
5595 // Crash records show that, in some crazy way, it is possible for the current URL to be blank at this point.
5596 // Probably some sort of race condition when Privacy Browser is being resumed.
5597 if ((tabLayout.selectedTabPosition == currentPagePosition) && !urlEditText.hasFocus() && (currentUrl != null)) {
5598 // Check to see if the URL is `about:blank`.
5599 if (currentUrl == "about:blank") { // The WebView is blank.
5600 // Display the hint in the URL edit text.
5601 urlEditText.setText("")
5603 // Request focus for the URL text box.
5604 urlEditText.requestFocus()
5606 // Display the keyboard.
5607 inputMethodManager.showSoftInput(urlEditText, 0)
5609 // Apply the domain settings. This clears any settings from the previous domain.
5610 applyDomainSettings(nestedScrollWebView, "", resetTab = true, reloadWebsite = false, loadUrl = false)
5612 // Only populate the title text view if the tab has been fully created.
5614 // Get the custom view from the tab.
5615 val tabView = tab.customView!!
5617 // Get the title text view from the tab.
5618 val tabTitleTextView = tabView.findViewById<TextView>(R.id.title_textview)
5620 // Set the title as the tab text.
5621 tabTitleTextView.setText(R.string.new_tab)
5623 } else { // The WebView has loaded a webpage.
5624 // Update the URL edit text if it is not currently being edited.
5625 if (!urlEditText.hasFocus()) {
5626 // 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.
5627 val sanitizedUrl = sanitizeUrl(currentUrl)
5629 // Display the final URL. Getting the URL from the WebView instead of using the one provided by `onPageFinished()` makes websites like YouTube function correctly.
5630 urlEditText.setText(sanitizedUrl)
5632 // Highlight the URL syntax.
5633 UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
5636 // Only populate the title text view if the tab has been fully created.
5638 // Get the custom view from the tab.
5639 val tabView = tab.customView!!
5641 // Get the title text view from the tab.
5642 val tabTitleTextView = tabView.findViewById<TextView>(R.id.title_textview)
5644 // Set the title as the tab text. Sometimes `onReceivedTitle()` is not called, especially when navigating history.
5645 tabTitleTextView.text = nestedScrollWebView.title
5651 // Handle SSL Certificate errors. Suppress the lint warning that ignoring the error might be dangerous.
5652 @SuppressLint("WebViewClientOnReceivedSslError")
5653 override fun onReceivedSslError(view: WebView, handler: SslErrorHandler, error: SslError) {
5654 // Get the current website SSL certificate.
5655 val currentWebsiteSslCertificate = error.certificate
5657 // Extract the individual pieces of information from the current website SSL certificate.
5658 val currentWebsiteIssuedToCName = currentWebsiteSslCertificate.issuedTo.cName
5659 val currentWebsiteIssuedToOName = currentWebsiteSslCertificate.issuedTo.oName
5660 val currentWebsiteIssuedToUName = currentWebsiteSslCertificate.issuedTo.uName
5661 val currentWebsiteIssuedByCName = currentWebsiteSslCertificate.issuedBy.cName
5662 val currentWebsiteIssuedByOName = currentWebsiteSslCertificate.issuedBy.oName
5663 val currentWebsiteIssuedByUName = currentWebsiteSslCertificate.issuedBy.uName
5664 val currentWebsiteSslStartDate = currentWebsiteSslCertificate.validNotBeforeDate
5665 val currentWebsiteSslEndDate = currentWebsiteSslCertificate.validNotAfterDate
5667 // Get the pinned SSL certificate.
5668 val (pinnedSslCertificateStringArray, pinnedSslCertificateDateArray) = nestedScrollWebView.getPinnedSslCertificate()
5670 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
5671 if (nestedScrollWebView.hasPinnedSslCertificate() &&
5672 (currentWebsiteIssuedToCName == pinnedSslCertificateStringArray[0]) &&
5673 (currentWebsiteIssuedToOName == pinnedSslCertificateStringArray[1]) &&
5674 (currentWebsiteIssuedToUName == pinnedSslCertificateStringArray[2]) &&
5675 (currentWebsiteIssuedByCName == pinnedSslCertificateStringArray[3]) &&
5676 (currentWebsiteIssuedByOName == pinnedSslCertificateStringArray[4]) &&
5677 (currentWebsiteIssuedByUName == pinnedSslCertificateStringArray[5]) &&
5678 (currentWebsiteSslStartDate == pinnedSslCertificateDateArray[0]) &&
5679 (currentWebsiteSslEndDate == pinnedSslCertificateDateArray[1])) {
5681 // An SSL certificate is pinned and matches the current domain certificate. Proceed to the website without displaying an error.
5683 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
5684 // Store the SSL error handler.
5685 nestedScrollWebView.sslErrorHandler = handler
5687 // Instantiate an SSL certificate error alert dialog.
5688 val sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error, nestedScrollWebView.webViewFragmentId)
5690 // Try to show the dialog. The SSL error handler continues to function even when the app has been stopped. Attempting to display a dialog in that state leads to a crash.
5692 // Show the SSL certificate error dialog.
5693 sslCertificateErrorDialogFragment.show(supportFragmentManager, getString(R.string.ssl_certificate_error))
5694 } catch (exception: Exception) {
5695 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
5696 pendingDialogsArrayList.add(PendingDialogDataClass(sslCertificateErrorDialogFragment, getString(R.string.ssl_certificate_error)))
5702 // Check to see if the state is being restored.
5703 if (restoringState) { // The state is being restored.
5704 // Resume the nested scroll WebView JavaScript timers.
5705 nestedScrollWebView.resumeTimers()
5706 } else if (pagePosition == 0) { // The first page is being loaded.
5707 // Set this nested scroll WebView as the current WebView.
5708 currentWebView = nestedScrollWebView
5710 // Get the intent that started the app.
5711 val launchingIntent = intent
5713 // Reset the intent. This prevents a duplicate tab from being created on restart.
5716 // Get the information from the intent.
5717 val launchingIntentAction = launchingIntent.action
5718 val launchingIntentUriData = launchingIntent.data
5719 val launchingIntentStringExtra = launchingIntent.getStringExtra(Intent.EXTRA_TEXT)
5721 // Parse the launching intent URL. Suppress the suggestions of using elvis expressions as they make the logic very difficult to follow.
5722 @Suppress("IfThenToElvis") val urlToLoadString = if ((launchingIntentAction != null) && (launchingIntentAction == Intent.ACTION_WEB_SEARCH)) { // The intent contains a search string.
5723 // Sanitize the search input and convert it to a search.
5724 val encodedSearchString = try {
5725 URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8")
5726 } catch (exception: UnsupportedEncodingException) {
5730 // Add the search URL to the encodedSearchString
5731 searchURL + encodedSearchString
5732 } else if (launchingIntentUriData != null) { // The launching intent contains a URL formatted as a URI.
5733 // Get the URL from the URI.
5734 launchingIntentUriData.toString()
5735 } else if (launchingIntentStringExtra != null) { // The launching intent contains text that might be a URL.
5736 // Get the URL from the string extra.
5737 launchingIntentStringExtra
5738 } else if (urlString != "") { // The activity has been restarted.
5739 // Load the saved URL.
5741 } else { // The is no saved URL and there is no URL in the intent.
5742 // Load the homepage.
5743 sharedPreferences.getString("homepage", getString(R.string.homepage_default_value))
5746 // Load the website if not waiting for the proxy.
5747 if (waitingForProxy) { // Store the URL to be loaded in the Nested Scroll WebView.
5748 nestedScrollWebView.waitingForProxyUrlString = urlToLoadString!!
5749 } else { // Load the URL.
5750 loadUrl(nestedScrollWebView, urlToLoadString!!)
5752 } else { // This is not the first tab.
5754 loadUrl(nestedScrollWebView, urlString)
5756 // Set the focus and display the keyboard if the URL is blank.
5757 if (urlString == "") {
5758 // Request focus for the URL text box.
5759 urlEditText.requestFocus()
5761 // Display the keyboard once the tab layout has settled.
5763 inputMethodManager.showSoftInput(urlEditText, 0)
5769 private fun loadBookmarksFolder() {
5770 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
5771 bookmarksCursor = bookmarksDatabaseHelper!!.getBookmarksByDisplayOrder(currentBookmarksFolderId)
5773 // Populate the bookmarks cursor adapter.
5774 bookmarksCursorAdapter = object : CursorAdapter(this, bookmarksCursor, false) {
5775 override fun newView(context: Context, cursor: Cursor, parent: ViewGroup): View {
5776 // Inflate the individual item layout.
5777 return layoutInflater.inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false)
5780 override fun bindView(view: View, context: Context, cursor: Cursor) {
5781 // Get handles for the views.
5782 val bookmarkFavoriteIcon = view.findViewById<ImageView>(R.id.bookmark_favorite_icon)
5783 val bookmarkNameTextView = view.findViewById<TextView>(R.id.bookmark_name)
5785 // Get the favorite icon byte array from the cursor.
5786 val favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndexOrThrow(FAVORITE_ICON))
5788 // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
5789 val favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.size)
5791 // Display the bitmap in the bookmark favorite icon.
5792 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap)
5794 // Display the bookmark name from the cursor in the bookmark name text view.
5795 bookmarkNameTextView.text = cursor.getString(cursor.getColumnIndexOrThrow(BOOKMARK_NAME))
5797 // Make the font bold for folders.
5798 if (cursor.getInt(cursor.getColumnIndexOrThrow(IS_FOLDER)) == 1)
5799 bookmarkNameTextView.typeface = Typeface.DEFAULT_BOLD
5800 else // Reset the font to default for normal bookmarks.
5801 bookmarkNameTextView.typeface = Typeface.DEFAULT
5805 // Populate the list view with the adapter.
5806 bookmarksListView.adapter = bookmarksCursorAdapter
5808 // Set the bookmarks drawer title.
5809 if (currentBookmarksFolderId == HOME_FOLDER_ID) // The current bookmarks folder is the home folder.
5810 bookmarksTitleTextView.setText(R.string.bookmarks)
5812 bookmarksTitleTextView.text = bookmarksDatabaseHelper!!.getFolderName(currentBookmarksFolderId)
5815 private fun loadUrl(nestedScrollWebView: NestedScrollWebView, url: String) {
5816 // Sanitize the URL.
5817 val urlString = sanitizeUrl(url)
5819 // Apply the domain settings and load the URL.
5820 applyDomainSettings(nestedScrollWebView, urlString, resetTab = true, reloadWebsite = false, loadUrl = true)
5823 private fun loadUrlFromTextBox() {
5824 // 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.
5825 var unformattedUrlString = urlEditText.text.toString().trim { it <= ' ' }
5827 // Create the formatted URL string.
5830 // Check to see if the unformatted URL string is a valid URL. Otherwise, convert it into a search.
5831 if (unformattedUrlString.startsWith("content://") || unformattedUrlString.startsWith("view-source:")) { // This is a content or source URL.
5832 // Load the entire content URL.
5833 urlString = unformattedUrlString
5834 } else if (Patterns.WEB_URL.matcher(unformattedUrlString).matches() || unformattedUrlString.startsWith("http://") || unformattedUrlString.startsWith("https://") ||
5835 unformattedUrlString.startsWith("file://")) { // This is a standard URL.
5837 // Add `https://` at the beginning if there is no protocol. Otherwise the app will segfault.
5838 if (!unformattedUrlString.startsWith("http") && !unformattedUrlString.startsWith("file://"))
5839 unformattedUrlString = "https://$unformattedUrlString"
5841 // Initialize the unformatted URL.
5842 var unformattedUrl: URL? = null
5844 // Convert the unformatted URL string to a URL.
5846 unformattedUrl = URL(unformattedUrlString)
5847 } catch (exception: MalformedURLException) {
5848 exception.printStackTrace()
5851 // Get the components of the URL.
5852 val scheme = unformattedUrl?.protocol
5853 val authority = unformattedUrl?.authority
5854 val path = unformattedUrl?.path
5855 val query = unformattedUrl?.query
5856 val fragment = unformattedUrl?.ref
5859 val uri = Uri.Builder()
5861 // Build the URI from the components of the URL.
5862 uri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment)
5864 // Decode the URI as a UTF-8 string in.
5866 urlString = URLDecoder.decode(uri.build().toString(), "UTF-8")
5867 } catch (exception: UnsupportedEncodingException) {
5868 // Do nothing. The formatted URL string will remain blank.
5870 } else if (unformattedUrlString.isNotEmpty()) { // This is not a URL, but rather a search string.
5871 // Sanitize the search input.
5872 val encodedSearchString = try {
5873 URLEncoder.encode(unformattedUrlString, "UTF-8")
5874 } catch (exception: UnsupportedEncodingException) {
5878 // Add the base search URL.
5879 urlString = searchURL + encodedSearchString
5882 // 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.
5883 urlEditText.clearFocus()
5886 loadUrl(currentWebView!!, urlString)
5889 override fun navigateHistory(steps: Int) {
5890 // Get the current web back forward list.
5891 val webBackForwardList = currentWebView!!.copyBackForwardList()
5893 // Calculate the target index.
5894 val targetIndex = webBackForwardList.currentIndex + steps
5896 // Get the previous entry data.
5897 val previousUrl = webBackForwardList.getItemAtIndex(targetIndex).url
5898 val previousFavoriteIcon = webBackForwardList.getItemAtIndex(targetIndex).favicon
5900 // Apply the domain settings.
5901 applyDomainSettings(currentWebView!!, previousUrl, resetTab = false, reloadWebsite = false, loadUrl = false)
5903 // Get the current tab.
5904 val tab = tabLayout.getTabAt(tabLayout.selectedTabPosition)!!
5906 // Get the custom view from the tab.
5907 val tabView = tab.customView!!
5909 // Get the favorite icon image view from the tab.
5910 val tabFavoriteIconImageView = tabView.findViewById<ImageView>(R.id.favorite_icon_imageview)
5912 // Store the previous favorite icon.
5913 if (previousFavoriteIcon == null)
5914 currentWebView!!.setFavoriteIcon(defaultFavoriteIconBitmap)
5916 currentWebView!!.setFavoriteIcon(previousFavoriteIcon)
5918 // Display the previous favorite icon in the tab.
5919 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(currentWebView!!.getFavoriteIcon(), 128, 128, true))
5921 // Load the history entry.
5922 currentWebView!!.goBackOrForward(steps)
5924 // Create a handler to update the URL edit box.
5925 val urlEditTextUpdateHandler = Handler(Looper.getMainLooper())
5927 // Create a runnable to update the URL edit box.
5928 val urlEditTextUpdateRunnable = Runnable {
5929 // Update the URL edit text.
5930 urlEditText.setText(currentWebView!!.url)
5932 // Disable the wide viewport if the source is being viewed.
5933 if (currentWebView!!.url!!.startsWith("view-source:"))
5934 currentWebView!!.settings.useWideViewPort = false
5937 // Update the URL edit text after 50 milliseconds, so that the WebView has enough time to navigate to the new URL.
5938 urlEditTextUpdateHandler.postDelayed(urlEditTextUpdateRunnable, 50)
5941 override fun openFile(dialogFragment: DialogFragment) {
5943 val dialog = dialogFragment.dialog!!
5945 // Get handles for the views.
5946 val fileNameEditText = dialog.findViewById<EditText>(R.id.file_name_edittext)
5947 val mhtCheckBox = dialog.findViewById<CheckBox>(R.id.mht_checkbox)
5949 // Get the file path string.
5950 val openFilePath = fileNameEditText.text.toString()
5952 // Apply the domain settings. This resets the favorite icon and removes any domain settings.
5953 applyDomainSettings(currentWebView!!, openFilePath, resetTab = true, reloadWebsite = false, loadUrl = false)
5955 // Open the file according to the type.
5956 if (mhtCheckBox.isChecked) { // Force opening of an MHT file.
5958 // Get the MHT file input stream.
5959 val mhtFileInputStream = contentResolver.openInputStream(Uri.parse(openFilePath))
5961 // Create a temporary MHT file.
5962 val temporaryMhtFile = File.createTempFile(TEMPORARY_MHT_FILE, ".mht", cacheDir)
5964 // Get a file output stream for the temporary MHT file.
5965 val temporaryMhtFileOutputStream = FileOutputStream(temporaryMhtFile)
5967 // Create a transfer byte array.
5968 val transferByteArray = ByteArray(1024)
5970 // Create an integer to track the number of bytes read.
5973 // Copy the temporary MHT file input stream to the MHT output stream.
5974 while (mhtFileInputStream!!.read(transferByteArray).also { bytesRead = it } > 0)
5975 temporaryMhtFileOutputStream.write(transferByteArray, 0, bytesRead)
5977 // Flush the temporary MHT file output stream.
5978 temporaryMhtFileOutputStream.flush()
5980 // Close the streams.
5981 temporaryMhtFileOutputStream.close()
5982 mhtFileInputStream.close()
5984 // Load the temporary MHT file.
5985 currentWebView!!.loadUrl(temporaryMhtFile.toString())
5986 } catch (exception: Exception) {
5987 // Display a snackbar.
5988 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
5990 } else { // Let the WebView handle opening of the file.
5992 currentWebView!!.loadUrl(openFilePath)
5995 // The view parameter cannot be removed because it is called from the layout onClick.
5996 fun openNavigationDrawer(@Suppress("UNUSED_PARAMETER")view: View) {
5997 // Open the navigation drawer.
5998 drawerLayout.openDrawer(GravityCompat.START)
6001 private fun openWithApp(url: String) {
6002 // Create an open with app intent with `ACTION_VIEW`.
6003 val openWithAppIntent = Intent(Intent.ACTION_VIEW)
6005 // Set the URI but not the MIME type. This should open all available apps.
6006 openWithAppIntent.data = Uri.parse(url)
6008 // Flag the intent to open in a new task.
6009 openWithAppIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
6013 // Show the chooser.
6014 startActivity(openWithAppIntent)
6015 } catch (exception: ActivityNotFoundException) { // There are no apps available to open the URL.
6016 // Show a snackbar with the error.
6017 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
6021 private fun openWithBrowser(url: String) {
6023 // Create an open with browser intent with `ACTION_VIEW`.
6024 val openWithBrowserIntent = Intent(Intent.ACTION_VIEW)
6026 // Set the URI and the MIME type. `"text/html"` should load browser options.
6027 openWithBrowserIntent.setDataAndType(Uri.parse(url), "text/html")
6029 // Flag the intent to open in a new task.
6030 openWithBrowserIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
6034 // Show the chooser.
6035 startActivity(openWithBrowserIntent)
6036 } catch (exception: ActivityNotFoundException) { // There are no browsers available to open the URL.
6037 // Show a snackbar with the error.
6038 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
6042 override fun pinnedErrorGoBack() {
6043 // Navigate back one page.
6047 private fun sanitizeUrl(urlString: String): String {
6048 // Initialize a sanitized URL string.
6049 var sanitizedUrlString = urlString
6051 // Sanitize tracking queries.
6052 if (sanitizeTrackingQueries)
6053 sanitizedUrlString = SanitizeUrlHelper.sanitizeTrackingQueries(sanitizedUrlString)
6055 // Sanitize AMP redirects.
6056 if (sanitizeAmpRedirects)
6057 sanitizedUrlString = SanitizeUrlHelper.sanitizeAmpRedirects(sanitizedUrlString)
6059 // Return the sanitized URL string.
6060 return sanitizedUrlString
6063 override fun saveWithAndroidDownloadManager(dialogFragment: DialogFragment) {
6065 val dialog = dialogFragment.dialog!!
6067 // Get handles for the dialog views.
6068 val dialogUrlEditText = dialog.findViewById<EditText>(R.id.url_edittext)
6069 val downloadDirectoryRadioGroup = dialog.findViewById<RadioGroup>(R.id.download_directory_radiogroup)
6070 val dialogFileNameEditText = dialog.findViewById<EditText>(R.id.file_name_edittext)
6072 // Get the string from the edit texts, which may have been modified by the user.
6073 val saveUrlString = dialogUrlEditText.text.toString()
6074 val fileNameString = dialogFileNameEditText.text.toString()
6076 // Get a handle for the system download service.
6077 val downloadManager = getSystemService(DOWNLOAD_SERVICE) as DownloadManager
6080 val downloadRequest = DownloadManager.Request(Uri.parse(saveUrlString))
6082 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
6083 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
6084 if (cookieManager.acceptCookie()) {
6085 // Get the cookies for the URL.
6086 val cookiesString = cookieManager.getCookie(saveUrlString)
6088 // Add the cookies to the download request. In the HTTP request header, cookies are named `Cookie`.
6089 downloadRequest.addRequestHeader("Cookie", cookiesString)
6092 // Get the download directory.
6093 val downloadDirectory = when (downloadDirectoryRadioGroup.checkedRadioButtonId) {
6094 R.id.downloads_radiobutton -> Environment.DIRECTORY_DOWNLOADS
6095 R.id.documents_radiobutton -> Environment.DIRECTORY_DOCUMENTS
6096 R.id.pictures_radiobutton -> Environment.DIRECTORY_PICTURES
6097 else -> Environment.DIRECTORY_MUSIC
6100 // Set the download destination.
6101 downloadRequest.setDestinationInExternalPublicDir(downloadDirectory, fileNameString)
6103 // Allow media scanner to index the download if it is a media file. This is automatic for API >= 29.
6104 @Suppress("DEPRECATION")
6105 if (Build.VERSION.SDK_INT <= 28)
6106 downloadRequest.allowScanningByMediaScanner()
6108 // Add the URL as the description for the download.
6109 downloadRequest.setDescription(saveUrlString)
6111 // Show the download notification after the download is completed.
6112 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
6114 // Initiate the download.
6115 downloadManager.enqueue(downloadRequest)
6118 private fun saveWithExternalApp(url: String) {
6119 // Create a download intent. Not specifying the action type will display the maximum number of options.
6120 val downloadIntent = Intent()
6122 // Set the URI and the mime type.
6123 downloadIntent.setDataAndType(Uri.parse(url), "text/html")
6125 // Flag the intent to open in a new task.
6126 downloadIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
6128 // Show the chooser.
6129 startActivity(Intent.createChooser(downloadIntent, getString(R.string.download_with_external_app)))
6132 override fun saveWithPrivacyBrowser(originalUrlString: String, fileNameString: String, dialogFragment: DialogFragment) {
6133 // Store the URL. This will be used in the save URL activity result launcher.
6134 saveUrlString = if (originalUrlString.startsWith("data:")) {
6135 // Save the original URL.
6139 val dialog = dialogFragment.dialog!!
6141 // Get a handle for the dialog URL edit text.
6142 val dialogUrlEditText = dialog.findViewById<EditText>(R.id.url_edittext)
6144 // Get the URL from the edit text, which may have been modified by the user.
6145 dialogUrlEditText.text.toString()
6148 // Open the file picker.
6149 saveUrlActivityResultLauncher.launch(fileNameString)
6152 private fun setCurrentWebView(pageNumber: Int) {
6153 // Stop the swipe to refresh indicator if it is running
6154 swipeRefreshLayout.isRefreshing = false
6156 // Try to set the current WebView. This will fail if the WebView has not yet been populated.
6158 // Get the WebView tab fragment.
6159 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(pageNumber)
6161 // Get the fragment view.
6162 val webViewFragmentView = webViewTabFragment.view
6164 // Store the current WebView.
6165 currentWebView = webViewFragmentView!!.findViewById(R.id.nestedscroll_webview)
6167 // Update the status of swipe to refresh.
6168 if (currentWebView!!.swipeToRefresh) { // Swipe to refresh is enabled.
6169 // Enable the swipe refresh layout if the WebView is scrolled all the way to the top. It is updated every time the scroll changes.
6170 swipeRefreshLayout.isEnabled = (currentWebView!!.scrollY == 0)
6171 } else { // Swipe to refresh is disabled.
6172 // Disable the swipe refresh layout.
6173 swipeRefreshLayout.isEnabled = false
6176 // Set the cookie status.
6177 cookieManager.setAcceptCookie(currentWebView!!.acceptCookies)
6179 // Update the privacy icons. `true` redraws the icons in the app bar.
6180 updatePrivacyIcons(true)
6182 // Get the current URL.
6183 val urlString = currentWebView!!.url
6185 // Update the URL edit text if not loading a new intent. Otherwise, this will be handled by `onPageStarted()` (if called) and `onPageFinished()`.
6186 if (!loadingNewIntent) { // A new intent is not being loaded.
6187 if ((urlString == null) || (urlString == "about:blank")) { // The WebView is blank.
6188 // Display the hint in the URL edit text.
6189 urlEditText.setText("")
6191 // Request focus for the URL text box.
6192 urlEditText.requestFocus()
6194 // Display the keyboard.
6195 inputMethodManager.showSoftInput(urlEditText, 0)
6196 } else { // The WebView has a loaded URL.
6197 // Clear the focus from the URL text box.
6198 urlEditText.clearFocus()
6200 // Hide the soft keyboard.
6201 inputMethodManager.hideSoftInputFromWindow(currentWebView!!.windowToken, 0)
6203 // Display the current URL in the URL text box.
6204 urlEditText.setText(urlString)
6206 // Highlight the URL syntax.
6207 UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
6209 } else { // A new intent is being loaded.
6210 // Reset the loading new intent flag.
6211 loadingNewIntent = false
6214 // Set the background to indicate the domain settings status.
6215 if (currentWebView!!.domainSettingsApplied) {
6216 // Set a background on the URL relative layout to indicate that custom domain settings are being used.
6217 urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.drawable.domain_settings_url_background)
6219 // Remove any background on the URL relative layout.
6220 urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.color.transparent)
6222 } catch (exception: Exception) { // Try again in 10 milliseconds if the WebView has not yet been populated.
6223 // Create a handler to set the current WebView.
6224 val setCurrentWebViewHandler = Handler(Looper.getMainLooper())
6226 // Create a runnable to set the current WebView.
6227 val setCurrentWebWebRunnable = Runnable {
6228 // Set the current WebView.
6229 setCurrentWebView(pageNumber)
6232 // Try setting the current WebView again after 10 milliseconds.
6233 setCurrentWebViewHandler.postDelayed(setCurrentWebWebRunnable, 10)
6237 // The view parameter cannot be removed because it is called from the layout onClick.
6238 fun toggleBookmarksDrawerPinned(@Suppress("UNUSED_PARAMETER")view: View?) {
6239 // Toggle the bookmarks drawer pinned tracker.
6240 bookmarksDrawerPinned = !bookmarksDrawerPinned
6242 // Update the bookmarks drawer pinned image view.
6243 updateBookmarksDrawerPinnedImageView()
6246 private fun updateBookmarksDrawerPinnedImageView() {
6247 // Set the current icon.
6248 if (bookmarksDrawerPinned)
6249 bookmarksDrawerPinnedImageView.setImageResource(R.drawable.pin_selected)
6251 bookmarksDrawerPinnedImageView.setImageResource(R.drawable.pin)
6254 private fun updateDomainsSettingsSet() {
6255 // Reset the domains settings set.
6256 domainsSettingsSet = HashSet()
6258 // Get a domains cursor.
6259 val domainsCursor = domainsDatabaseHelper!!.domainNameCursorOrderedByDomain
6261 // Get the current count of domains.
6262 val domainsCount = domainsCursor.count
6264 // Get the domain name column index.
6265 val domainNameColumnIndex = domainsCursor.getColumnIndexOrThrow(DOMAIN_NAME)
6267 // Populate the domain settings set.
6268 for (i in 0 until domainsCount) {
6269 // Move the domains cursor to the current row.
6270 domainsCursor.moveToPosition(i)
6272 // Store the domain name in the domain settings set.
6273 domainsSettingsSet.add(domainsCursor.getString(domainNameColumnIndex))
6276 // Close the domains cursor.
6277 domainsCursor.close()
6280 override fun updateFontSize(dialogFragment: DialogFragment) {
6282 val dialog = dialogFragment.dialog!!
6284 // Get a handle for the font size edit text.
6285 val fontSizeEditText = dialog.findViewById<EditText>(R.id.font_size_edittext)
6287 // Initialize the new font size variable with the current font size.
6288 var newFontSize = currentWebView!!.settings.textZoom
6290 // Get the font size from the edit text.
6292 newFontSize = fontSizeEditText.text.toString().toInt()
6293 } catch (exception: Exception) {
6294 // If the edit text does not contain a valid font size do nothing.
6297 // Apply the new font size.
6298 currentWebView!!.settings.textZoom = newFontSize
6301 private fun updatePrivacyIcons(runInvalidateOptionsMenu: Boolean) {
6302 // Only update the privacy icons if the options menu and the current WebView have already been populated.
6303 if ((optionsMenu != null) && (currentWebView != null)) {
6304 // Update the privacy icon.
6305 if (currentWebView!!.settings.javaScriptEnabled) // JavaScript is enabled.
6306 optionsPrivacyMenuItem.setIcon(R.drawable.javascript_enabled)
6307 else if (currentWebView!!.acceptCookies) // JavaScript is disabled but cookies are enabled.
6308 optionsPrivacyMenuItem.setIcon(R.drawable.warning)
6309 else // All the dangerous features are disabled.
6310 optionsPrivacyMenuItem.setIcon(R.drawable.privacy_mode)
6312 // Update the cookies icon.
6313 if (currentWebView!!.acceptCookies)
6314 optionsCookiesMenuItem.setIcon(R.drawable.cookies_enabled)
6316 optionsCookiesMenuItem.setIcon(R.drawable.cookies_disabled)
6318 // Update the refresh icon.
6319 if (optionsRefreshMenuItem.title == getString(R.string.refresh)) // The refresh icon is displayed.
6320 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled)
6321 else // The stop icon is displayed.
6322 optionsRefreshMenuItem.setIcon(R.drawable.close_blue)
6324 // `invalidateOptionsMenu()` calls `onPrepareOptionsMenu()` and redraws the icons in the app bar.
6325 if (runInvalidateOptionsMenu)
6326 invalidateOptionsMenu()