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.webkit.WebViewDatabase
80 import android.widget.AdapterView
81 import android.widget.ArrayAdapter
82 import android.widget.CheckBox
83 import android.widget.EditText
84 import android.widget.FrameLayout
85 import android.widget.ImageView
86 import android.widget.LinearLayout
87 import android.widget.ListView
88 import android.widget.ProgressBar
89 import android.widget.RadioButton
90 import android.widget.RelativeLayout
91 import android.widget.TextView
93 import androidx.activity.OnBackPressedCallback
94 import androidx.activity.result.contract.ActivityResultContracts
95 import androidx.appcompat.app.ActionBar
96 import androidx.appcompat.app.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_FORM_DATA
155 import com.stoutner.privacybrowser.helpers.ENABLE_JAVASCRIPT
156 import com.stoutner.privacybrowser.helpers.ENABLE_ULTRAPRIVACY
157 import com.stoutner.privacybrowser.helpers.ENABLED
158 import com.stoutner.privacybrowser.helpers.FAVORITE_ICON
159 import com.stoutner.privacybrowser.helpers.FOLDER_ID
160 import com.stoutner.privacybrowser.helpers.FONT_SIZE
161 import com.stoutner.privacybrowser.helpers.ID
162 import com.stoutner.privacybrowser.helpers.IP_ADDRESSES
163 import com.stoutner.privacybrowser.helpers.IS_FOLDER
164 import com.stoutner.privacybrowser.helpers.LIGHT_THEME
165 import com.stoutner.privacybrowser.helpers.PINNED_IP_ADDRESSES
166 import com.stoutner.privacybrowser.helpers.PINNED_SSL_CERTIFICATE
167 import com.stoutner.privacybrowser.helpers.REQUEST_ALLOWED
168 import com.stoutner.privacybrowser.helpers.REQUEST_BLOCKED
169 import com.stoutner.privacybrowser.helpers.REQUEST_DEFAULT
170 import com.stoutner.privacybrowser.helpers.REQUEST_THIRD_PARTY
171 import com.stoutner.privacybrowser.helpers.SSL_ISSUED_BY_COMMON_NAME
172 import com.stoutner.privacybrowser.helpers.SSL_ISSUED_BY_ORGANIZATION
173 import com.stoutner.privacybrowser.helpers.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT
174 import com.stoutner.privacybrowser.helpers.SSL_ISSUED_TO_COMMON_NAME
175 import com.stoutner.privacybrowser.helpers.SSL_ISSUED_TO_ORGANIZATION
176 import com.stoutner.privacybrowser.helpers.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT
177 import com.stoutner.privacybrowser.helpers.SWIPE_TO_REFRESH
178 import com.stoutner.privacybrowser.helpers.SYSTEM_DEFAULT
179 import com.stoutner.privacybrowser.helpers.WEBVIEW_THEME
180 import com.stoutner.privacybrowser.helpers.WIDE_VIEWPORT
181 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper
182 import com.stoutner.privacybrowser.helpers.CheckFilterListHelper
183 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper
184 import com.stoutner.privacybrowser.helpers.ProxyHelper
185 import com.stoutner.privacybrowser.helpers.SanitizeUrlHelper
186 import com.stoutner.privacybrowser.helpers.UrlHelper
187 import com.stoutner.privacybrowser.views.BLOCKED_REQUESTS
188 import com.stoutner.privacybrowser.views.EASYLIST
189 import com.stoutner.privacybrowser.views.EASYPRIVACY
190 import com.stoutner.privacybrowser.views.FANBOYS_ANNOYANCE_LIST
191 import com.stoutner.privacybrowser.views.FANBOYS_SOCIAL_BLOCKING_LIST
192 import com.stoutner.privacybrowser.views.THIRD_PARTY_REQUESTS
193 import com.stoutner.privacybrowser.views.ULTRAPRIVACY
194 import com.stoutner.privacybrowser.views.NestedScrollWebView
196 import kotlinx.coroutines.CoroutineScope
197 import kotlinx.coroutines.Dispatchers
198 import kotlinx.coroutines.launch
199 import kotlinx.coroutines.withContext
201 import java.io.ByteArrayInputStream
202 import java.io.ByteArrayOutputStream
204 import java.io.FileInputStream
205 import java.io.FileOutputStream
206 import java.io.IOException
207 import java.io.UnsupportedEncodingException
209 import java.net.MalformedURLException
211 import java.net.URLDecoder
212 import java.net.URLEncoder
214 import java.text.NumberFormat
216 import java.util.ArrayList
217 import java.util.Date
218 import java.util.concurrent.Executors
219 import kotlin.system.exitProcess
221 // Define the public constants
222 const val CURRENT_URL = "current_url"
223 const val DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0
224 const val DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2
225 const val DOMAINS_CUSTOM_USER_AGENT = 12
226 const val SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1
227 const val SETTINGS_CUSTOM_USER_AGENT = 11
228 const val UNRECOGNIZED_USER_AGENT = -1
230 // Define the private class constants.
231 private const val BOOKMARKS_DRAWER_PINNED = "bookmarks_drawer_pinned"
232 private const val PROXY_MODE = "proxy_mode"
233 private const val SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST = "saved_nested_scroll_webview_state_array_list"
234 private const val SAVED_STATE_ARRAY_LIST = "saved_state_array_list"
235 private const val SAVED_TAB_POSITION = "saved_tab_position"
236 private const val TEMPORARY_MHT_FILE = "temporary_mht_file"
238 class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener, FontSizeDialog.UpdateFontSizeListener,
239 NavigationView.OnNavigationItemSelectedListener, OpenDialog.OpenListener, PinnedMismatchDialog.PinnedMismatchListener, PopulateFilterListsCoroutine.PopulateFilterListsListener, SaveDialog.SaveListener,
240 UrlHistoryDialog.NavigateHistoryListener, WebViewTabFragment.NewTabListener {
243 // Define the public static variables.
244 var currentBookmarksFolderId = 0L
245 val executorService = Executors.newFixedThreadPool(4)!!
246 var orbotStatus = "unknown"
247 val pendingDialogsArrayList = ArrayList<PendingDialogDataClass>()
248 var proxyMode = ProxyHelper.NONE
249 var restartFromBookmarksActivity = false
250 var webViewStateAdapter: WebViewStateAdapter? = null
252 // Declare the public static variables.
253 lateinit var appBarLayout: AppBarLayout
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 navigationBackMenuItem: MenuItem
282 private lateinit var navigationForwardMenuItem: MenuItem
283 private lateinit var navigationHistoryMenuItem: MenuItem
284 private lateinit var navigationRequestsMenuItem: MenuItem
285 private lateinit var navigationScrollToBottomMenuItem: MenuItem
286 private lateinit var navigationView: NavigationView
287 private lateinit var optionsAddOrEditDomainMenuItem: MenuItem
288 private lateinit var optionsBlockAllThirdPartyRequestsMenuItem: MenuItem
289 private lateinit var optionsClearCookiesMenuItem: MenuItem
290 private lateinit var optionsClearDataMenuItem: MenuItem
291 private lateinit var optionsClearDomStorageMenuItem: MenuItem
292 private lateinit var optionsClearFormDataMenuItem: 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 optionsSaveFormDataMenuItem: MenuItem
311 private lateinit var optionsSwipeToRefreshMenuItem: MenuItem
312 private lateinit var optionsUltraListMenuItem: MenuItem
313 private lateinit var optionsUltraPrivacyMenuItem: MenuItem
314 private lateinit var optionsUserAgentChromeOnAndroidMenuItem: MenuItem
315 private lateinit var optionsUserAgentChromeOnWindowsMenuItem: MenuItem
316 private lateinit var optionsUserAgentChromiumOnLinuxMenuItem: MenuItem
317 private lateinit var optionsUserAgentCustomMenuItem: MenuItem
318 private lateinit var optionsUserAgentEdgeOnWindowsMenuItem: MenuItem
319 private lateinit var optionsUserAgentFirefoxOnAndroidMenuItem: MenuItem
320 private lateinit var optionsUserAgentFirefoxOnLinuxMenuItem: MenuItem
321 private lateinit var optionsUserAgentFirefoxOnWindowsMenuItem: MenuItem
322 private lateinit var optionsUserAgentMenuItem: MenuItem
323 private lateinit var optionsUserAgentPrivacyBrowserMenuItem: MenuItem
324 private lateinit var optionsUserAgentSafariOnIosMenuItem: MenuItem
325 private lateinit var optionsUserAgentSafariOnMacosMenuItem: MenuItem
326 private lateinit var optionsUserAgentWebViewDefaultMenuItem: MenuItem
327 private lateinit var optionsViewSourceMenuItem: MenuItem
328 private lateinit var optionsWideViewportMenuItem: MenuItem
329 private lateinit var proxyHelper: ProxyHelper
330 private lateinit var redColorSpan: ForegroundColorSpan
331 private lateinit var rootFrameLayout: FrameLayout
332 private lateinit var saveUrlString: String
333 private lateinit var searchURL: String
334 private lateinit var sharedPreferences: SharedPreferences
335 private lateinit var swipeRefreshLayout: SwipeRefreshLayout
336 private lateinit var tabLayout: TabLayout
337 private lateinit var tabsLinearLayout: LinearLayout
338 private lateinit var toolbar: Toolbar
339 private lateinit var webViewDefaultUserAgent: String
340 private lateinit var webViewThemeEntryValuesStringArray: Array<String>
341 private lateinit var webViewViewPager2: ViewPager2
342 private lateinit var ultraList: ArrayList<List<Array<String>>>
343 private lateinit var urlEditText: EditText
344 private lateinit var urlRelativeLayout: RelativeLayout
345 private lateinit var userAgentDataArray: Array<String>
346 private lateinit var userAgentNamesArray: Array<String>
347 private lateinit var userAgentDataArrayAdapter: ArrayAdapter<CharSequence>
348 private lateinit var userAgentNamesArrayAdapter: ArrayAdapter<CharSequence>
350 // Define the class variables.
351 private var appBarHeight = 0
352 private var bookmarksCursor: Cursor? = null
353 private var bookmarksDatabaseHelper: BookmarksDatabaseHelper? = null
354 private var bookmarksDrawerPinned = false
355 private var bottomAppBar = false
356 private var currentWebView: NestedScrollWebView? = null
357 private var defaultBlockAllThirdPartyRequests = false
358 private var defaultCookies = false
359 private var defaultDisplayWebpageImages = true
360 private var defaultDomStorage = false
361 private var defaultEasyList = true
362 private var defaultEasyPrivacy = true
363 private var defaultFanboysAnnoyanceList = true
364 private var defaultFanboysSocialBlockingList = true
365 private var defaultFormData = false // Form data can be removed once the minimum API >= 26.
366 private var defaultProgressViewEndOffset = 0
367 private var defaultProgressViewStartOffset = 0
368 private var defaultJavaScript = false
369 private var defaultSwipeToRefresh = true
370 private var defaultUltraList = true
371 private var defaultUltraPrivacy = true
372 private var defaultWideViewport = true
373 private var displayAdditionalAppBarIcons = false
374 private var displayingFullScreenVideo = false
375 private var domainsDatabaseHelper: DomainsDatabaseHelper? = null
376 private var downloadWithExternalApp = false
377 private var fullScreenBrowsingModeEnabled = false
378 private var hideAppBar = true
379 private var inFullScreenBrowsingMode = false
380 private var incognitoModeEnabled = false
381 private var loadingNewIntent = false
382 private var navigationDrawerFirstView = true
383 private var objectAnimator = ObjectAnimator()
384 private var optionsMenu: Menu? = null
385 private var orbotStatusBroadcastReceiver: BroadcastReceiver? = null
386 private var reapplyAppSettingsOnRestart = false
387 private var reapplyDomainSettingsOnRestart = false
388 private var sanitizeAmpRedirects = false
389 private var sanitizeTrackingQueries = false
390 private var savedProxyMode: String? = null
391 private var savedNestedScrollWebViewStateArrayList: ArrayList<Bundle>? = null
392 private var savedStateArrayList: ArrayList<Bundle>? = null
393 private var savedTabPosition = 0
394 private var scrollAppBar = false
395 private var ultraPrivacy: ArrayList<List<Array<String>>>? = null
396 private var waitingForProxy = false
398 // Define the save webpage image activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
399 private val browseFileUploadActivityResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { activityResult ->
400 // Pass the file to the WebView.
401 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(activityResult.resultCode, activityResult.data))
404 // Define the save URL activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
405 private val saveUrlActivityResultLauncher = registerForActivityResult<String, Uri>(ActivityResultContracts.CreateDocument("*/*")) { fileUri ->
406 // Only save the URL if the file URI is not null, which happens if the user exited the file picker by pressing back.
407 if (fileUri != null) {
408 // Instantiate the save URL coroutine.
409 val saveUrlCoroutine = SaveUrlCoroutine()
412 saveUrlCoroutine.save(this, this, saveUrlString, fileUri, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
415 // Reset the save URL string.
419 // Define the save webpage archive activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
420 private val saveWebpageArchiveActivityResultLauncher = registerForActivityResult<String, Uri>(ActivityResultContracts.CreateDocument("multipart/related")) { fileUri ->
421 // Only save the webpage archive if the file URI is not null, which happens if the user exited the file picker by pressing back.
422 if (fileUri != null) {
423 // Initialize the file name string from the file URI last path segment.
424 var fileNameString = fileUri.lastPathSegment
426 // Query the exact file name if the API >= 26.
427 if (Build.VERSION.SDK_INT >= 26) {
428 // Get a cursor from the content resolver.
429 val contentResolverCursor = contentResolver.query(fileUri, null, null, null)!!
431 // Move to the fist row.
432 contentResolverCursor.moveToFirst()
434 // Get the file name from the cursor.
435 fileNameString = contentResolverCursor.getString(contentResolverCursor.getColumnIndexOrThrow(OpenableColumns.DISPLAY_NAME))
438 contentResolverCursor.close()
441 // Use a coroutine to save the file.
442 CoroutineScope(Dispatchers.Main).launch {
444 // Create the file on the IO thread.
445 withContext(Dispatchers.IO) {
446 // Create a temporary MHT file.
447 val temporaryMhtFile = File.createTempFile(TEMPORARY_MHT_FILE, ".mht", cacheDir)
449 // The WebView must be accessed from the main thread.
450 withContext(Dispatchers.Main) {
451 currentWebView!!.saveWebArchive(temporaryMhtFile.toString(), false) { callbackValue ->
452 if (callbackValue != null) { // The temporary MHT file was saved successfully.
454 // Create a temporary MHT file input stream.
455 val temporaryMhtFileInputStream = FileInputStream(temporaryMhtFile)
457 // Get an output stream for the save webpage file path.
458 val mhtOutputStream = contentResolver.openOutputStream(fileUri)!!
460 // Create a transfer byte array.
461 val transferByteArray = ByteArray(1024)
463 // Create an integer to track the number of bytes read.
466 // Copy the temporary MHT file input stream to the MHT output stream.
467 while (temporaryMhtFileInputStream.read(transferByteArray).also { bytesRead = it } > 0)
468 mhtOutputStream.write(transferByteArray, 0, bytesRead)
470 // Close the streams.
471 mhtOutputStream.close()
472 temporaryMhtFileInputStream.close()
474 // Display a snackbar.
475 Snackbar.make(currentWebView!!, getString(R.string.saved, fileNameString), Snackbar.LENGTH_SHORT).show()
476 } catch (exception: Exception) {
477 // Display snackbar with the exception.
478 Snackbar.make(currentWebView!!, getString(R.string.error_saving_file, fileNameString, exception), Snackbar.LENGTH_INDEFINITE).show()
480 // Delete the temporary MHT file.
481 temporaryMhtFile.delete()
483 } else { // There was an unspecified error while saving the temporary MHT file.
484 // Display a snackbar.
485 Snackbar.make(currentWebView!!, getString(R.string.error_saving_file, fileNameString, getString(R.string.unknown_error)), Snackbar.LENGTH_INDEFINITE).show()
490 } catch (ioException: IOException) {
491 // Display a snackbar with the IO exception.
492 Snackbar.make(currentWebView!!, getString(R.string.error_saving_file, fileNameString, ioException), Snackbar.LENGTH_INDEFINITE).show()
498 // Define the save webpage image activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
499 private val saveWebpageImageActivityResultLauncher = registerForActivityResult<String, Uri>(ActivityResultContracts.CreateDocument("image/png")) { fileUri ->
500 // Only save the webpage image if the file URI is not null, which happens if the user exited the file picker by pressing back.
501 if (fileUri != null) {
502 // Instantiate the save webpage image coroutine.
503 val saveWebpageImageCoroutine = SaveWebpageImageCoroutine()
505 // Save the webpage image.
506 saveWebpageImageCoroutine.save(this, fileUri, currentWebView!!)
510 override fun onCreate(savedInstanceState: Bundle?) {
511 // Run the default commands.
512 super.onCreate(savedInstanceState)
514 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
515 PreferenceManager.setDefaultValues(this, R.xml.preferences, false)
517 // Get a handle for the shared preferences.
518 sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
520 // Get the preferences.
521 val appTheme = sharedPreferences.getString(getString(R.string.app_theme_key), getString(R.string.app_theme_default_value))
522 val allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false)
523 bottomAppBar = sharedPreferences.getBoolean(getString(R.string.bottom_app_bar_key), false)
524 displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false)
525 val displayUnderCutouts = sharedPreferences.getBoolean(getString(R.string.display_under_cutouts_key), false)
527 // 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.
528 if (displayUnderCutouts) {
529 if (Build.VERSION.SDK_INT >= 30)
530 window.attributes.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS
531 else if (Build.VERSION.SDK_INT >= 28)
532 window.attributes.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
535 // Get the theme entry values string array.
536 val appThemeEntryValuesStringArray = resources.getStringArray(R.array.app_theme_entry_values)
538 // Get the current theme status.
539 val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
541 // 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.
542 if (appTheme == appThemeEntryValuesStringArray[1]) { // The light theme is selected.
543 // Apply the light theme.
544 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
545 } else if (appTheme == appThemeEntryValuesStringArray[2]) { // The dark theme is selected.
546 // Apply the dark theme.
547 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
548 } else { // The system default theme is selected.
549 if (Build.VERSION.SDK_INT >= 28) { // The system default theme is supported.
550 // Follow the system default theme.
551 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
552 } else { // The system default theme is not supported.
553 // Follow the battery saver mode.
554 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY)
558 // Do not continue if the app theme is different than the OS theme. The app always initially starts in the OS theme.
559 // 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.
560 // 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.
561 // See https://redmine.stoutner.com/issues/952.
562 if ((appTheme == appThemeEntryValuesStringArray[0]) || // The system default theme is used.
563 ((appTheme == appThemeEntryValuesStringArray[1]) && (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO)) || // The app is running in day theme as desired.
564 ((appTheme == appThemeEntryValuesStringArray[2]) && (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES))) { // The app is running in night theme as desired.
566 // Disable screenshots if not allowed.
567 if (!allowScreenshots) {
568 window.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
571 // Check to see if the activity has been restarted.
572 if (savedInstanceState != null) {
573 // Store the saved instance state variables. The deprecated `getParcelableArrayList` can be upgraded once the minimum API >= 33.
574 bookmarksDrawerPinned = savedInstanceState.getBoolean(BOOKMARKS_DRAWER_PINNED)
575 @Suppress("DEPRECATION")
576 savedStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_STATE_ARRAY_LIST)
577 @Suppress("DEPRECATION")
578 savedNestedScrollWebViewStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST)
579 savedTabPosition = savedInstanceState.getInt(SAVED_TAB_POSITION)
580 savedProxyMode = savedInstanceState.getString(PROXY_MODE)
583 // 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.
584 WebView.enableSlowWholeDocumentDraw()
586 // Set the content view according to the position of the app bar.
588 setContentView(R.layout.main_framelayout_bottom_appbar)
590 setContentView(R.layout.main_framelayout_top_appbar)
592 // Get handles for the views.
593 rootFrameLayout = findViewById(R.id.root_framelayout)
594 drawerLayout = findViewById(R.id.drawerlayout)
595 coordinatorLayout = findViewById(R.id.coordinatorlayout)
596 appBarLayout = findViewById(R.id.appbar_layout)
597 toolbar = findViewById(R.id.toolbar)
598 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout)
599 findOnPageEditText = findViewById(R.id.find_on_page_edittext)
600 findOnPageCountTextView = findViewById(R.id.find_on_page_count_textview)
601 tabsLinearLayout = findViewById(R.id.tabs_linearlayout)
602 tabLayout = findViewById(R.id.tablayout)
603 swipeRefreshLayout = findViewById(R.id.swiperefreshlayout)
604 webViewViewPager2 = findViewById(R.id.webview_viewpager2)
605 navigationView = findViewById(R.id.navigationview)
606 bookmarksListView = findViewById(R.id.bookmarks_drawer_listview)
607 bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview)
608 bookmarksDrawerPinnedImageView = findViewById(R.id.bookmarks_drawer_pinned_imageview)
609 fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout)
611 // Get a handle for the navigation menu.
612 val navigationMenu = navigationView.menu
614 // Get handles for the navigation menu items.
615 navigationBackMenuItem = navigationMenu.findItem(R.id.back)
616 navigationForwardMenuItem = navigationMenu.findItem(R.id.forward)
617 navigationScrollToBottomMenuItem = navigationMenu.findItem(R.id.scroll_to_bottom)
618 navigationHistoryMenuItem = navigationMenu.findItem(R.id.history)
619 navigationRequestsMenuItem = navigationMenu.findItem(R.id.requests)
621 // Listen for touches on the navigation menu.
622 navigationView.setNavigationItemSelectedListener(this)
624 // Set the support action bar.
625 setSupportActionBar(toolbar)
627 // Get a handle for the app bar.
628 appBar = supportActionBar!!
630 // Set the custom app bar layout, which shows the URL text bar.
631 appBar.setCustomView(R.layout.url_app_bar)
633 // Display the custom app bar layout.
634 appBar.displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM
636 // Get handles for the views in the URL app bar.
637 urlRelativeLayout = findViewById(R.id.url_relativelayout)
638 urlEditText = findViewById(R.id.url_edittext)
640 // Initially disable the sliding drawers. They will be enabled once the filter lists are loaded.
641 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
643 // Initially hide the user interface so that only the filter list loading screen is shown (if reloading).
644 drawerLayout.visibility = View.GONE
646 // Initialize the WebView state adapter.
647 webViewStateAdapter = WebViewStateAdapter(this, bottomAppBar)
649 // Set the WebView pager adapter.
650 webViewViewPager2.adapter = webViewStateAdapter
652 // Store up to 100 tabs in memory.
653 webViewViewPager2.offscreenPageLimit = 100
655 // Disable swiping between pages in the view pager.
656 webViewViewPager2.isUserInputEnabled = false
658 // Get a handle for the cookie manager.
659 cookieManager = CookieManager.getInstance()
661 // Instantiate the helpers.
662 bookmarksDatabaseHelper = BookmarksDatabaseHelper(this)
663 domainsDatabaseHelper = DomainsDatabaseHelper(this)
664 proxyHelper = ProxyHelper()
666 // Update the bookmarks drawer pinned image view.
667 updateBookmarksDrawerPinnedImageView()
669 // Initialize the app.
672 // Apply the app settings from the shared preferences.
675 // Control what the system back command does.
676 val onBackPressedCallback: OnBackPressedCallback = object : OnBackPressedCallback(true) {
677 override fun handleOnBackPressed() {
678 // Process the different back options.
679 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
680 // Close the navigation drawer.
681 drawerLayout.closeDrawer(GravityCompat.START)
682 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)) { // The bookmarks drawer is open.
683 // close the bookmarks drawer.
684 drawerLayout.closeDrawer(GravityCompat.END)
685 } else if (displayingFullScreenVideo) { // A full screen video is shown.
686 // Exit the full screen video.
687 exitFullScreenVideo()
688 // It shouldn't be possible for the currentWebView to be null, but crash logs indicate it sometimes happens.
689 } else if (currentWebView != null && currentWebView!!.canGoBack()) { // There is at least one item in the current WebView history.
690 // Get the current web back forward list.
691 val webBackForwardList = currentWebView!!.copyBackForwardList()
693 // Get the previous entry data.
694 val previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex - 1).url
695 val previousFavoriteIcon = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex - 1).favicon
697 // Apply the domain settings.
698 applyDomainSettings(currentWebView!!, previousUrl, resetTab = false, reloadWebsite = false, loadUrl = false)
700 // Get the current tab.
701 val tab = tabLayout.getTabAt(tabLayout.selectedTabPosition)!!
703 // Get the custom view from the tab.
704 val tabView = tab.customView!!
706 // Get the favorite icon image view from the tab.
707 val tabFavoriteIconImageView = tabView.findViewById<ImageView>(R.id.favorite_icon_imageview)
709 // Set the previous favorite icon if it isn't null.
710 if (previousFavoriteIcon != null)
711 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(previousFavoriteIcon, 64, 64, true))
714 currentWebView!!.goBack()
716 // Update the URL edit text after a delay.
717 updateUrlEditTextAfterDelay()
718 } else { // Close the current tab.
719 // A view is required because the method is also called by an XML `onClick`.
725 // Register the on back pressed callback.
726 onBackPressedDispatcher.addCallback(this, onBackPressedCallback)
728 // Instantiate the populate filter lists coroutine.
729 val populateFilterListsCoroutine = PopulateFilterListsCoroutine(this)
731 // Populate the filter lists.
732 populateFilterListsCoroutine.populateFilterLists(this)
736 override fun onNewIntent(intent: Intent) {
737 // Run the default commands.
738 super.onNewIntent(intent)
740 // Close the navigation drawer if it is open.
741 if (drawerLayout.isDrawerVisible(GravityCompat.START))
742 drawerLayout.closeDrawer(GravityCompat.START)
744 // Close the bookmarks drawer if it is open.
745 if (drawerLayout.isDrawerVisible(GravityCompat.END))
746 drawerLayout.closeDrawer(GravityCompat.END)
748 // Get the information from the intent.
749 val intentAction = intent.action
750 val intentUriData = intent.data
751 val intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT)
753 // Determine if this is a web search.
754 val isWebSearch = (intentAction != null) && (intentAction == Intent.ACTION_WEB_SEARCH)
756 // Check to see if the app is being restarted from a saved state.
757 if (ultraPrivacy != null) { // The activity is not being restarted from a saved state.
758 // 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.
759 if ((intentUriData != null) || (intentStringExtra != null) || isWebSearch) {
760 // Exit the full screen video if it is displayed.
761 if (displayingFullScreenVideo) {
762 // Exit full screen video mode.
763 exitFullScreenVideo()
765 // Reload the current WebView. Otherwise, it can display entirely black.
766 currentWebView!!.reload()
770 val url = if (isWebSearch) { // The intent is a web search.
771 // Sanitize the search input and convert it to a search.
772 val encodedSearchString = try {
773 URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8")
774 } catch (exception: UnsupportedEncodingException) {
778 // Add the base search URL.
779 searchURL + encodedSearchString
780 } else { // The intent contains a URL in either the data or an extra.
781 intentUriData?.toString() ?: intentStringExtra
784 // Add a new tab if specified in the preferences.
785 if (sharedPreferences.getBoolean(getString(R.string.open_intents_in_new_tab_key), true)) { // Load the URL in a new tab.
786 // Set the loading new intent flag.
787 loadingNewIntent = true
790 addNewPage(url!!, adjacent = false, moveToTab = true)
791 } else { // Load the URL in the current tab.
793 loadUrl(currentWebView!!, url!!)
796 } else { // The app has been restarted.
797 // Replace the intent that started the app with this one. This will load the tab after the others have been restored.
802 public override fun onRestart() {
803 // Run the default commands.
806 // Apply the app settings if returning from the Settings activity.
807 if (reapplyAppSettingsOnRestart) {
808 // Reset the reapply app settings on restart flag.
809 reapplyAppSettingsOnRestart = false
811 // Apply the app settings.
815 // Apply the domain settings if returning from the settings or domains activity.
816 if (reapplyDomainSettingsOnRestart) {
817 // Reset the reapply domain settings on restart flag.
818 reapplyDomainSettingsOnRestart = false
820 // Update the domains settings set.
821 updateDomainsSettingsSet()
823 // Reapply the domain settings for each tab.
824 for (i in 0 until webViewStateAdapter!!.itemCount) {
825 // Get the WebView tab fragment.
826 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
828 // Get the fragment view.
829 val fragmentView = webViewTabFragment.view
831 // Only reload the WebViews if they exist.
832 if (fragmentView != null) {
833 // Get the nested scroll WebView from the tab fragment.
834 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
836 // Reset the current domain name so the domain settings will be reapplied.
837 nestedScrollWebView.currentDomainName = ""
839 // Reapply the domain settings if the URL is not null, which happens for empty tabs when returning from settings.
840 if (nestedScrollWebView.url != null)
841 applyDomainSettings(nestedScrollWebView, nestedScrollWebView.url, resetTab = false, reloadWebsite = true, loadUrl = false)
846 // Update the bookmarks drawer if returning from the Bookmarks activity.
847 if (restartFromBookmarksActivity) {
848 // Reset the restart from bookmarks activity flag.
849 restartFromBookmarksActivity = false
851 // Close the bookmarks drawer.
852 drawerLayout.closeDrawer(GravityCompat.END)
854 // Reload the bookmarks drawer.
855 loadBookmarksFolder()
858 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
859 updatePrivacyIcons(true)
862 // `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.
863 public override fun onStart() {
864 // Run the default commands.
867 // 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.
868 if (webViewStateAdapter != null) {
869 for (i in 0 until webViewStateAdapter!!.itemCount) {
870 // Get the WebView tab fragment.
871 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
873 // Get the fragment view.
874 val fragmentView = webViewTabFragment.view
876 // Only resume the WebViews if they exist (they won't when the app is first created).
877 if (fragmentView != null) {
878 // Get the nested scroll WebView from the tab fragment.
879 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
881 // Resume the nested scroll WebView.
882 nestedScrollWebView.onResume()
887 // Resume the nested scroll WebView JavaScript timers. This is a global command that resumes JavaScript timers on all WebViews.
888 if (currentWebView != null)
889 currentWebView!!.resumeTimers()
891 // Reapply the proxy settings if the system is using a proxy. This redisplays the appropriate alert dialog.
892 if (proxyMode != ProxyHelper.NONE)
895 // Reapply any system UI flags.
896 if (displayingFullScreenVideo || inFullScreenBrowsingMode) { // The system is displaying a website or a video in full screen mode.
897 /* Hide the system bars.
898 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
899 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
900 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
901 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
904 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
905 @Suppress("DEPRECATION")
906 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
909 // Show any pending dialogs.
910 for (i in pendingDialogsArrayList.indices) {
911 // Get the pending dialog from the array list.
912 val (dialogFragment, tag) = pendingDialogsArrayList[i]
914 // Show the pending dialog.
915 dialogFragment.show(supportFragmentManager, tag)
918 // Clear the pending dialogs array list.
919 pendingDialogsArrayList.clear()
922 public override fun onSaveInstanceState(savedInstanceState: Bundle) {
923 // Run the default commands.
924 super.onSaveInstanceState(savedInstanceState)
926 // 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.
927 if (webViewStateAdapter != null) {
928 // Initialize the saved state array lists.
929 savedStateArrayList = ArrayList<Bundle>()
930 savedNestedScrollWebViewStateArrayList = ArrayList<Bundle>()
932 // Get the URLs from each tab.
933 for (i in 0 until webViewStateAdapter!!.itemCount) {
934 // Get the WebView tab fragment.
935 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
937 // Get the fragment view.
938 val fragmentView = webViewTabFragment.view
940 // Save the fragment state if it is not null.
941 if (fragmentView != null) {
942 // Get the nested scroll WebView from the tab fragment.
943 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
945 // Create the saved state bundle.
946 val savedStateBundle = Bundle()
948 // Get the current states.
949 nestedScrollWebView.saveState(savedStateBundle)
950 val savedNestedScrollWebViewStateBundle = nestedScrollWebView.saveNestedScrollWebViewState()
952 // Store the saved states in the array lists.
953 savedStateArrayList!!.add(savedStateBundle)
954 savedNestedScrollWebViewStateArrayList!!.add(savedNestedScrollWebViewStateBundle)
958 // Get the current tab position.
959 val currentTabPosition = tabLayout.selectedTabPosition
961 // Store the saved states in the bundle.
962 savedInstanceState.putBoolean(BOOKMARKS_DRAWER_PINNED, bookmarksDrawerPinned)
963 savedInstanceState.putString(PROXY_MODE, proxyMode)
964 savedInstanceState.putParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST, savedNestedScrollWebViewStateArrayList)
965 savedInstanceState.putParcelableArrayList(SAVED_STATE_ARRAY_LIST, savedStateArrayList)
966 savedInstanceState.putInt(SAVED_TAB_POSITION, currentTabPosition)
970 // `onStop()` runs after `onPause()`. It is used instead of `onPause()` so the commands are not called every time the screen is partially hidden.
971 public override fun onStop() {
972 // Run the default commands.
975 // 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.
976 if (webViewStateAdapter != null) {
977 // Pause each web view.
978 for (i in 0 until webViewStateAdapter!!.itemCount) {
979 // Get the WebView tab fragment.
980 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
982 // Get the fragment view.
983 val fragmentView = webViewTabFragment.view
985 // Only pause the WebViews if they exist (they won't when the app is first created).
986 if (fragmentView != null) {
987 // Get the nested scroll WebView from the tab fragment.
988 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
990 // Pause the nested scroll WebView.
991 nestedScrollWebView.onPause()
996 // Pause the WebView JavaScript timers. This is a global command that pauses JavaScript on all WebViews.
997 if (currentWebView != null)
998 currentWebView!!.pauseTimers()
1001 public override fun onDestroy() {
1002 // Unregister the orbot status broadcast receiver if it exists.
1003 if (orbotStatusBroadcastReceiver != null) {
1004 unregisterReceiver(orbotStatusBroadcastReceiver)
1007 // Close the bookmarks cursor if it exists.
1008 bookmarksCursor?.close()
1010 // Close the databases if they exist.
1011 bookmarksDatabaseHelper?.close()
1012 domainsDatabaseHelper?.close()
1014 // Run the default commands.
1018 override fun onConfigurationChanged(newConfig: Configuration) {
1019 // Run the default commands.
1020 super.onConfigurationChanged(newConfig)
1022 // Reset the navigation drawer first view flag.
1023 navigationDrawerFirstView = true
1025 // Get the current page.
1026 val currentPage = webViewViewPager2.currentItem
1028 // Toggle the pages if there is more than one so that the view pager will recalculate their size.
1029 if (currentPage > 0) {
1030 // Switch to the previous page after 25 milliseconds.
1031 webViewViewPager2.postDelayed ({ webViewViewPager2.currentItem = (currentPage - 1) }, 25)
1033 // Switch back to the current page after the view pager has quiesced (which we are deciding should be 25 milliseconds).
1034 webViewViewPager2.postDelayed ({ webViewViewPager2.currentItem = currentPage }, 25)
1037 // Scroll to the current tab position after 25 milliseconds.
1038 tabLayout.postDelayed ({ tabLayout.setScrollPosition(currentPage, 0F, false, false) }, 25)
1041 override fun onCreateOptionsMenu(menu: Menu): Boolean {
1042 // Inflate the menu. This adds items to the app bar if it is present.
1043 menuInflater.inflate(R.menu.webview_options_menu, menu)
1045 // Get handles for the menu items.
1046 optionsPrivacyMenuItem = menu.findItem(R.id.javascript)
1047 optionsRefreshMenuItem = menu.findItem(R.id.refresh)
1048 val optionsBookmarksMenuItem = menu.findItem(R.id.bookmarks)
1049 optionsCookiesMenuItem = menu.findItem(R.id.cookies)
1050 optionsDomStorageMenuItem = menu.findItem(R.id.dom_storage)
1051 optionsSaveFormDataMenuItem = menu.findItem(R.id.save_form_data) // Form data can be removed once the minimum API >= 26.
1052 optionsClearDataMenuItem = menu.findItem(R.id.clear_data)
1053 optionsClearCookiesMenuItem = menu.findItem(R.id.clear_cookies)
1054 optionsClearDomStorageMenuItem = menu.findItem(R.id.clear_dom_storage)
1055 optionsClearFormDataMenuItem = menu.findItem(R.id.clear_form_data) // Form data can be removed once the minimum API >= 26.
1056 optionsEasyListMenuItem = menu.findItem(R.id.easylist)
1057 optionsEasyPrivacyMenuItem = menu.findItem(R.id.easyprivacy)
1058 optionsFanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list)
1059 optionsFanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list)
1060 optionsFilterListsMenuItem = menu.findItem(R.id.filterlists)
1061 optionsUltraListMenuItem = menu.findItem(R.id.ultralist)
1062 optionsUltraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy)
1063 optionsBlockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests)
1064 optionsProxyMenuItem = menu.findItem(R.id.proxy)
1065 optionsProxyNoneMenuItem = menu.findItem(R.id.proxy_none)
1066 optionsProxyTorMenuItem = menu.findItem(R.id.proxy_tor)
1067 optionsProxyI2pMenuItem = menu.findItem(R.id.proxy_i2p)
1068 optionsProxyCustomMenuItem = menu.findItem(R.id.proxy_custom)
1069 optionsUserAgentMenuItem = menu.findItem(R.id.user_agent)
1070 optionsUserAgentPrivacyBrowserMenuItem = menu.findItem(R.id.user_agent_privacy_browser)
1071 optionsUserAgentWebViewDefaultMenuItem = menu.findItem(R.id.user_agent_webview_default)
1072 optionsUserAgentFirefoxOnAndroidMenuItem = menu.findItem(R.id.user_agent_firefox_on_android)
1073 optionsUserAgentChromeOnAndroidMenuItem = menu.findItem(R.id.user_agent_chrome_on_android)
1074 optionsUserAgentSafariOnIosMenuItem = menu.findItem(R.id.user_agent_safari_on_ios)
1075 optionsUserAgentFirefoxOnLinuxMenuItem = menu.findItem(R.id.user_agent_firefox_on_linux)
1076 optionsUserAgentChromiumOnLinuxMenuItem = menu.findItem(R.id.user_agent_chromium_on_linux)
1077 optionsUserAgentFirefoxOnWindowsMenuItem = menu.findItem(R.id.user_agent_firefox_on_windows)
1078 optionsUserAgentChromeOnWindowsMenuItem = menu.findItem(R.id.user_agent_chrome_on_windows)
1079 optionsUserAgentEdgeOnWindowsMenuItem = menu.findItem(R.id.user_agent_edge_on_windows)
1080 optionsUserAgentSafariOnMacosMenuItem = menu.findItem(R.id.user_agent_safari_on_macos)
1081 optionsUserAgentCustomMenuItem = menu.findItem(R.id.user_agent_custom)
1082 optionsSwipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh)
1083 optionsWideViewportMenuItem = menu.findItem(R.id.wide_viewport)
1084 optionsDisplayImagesMenuItem = menu.findItem(R.id.display_images)
1085 optionsDarkWebViewMenuItem = menu.findItem(R.id.dark_webview)
1086 optionsFontSizeMenuItem = menu.findItem(R.id.font_size)
1087 optionsViewSourceMenuItem = menu.findItem(R.id.view_source)
1088 optionsAddOrEditDomainMenuItem = menu.findItem(R.id.add_or_edit_domain)
1090 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1091 updatePrivacyIcons(false)
1093 // Only display the form data menu items if the API < 26.
1094 optionsSaveFormDataMenuItem.isVisible = Build.VERSION.SDK_INT < 26
1095 optionsClearFormDataMenuItem.isVisible = Build.VERSION.SDK_INT < 26
1097 // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
1098 optionsClearFormDataMenuItem.isEnabled = Build.VERSION.SDK_INT < 26
1100 // 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.
1101 if (displayAdditionalAppBarIcons) { // Display the additional icons.
1102 optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
1103 optionsBookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM)
1104 optionsCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM)
1105 } else { //Do not display the additional icons.
1106 optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER)
1107 optionsBookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER)
1108 optionsCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER)
1111 // Replace `Refresh` with `Stop` if a URL is already loading.
1112 if ((currentWebView != null) && (currentWebView!!.progress != 100)) {
1114 optionsRefreshMenuItem.setTitle(R.string.stop)
1116 // Set the icon if it is displayed in the app bar. Once the minimum API is >= 26, the blue and black icons can be combined with a tint list.
1117 if (displayAdditionalAppBarIcons)
1118 optionsRefreshMenuItem.setIcon(R.drawable.close_blue)
1121 // Store a handle for the options menu.
1128 override fun onPrepareOptionsMenu(menu: Menu): Boolean {
1129 // Initialize the current user agent string and the font size.
1130 var currentUserAgent = getString(R.string.user_agent_privacy_browser)
1133 // 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.
1134 if (currentWebView != null) {
1135 // Set the add or edit domain text.
1136 if (currentWebView!!.domainSettingsApplied)
1137 optionsAddOrEditDomainMenuItem.setTitle(R.string.edit_domain_settings)
1139 optionsAddOrEditDomainMenuItem.setTitle(R.string.add_domain_settings)
1141 // Get the current user agent from the WebView.
1142 currentUserAgent = currentWebView!!.settings.userAgentString
1144 // Get the current font size from the the WebView.
1145 fontSize = currentWebView!!.settings.textZoom
1147 // Set the status of the menu item checkboxes.
1148 optionsDomStorageMenuItem.isChecked = currentWebView!!.settings.domStorageEnabled
1149 @Suppress("DEPRECATION")
1150 optionsSaveFormDataMenuItem.isChecked = currentWebView!!.settings.saveFormData // Form data can be removed once the minimum API >= 26.
1151 optionsEasyListMenuItem.isChecked = currentWebView!!.easyListEnabled
1152 optionsEasyPrivacyMenuItem.isChecked = currentWebView!!.easyPrivacyEnabled
1153 optionsFanboysAnnoyanceListMenuItem.isChecked = currentWebView!!.fanboysAnnoyanceListEnabled
1154 optionsFanboysSocialBlockingListMenuItem.isChecked = currentWebView!!.fanboysSocialBlockingListEnabled
1155 optionsUltraListMenuItem.isChecked = currentWebView!!.ultraListEnabled
1156 optionsUltraPrivacyMenuItem.isChecked = currentWebView!!.ultraPrivacyEnabled
1157 optionsBlockAllThirdPartyRequestsMenuItem.isChecked = currentWebView!!.blockAllThirdPartyRequests
1158 optionsSwipeToRefreshMenuItem.isChecked = currentWebView!!.swipeToRefresh
1159 optionsWideViewportMenuItem.isChecked = currentWebView!!.settings.useWideViewPort
1160 optionsDisplayImagesMenuItem.isChecked = currentWebView!!.settings.loadsImagesAutomatically
1162 // Set the display names for the filter lists with the number of blocked requests.
1163 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + currentWebView!!.getRequestsCount(BLOCKED_REQUESTS)
1164 optionsEasyListMenuItem.title = currentWebView!!.getRequestsCount(EASYLIST).toString() + " - " + getString(R.string.easylist)
1165 optionsEasyPrivacyMenuItem.title = currentWebView!!.getRequestsCount(EASYPRIVACY).toString() + " - " + getString(R.string.easyprivacy)
1166 optionsFanboysAnnoyanceListMenuItem.title = currentWebView!!.getRequestsCount(FANBOYS_ANNOYANCE_LIST).toString() + " - " + getString(R.string.fanboys_annoyance_list)
1167 optionsFanboysSocialBlockingListMenuItem.title = currentWebView!!.getRequestsCount(FANBOYS_SOCIAL_BLOCKING_LIST).toString() + " - " + getString(R.string.fanboys_social_blocking_list)
1168 optionsUltraListMenuItem.title = currentWebView!!.getRequestsCount(com.stoutner.privacybrowser.views.ULTRALIST).toString() + " - " + getString(R.string.ultralist)
1169 optionsUltraPrivacyMenuItem.title = currentWebView!!.getRequestsCount(ULTRAPRIVACY).toString() + " - " + getString(R.string.ultraprivacy)
1170 optionsBlockAllThirdPartyRequestsMenuItem.title = currentWebView!!.getRequestsCount(THIRD_PARTY_REQUESTS).toString() + " - " + getString(R.string.block_all_third_party_requests)
1172 // Enable DOM Storage if JavaScript is enabled.
1173 optionsDomStorageMenuItem.isEnabled = currentWebView!!.settings.javaScriptEnabled
1175 // Get the current theme status.
1176 val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
1178 // Enable dark WebView if night mode is enabled.
1179 optionsDarkWebViewMenuItem.isEnabled = (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES)
1181 // Set the checkbox status for dark WebView if algorithmic darkening is supported.
1182 if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING))
1183 optionsDarkWebViewMenuItem.isChecked = WebSettingsCompat.isAlgorithmicDarkeningAllowed(currentWebView!!.settings)
1185 // Set the view source title according to the current URL.
1186 if (currentWebView!!.currentUrl.startsWith("view-source:"))
1187 optionsViewSourceMenuItem.title = getString(R.string.view_rendered_website)
1189 optionsViewSourceMenuItem.title = getString(R.string.view_source)
1192 // Set the cookies menu item checked status.
1193 optionsCookiesMenuItem.isChecked = cookieManager.acceptCookie()
1195 // Enable Clear Cookies if there are any.
1196 optionsClearCookiesMenuItem.isEnabled = cookieManager.hasCookies()
1198 // 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`.
1199 val privateDataDirectoryString = applicationInfo.dataDir
1201 // Get the storage directories.
1202 val localStorageDirectory = File("$privateDataDirectoryString/app_webview/Local Storage/")
1203 val indexedDBDirectory = File("$privateDataDirectoryString/app_webview/IndexedDB")
1205 // Initialize the number of files counters.
1206 var localStorageDirectoryNumberOfFiles = 0
1207 var indexedDBDirectoryNumberOfFiles = 0
1209 // 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.
1210 if (localStorageDirectory.exists())
1211 localStorageDirectoryNumberOfFiles = (localStorageDirectory.list())?.size ?: 0
1213 // Get a count of the number of files in the IndexedDB directory. The list can be null, in which case a `0` is returned.
1214 if (indexedDBDirectory.exists())
1215 indexedDBDirectoryNumberOfFiles = (indexedDBDirectory.list())?.size ?: 0
1217 // Enable Clear DOM Storage if there is any.
1218 optionsClearDomStorageMenuItem.isEnabled = localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0
1220 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
1221 if (Build.VERSION.SDK_INT < 26) {
1222 // Get the WebView database.
1223 val webViewDatabase = WebViewDatabase.getInstance(this)
1225 // Enable the clear form data menu item if there is anything to clear.
1226 @Suppress("DEPRECATION")
1227 optionsClearFormDataMenuItem.isEnabled = webViewDatabase.hasFormData()
1230 // Enable Clear Data if any of the submenu items are enabled.
1231 optionsClearDataMenuItem.isEnabled = (optionsClearCookiesMenuItem.isEnabled || optionsClearDomStorageMenuItem.isEnabled || optionsClearFormDataMenuItem.isEnabled)
1233 // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
1234 optionsFanboysSocialBlockingListMenuItem.isEnabled = !optionsFanboysAnnoyanceListMenuItem.isChecked
1236 // Set the proxy title and check the applied proxy.
1238 ProxyHelper.NONE -> {
1239 // Set the proxy title.
1240 optionsProxyMenuItem.title = getString(R.string.proxy) + " - " + getString(R.string.proxy_none)
1242 // Check the proxy None radio button.
1243 optionsProxyNoneMenuItem.isChecked = true
1246 ProxyHelper.TOR -> {
1247 // Set the proxy title.
1248 optionsProxyMenuItem.title = getString(R.string.proxy) + " - " + getString(R.string.proxy_tor)
1250 // Check the proxy Tor radio button.
1251 optionsProxyTorMenuItem.isChecked = true
1254 ProxyHelper.I2P -> {
1255 // Set the proxy title.
1256 optionsProxyMenuItem.title = getString(R.string.proxy) + " - " + getString(R.string.proxy_i2p)
1258 // Check the proxy I2P radio button.
1259 optionsProxyI2pMenuItem.isChecked = true
1262 ProxyHelper.CUSTOM -> {
1263 // Set the proxy title.
1264 optionsProxyMenuItem.title = getString(R.string.proxy) + " - " + getString(R.string.proxy_custom)
1266 // Check the proxy Custom radio button.
1267 optionsProxyCustomMenuItem.isChecked = true
1271 // Select the current user agent menu item.
1272 when (currentUserAgent) {
1273 resources.getStringArray(R.array.user_agent_data)[0] -> { // Privacy Browser.
1274 // Update the user agent menu item title.
1275 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_privacy_browser)
1277 // Select the Privacy Browser radio box.
1278 optionsUserAgentPrivacyBrowserMenuItem.isChecked = true
1281 webViewDefaultUserAgent -> { // WebView Default.
1282 // Update the user agent menu item title.
1283 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_webview_default)
1285 // Select the WebView Default radio box.
1286 optionsUserAgentWebViewDefaultMenuItem.isChecked = true
1289 resources.getStringArray(R.array.user_agent_data)[2] -> { // Firefox on Android.
1290 // Update the user agent menu item title.
1291 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_android)
1293 // Select the Firefox on Android radio box.
1294 optionsUserAgentFirefoxOnAndroidMenuItem.isChecked = true
1297 resources.getStringArray(R.array.user_agent_data)[3] -> { // Chrome on Android.
1298 // Update the user agent menu item title.
1299 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_android)
1301 // Select the Chrome on Android radio box.
1302 optionsUserAgentChromeOnAndroidMenuItem.isChecked = true
1305 resources.getStringArray(R.array.user_agent_data)[4] -> { // Safari on iOS.
1306 // Update the user agent menu item title.
1307 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_ios)
1309 // Select the Safari on iOS radio box.
1310 optionsUserAgentSafariOnIosMenuItem.isChecked = true
1313 resources.getStringArray(R.array.user_agent_data)[5] -> { // Firefox on Linux.
1314 // Update the user agent menu item title.
1315 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_linux)
1317 // Select the Firefox on Linux radio box.
1318 optionsUserAgentFirefoxOnLinuxMenuItem.isChecked = true
1321 resources.getStringArray(R.array.user_agent_data)[6] -> { // Chromium on Linux.
1322 // Update the user agent menu item title.
1323 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chromium_on_linux)
1325 // Select the Chromium on Linux radio box.
1326 optionsUserAgentChromiumOnLinuxMenuItem.isChecked = true
1329 resources.getStringArray(R.array.user_agent_data)[7] -> { // Firefox on Windows.
1330 // Update the user agent menu item title.
1331 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_windows)
1333 // Select the Firefox on Windows radio box.
1334 optionsUserAgentFirefoxOnWindowsMenuItem.isChecked = true
1337 resources.getStringArray(R.array.user_agent_data)[8] -> { // Chrome on Windows.
1338 // Update the user agent menu item title.
1339 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_windows)
1341 // Select the Chrome on Windows radio box.
1342 optionsUserAgentChromeOnWindowsMenuItem.isChecked = true
1345 resources.getStringArray(R.array.user_agent_data)[9] -> { // Edge on Windows.
1346 // Update the user agent menu item title.
1347 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_edge_on_windows)
1349 // Select the Edge on Windows radio box.
1350 optionsUserAgentEdgeOnWindowsMenuItem.isChecked = true
1353 resources.getStringArray(R.array.user_agent_data)[10] -> { // Safari on macOS.
1354 // Update the user agent menu item title.
1355 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_macos)
1357 // Select the Safari on macOS radio box.
1358 optionsUserAgentSafariOnMacosMenuItem.isChecked = true
1361 else -> { // Custom user agent.
1362 // Update the user agent menu item title.
1363 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_custom)
1365 // Select the Custom radio box.
1366 optionsUserAgentCustomMenuItem.isChecked = true
1370 // Set the font size title.
1371 optionsFontSizeMenuItem.title = getString(R.string.font_size) + " - " + fontSize + "%"
1373 // Run all the other default commands.
1374 super.onPrepareOptionsMenu(menu)
1376 // Display the menu.
1380 override fun onOptionsItemSelected(menuItem: MenuItem): Boolean {
1381 // Run the commands that correlate to the selected menu item.
1382 return when (menuItem.itemId) {
1383 R.id.javascript -> { // JavaScript.
1384 // Toggle the JavaScript status.
1385 currentWebView!!.settings.javaScriptEnabled = !currentWebView!!.settings.javaScriptEnabled
1387 // Update the privacy icon.
1388 updatePrivacyIcons(true)
1390 // Display a snackbar.
1391 if (currentWebView!!.settings.javaScriptEnabled) // JavaScrip is enabled.
1392 Snackbar.make(webViewViewPager2, R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show()
1393 else if (cookieManager.acceptCookie()) // JavaScript is disabled, but cookies are enabled.
1394 Snackbar.make(webViewViewPager2, R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show()
1395 else // Privacy mode.
1396 Snackbar.make(webViewViewPager2, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show()
1398 // Reload the current WebView.
1399 currentWebView!!.reload()
1401 // Consume the event.
1405 R.id.refresh -> { // Refresh.
1406 // Run the command that correlates to the current status of the menu item.
1407 if (menuItem.title == getString(R.string.refresh)) // The refresh button was pushed.
1408 currentWebView!!.reload()
1409 else // The stop button was pushed.
1410 currentWebView!!.stopLoading()
1412 // Consume the event.
1416 R.id.bookmarks -> { // Bookmarks.
1417 // Open the bookmarks drawer.
1418 drawerLayout.openDrawer(GravityCompat.END)
1420 // Consume the event.
1424 R.id.cookies -> { // Cookies.
1425 // Toggle the cookie status.
1426 cookieManager.setAcceptCookie(!cookieManager.acceptCookie())
1428 // Store the cookie status.
1429 currentWebView!!.acceptCookies = cookieManager.acceptCookie()
1431 // Update the menu checkbox.
1432 menuItem.isChecked = cookieManager.acceptCookie()
1434 // Update the privacy icon.
1435 updatePrivacyIcons(true)
1437 // Display a snackbar.
1438 if (cookieManager.acceptCookie()) // Cookies are enabled.
1439 Snackbar.make(webViewViewPager2, R.string.cookies_enabled, Snackbar.LENGTH_SHORT).show()
1440 else if (currentWebView!!.settings.javaScriptEnabled) // JavaScript is still enabled.
1441 Snackbar.make(webViewViewPager2, R.string.cookies_disabled, Snackbar.LENGTH_SHORT).show()
1442 else // Privacy mode.
1443 Snackbar.make(webViewViewPager2, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show()
1445 // Reload the current WebView.
1446 currentWebView!!.reload()
1448 // Consume the event.
1452 R.id.dom_storage -> { // DOM storage.
1453 // Toggle the DOM storage status.
1454 currentWebView!!.settings.domStorageEnabled = !currentWebView!!.settings.domStorageEnabled
1456 // Update the menu checkbox.
1457 menuItem.isChecked = currentWebView!!.settings.domStorageEnabled
1459 // Update the privacy icon.
1460 updatePrivacyIcons(true)
1462 // Display a snackbar.
1463 if (currentWebView!!.settings.domStorageEnabled)
1464 Snackbar.make(webViewViewPager2, R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show()
1466 Snackbar.make(webViewViewPager2, R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show()
1468 // Reload the current WebView.
1469 currentWebView!!.reload()
1471 // Consume the event.
1475 R.id.save_form_data -> { // Form data. This can be removed once the minimum API >= 26.
1476 // Switch the status of saveFormDataEnabled.
1477 @Suppress("DEPRECATION")
1478 currentWebView!!.settings.saveFormData = !currentWebView!!.settings.saveFormData
1480 // Update the menu checkbox.
1481 @Suppress("DEPRECATION")
1482 menuItem.isChecked = currentWebView!!.settings.saveFormData
1484 // Display a snackbar.
1485 @Suppress("DEPRECATION")
1486 if (currentWebView!!.settings.saveFormData)
1487 Snackbar.make(webViewViewPager2, R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show()
1489 Snackbar.make(webViewViewPager2, R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show()
1491 // Update the privacy icon.
1492 updatePrivacyIcons(true)
1494 // Reload the current WebView.
1495 currentWebView!!.reload()
1497 // Consume the event.
1501 R.id.clear_cookies -> { // Clear cookies.
1502 // Create a snackbar.
1503 Snackbar.make(webViewViewPager2, R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1504 .setAction(R.string.undo) {} // Everything will be handled by `onDismissed()` below.
1505 .addCallback(object : Snackbar.Callback() {
1506 override fun onDismissed(snackbar: Snackbar, event: Int) {
1507 if (event != DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1508 // Delete the cookies.
1509 cookieManager.removeAllCookies(null)
1515 // Consume the event.
1519 R.id.clear_dom_storage -> { // Clear DOM storage.
1520 // Create a snackbar.
1521 Snackbar.make(webViewViewPager2, R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1522 .setAction(R.string.undo) {} // Everything will be handled by `onDismissed()` below.
1523 .addCallback(object : Snackbar.Callback() {
1524 override fun onDismissed(snackbar: Snackbar, event: Int) {
1525 if (event != DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1526 // Get a handle for the web storage.
1527 val webStorage = WebStorage.getInstance()
1529 // Delete the DOM Storage.
1530 webStorage.deleteAllData()
1532 // Initialize a handler to manually delete the DOM storage files and directories.
1533 val deleteDomStorageHandler = Handler(Looper.getMainLooper())
1535 // Setup a runnable to manually delete the DOM storage files and directories.
1536 val deleteDomStorageRunnable = Runnable {
1538 // Get a handle for the runtime.
1539 val runtime = Runtime.getRuntime()
1541 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1542 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1543 val privateDataDirectoryString = applicationInfo.dataDir
1545 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1546 val deleteLocalStorageProcess = runtime.exec(arrayOf("rm", "-rf", "$privateDataDirectoryString/app_webview/Local Storage/"))
1548 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1549 val deleteIndexProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview/IndexedDB")
1550 val deleteQuotaManagerProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/QuotaManager")
1551 val deleteQuotaManagerJournalProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/QuotaManager-journal")
1552 val deleteDatabasesProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview/databases")
1554 // Wait for the processes to finish.
1555 deleteLocalStorageProcess.waitFor()
1556 deleteIndexProcess.waitFor()
1557 deleteQuotaManagerProcess.waitFor()
1558 deleteQuotaManagerJournalProcess.waitFor()
1559 deleteDatabasesProcess.waitFor()
1560 } catch (exception: Exception) {
1561 // Do nothing if an error is thrown.
1565 // Manually delete the DOM storage files after 200 milliseconds.
1566 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200)
1572 // Consume the event.
1576 R.id.clear_form_data -> { // Clear form data. This can be remove once the minimum API >= 26.
1577 // Create a snackbar.
1578 Snackbar.make(webViewViewPager2, R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1579 .setAction(R.string.undo) {} // Everything will be handled by `onDismissed()` below.
1580 .addCallback(object : Snackbar.Callback() {
1581 override fun onDismissed(snackbar: Snackbar, event: Int) {
1582 if (event != DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1583 // Get a handle for the webView database.
1584 val webViewDatabase = WebViewDatabase.getInstance(applicationContext)
1586 // Delete the form data.
1587 @Suppress("DEPRECATION")
1588 webViewDatabase.clearFormData()
1594 // Consume the event.
1598 R.id.easylist -> { // EasyList.
1599 // Toggle the EasyList status.
1600 currentWebView!!.easyListEnabled = !currentWebView!!.easyListEnabled
1602 // Update the menu checkbox.
1603 menuItem.isChecked = currentWebView!!.easyListEnabled
1605 // Reload the current WebView.
1606 currentWebView!!.reload()
1608 // Consume the event.
1612 R.id.easyprivacy -> { // EasyPrivacy.
1613 // Toggle the EasyPrivacy status.
1614 currentWebView!!.easyPrivacyEnabled = !currentWebView!!.easyPrivacyEnabled
1616 // Update the menu checkbox.
1617 menuItem.isChecked = currentWebView!!.easyPrivacyEnabled
1619 // Reload the current WebView.
1620 currentWebView!!.reload()
1622 // Consume the event.
1626 R.id.fanboys_annoyance_list -> { // Fanboy's Annoyance List.
1627 // Toggle Fanboy's Annoyance List status.
1628 currentWebView!!.fanboysAnnoyanceListEnabled = !currentWebView!!.fanboysAnnoyanceListEnabled
1630 // Update the menu checkbox.
1631 menuItem.isChecked = currentWebView!!.fanboysAnnoyanceListEnabled
1633 // Update the status of Fanboy's Social Blocking List.
1634 optionsFanboysSocialBlockingListMenuItem.isEnabled = !currentWebView!!.fanboysAnnoyanceListEnabled
1636 // Reload the current WebView.
1637 currentWebView!!.reload()
1639 // Consume the event.
1643 R.id.fanboys_social_blocking_list -> { // Fanboy's Social Blocking List.
1644 // Toggle Fanboy's Social Blocking List status.
1645 currentWebView!!.fanboysSocialBlockingListEnabled = !currentWebView!!.fanboysSocialBlockingListEnabled
1647 // Update the menu checkbox.
1648 menuItem.isChecked = currentWebView!!.fanboysSocialBlockingListEnabled
1650 // Reload the current WebView.
1651 currentWebView!!.reload()
1653 // Consume the event.
1657 R.id.ultralist -> { // UltraList.
1658 // Toggle the UltraList status.
1659 currentWebView!!.ultraListEnabled = !currentWebView!!.ultraListEnabled
1661 // Update the menu checkbox.
1662 menuItem.isChecked = currentWebView!!.ultraListEnabled
1664 // Reload the current WebView.
1665 currentWebView!!.reload()
1667 // Consume the event.
1671 R.id.ultraprivacy -> { // UltraPrivacy.
1672 // Toggle the UltraPrivacy status.
1673 currentWebView!!.ultraPrivacyEnabled = !currentWebView!!.ultraPrivacyEnabled
1675 // Update the menu checkbox.
1676 menuItem.isChecked = currentWebView!!.ultraPrivacyEnabled
1678 // Reload the current WebView.
1679 currentWebView!!.reload()
1681 // Consume the event.
1685 R.id.block_all_third_party_requests -> { // Block all third-party requests.
1686 //Toggle the third-party requests blocker status.
1687 currentWebView!!.blockAllThirdPartyRequests = !currentWebView!!.blockAllThirdPartyRequests
1689 // Update the menu checkbox.
1690 menuItem.isChecked = currentWebView!!.blockAllThirdPartyRequests
1692 // Reload the current WebView.
1693 currentWebView!!.reload()
1695 // Consume the event.
1699 R.id.proxy_none -> { // Proxy - None.
1700 // Update the proxy mode.
1701 proxyMode = ProxyHelper.NONE
1703 // Apply the proxy mode.
1706 // Consume the event.
1710 R.id.proxy_tor -> { // Proxy - Tor.
1711 // Update the proxy mode.
1712 proxyMode = ProxyHelper.TOR
1714 // Apply the proxy mode.
1717 // Consume the event.
1721 R.id.proxy_i2p -> { // Proxy - I2P.
1722 // Update the proxy mode.
1723 proxyMode = ProxyHelper.I2P
1725 // Apply the proxy mode.
1728 // Consume the event.
1732 R.id.proxy_custom -> { // Proxy - Custom.
1733 // Update the proxy mode.
1734 proxyMode = ProxyHelper.CUSTOM
1736 // Apply the proxy mode.
1739 // Consume the event.
1743 R.id.user_agent_privacy_browser -> { // User Agent - Privacy Browser.
1744 // Update the user agent.
1745 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[0]
1747 // Reload the current WebView.
1748 currentWebView!!.reload()
1750 // Consume the event.
1754 R.id.user_agent_webview_default -> { // User Agent - WebView Default.
1755 // Update the user agent.
1756 currentWebView!!.settings.userAgentString = ""
1758 // Reload the current WebView.
1759 currentWebView!!.reload()
1761 // Consume the event.
1765 R.id.user_agent_firefox_on_android -> { // User Agent - Firefox on Android.
1766 // Update the user agent.
1767 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[2]
1769 // Reload the current WebView.
1770 currentWebView!!.reload()
1772 // Consume the event.
1776 R.id.user_agent_chrome_on_android -> { // User Agent - Chrome on Android.
1777 // Update the user agent.
1778 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[3]
1780 // Reload the current WebView.
1781 currentWebView!!.reload()
1783 // Consume the event.
1787 R.id.user_agent_safari_on_ios -> { // User Agent - Safari on iOS.
1788 // Update the user agent.
1789 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[4]
1791 // Reload the current WebView.
1792 currentWebView!!.reload()
1794 // Consume the event.
1798 R.id.user_agent_firefox_on_linux -> { // User Agent - Firefox on Linux.
1799 // Update the user agent.
1800 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[5]
1802 // Reload the current WebView.
1803 currentWebView!!.reload()
1805 // Consume the event.
1809 R.id.user_agent_chromium_on_linux -> { // User Agent - Chromium on Linux.
1810 // Update the user agent.
1811 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[6]
1813 // Reload the current WebView.
1814 currentWebView!!.reload()
1816 // Consume the event.
1820 R.id.user_agent_firefox_on_windows -> { // User Agent - Firefox on Windows.
1821 // Update the user agent.
1822 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[7]
1824 // Reload the current WebView.
1825 currentWebView!!.reload()
1827 // Consume the event.
1831 R.id.user_agent_chrome_on_windows -> { // User Agent - Chrome on Windows.
1832 // Update the user agent.
1833 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[8]
1835 // Reload the current WebView.
1836 currentWebView!!.reload()
1838 // Consume the event.
1842 R.id.user_agent_edge_on_windows -> { // User Agent - Edge on Windows.
1843 // Update the user agent.
1844 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[9]
1846 // Reload the current WebView.
1847 currentWebView!!.reload()
1849 // Consume the event.
1853 R.id.user_agent_safari_on_macos -> { // User Agent - Safari on macOS.
1854 // Update the user agent.
1855 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[10]
1857 // Reload the current WebView.
1858 currentWebView!!.reload()
1860 // Consume the event.
1864 R.id.user_agent_custom -> { // User Agent - Custom.
1865 // Update the user agent.
1866 currentWebView!!.settings.userAgentString = sharedPreferences.getString(getString(R.string.custom_user_agent_key), getString(R.string.custom_user_agent_default_value))
1868 // Reload the current WebView.
1869 currentWebView!!.reload()
1871 // Consume the event.
1875 R.id.font_size -> { // Font size.
1876 // Instantiate the font size dialog.
1877 val fontSizeDialogFragment: DialogFragment = FontSizeDialog.displayDialog(currentWebView!!.settings.textZoom)
1879 // Show the font size dialog.
1880 fontSizeDialogFragment.show(supportFragmentManager, getString(R.string.font_size))
1882 // Consume the event.
1886 R.id.swipe_to_refresh -> { // Swipe to refresh.
1887 // Toggle the stored status of swipe to refresh.
1888 currentWebView!!.swipeToRefresh = !currentWebView!!.swipeToRefresh
1890 // Update the swipe refresh layout.
1891 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.
1892 swipeRefreshLayout.isEnabled = currentWebView!!.scrollY == 0
1893 else // Swipe to refresh is disabled.
1894 swipeRefreshLayout.isEnabled = false
1896 // Consume the event.
1900 R.id.wide_viewport -> { // Wide viewport.
1901 // Toggle the viewport.
1902 currentWebView!!.settings.useWideViewPort = !currentWebView!!.settings.useWideViewPort
1904 // Consume the event.
1908 R.id.display_images -> { // Display images.
1909 // Toggle the displaying of images.
1910 if (currentWebView!!.settings.loadsImagesAutomatically) { // Images are currently loaded automatically.
1911 // Disable loading of images.
1912 currentWebView!!.settings.loadsImagesAutomatically = false
1914 // Reload the website to remove existing images.
1915 currentWebView!!.reload()
1916 } else { // Images are not currently loaded automatically.
1917 // Enable loading of images. Missing images will be loaded without the need for a reload.
1918 currentWebView!!.settings.loadsImagesAutomatically = true
1921 // Consume the event.
1925 R.id.dark_webview -> { // Dark WebView.
1926 // Toggle dark WebView if supported.
1927 if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING))
1928 WebSettingsCompat.setAlgorithmicDarkeningAllowed(currentWebView!!.settings, !WebSettingsCompat.isAlgorithmicDarkeningAllowed(currentWebView!!.settings)
1931 // Consume the event.
1935 R.id.find_on_page -> { // Find on page.
1936 // Set the minimum height of the find on page linear layout to match the toolbar.
1937 findOnPageLinearLayout.minimumHeight = toolbar.height
1939 // Hide the toolbar.
1940 toolbar.visibility = View.GONE
1942 // Show the find on page linear layout.
1943 findOnPageLinearLayout.visibility = View.VISIBLE
1945 // Display the keyboard. The app must wait 200 ms before running the command to work around a bug in Android.
1946 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1947 findOnPageEditText.postDelayed({
1948 // Set the focus on the find on page edit text.
1949 findOnPageEditText.requestFocus()
1951 // Get a handle for the input method manager.
1952 val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
1954 // Display the keyboard. `0` sets no input flags.
1955 inputMethodManager.showSoftInput(findOnPageEditText, 0)
1958 // Consume the event.
1962 R.id.print -> { // Print.
1963 // Get a print manager instance.
1964 val printManager = (getSystemService(PRINT_SERVICE) as PrintManager)
1966 // Create a print document adapter from the current WebView.
1967 val printDocumentAdapter = currentWebView!!.createPrintDocumentAdapter(getString(R.string.print))
1969 // Print the document.
1970 printManager.print(getString(R.string.privacy_browser_webpage), printDocumentAdapter, null)
1972 // Consume the event.
1976 R.id.save_url -> { // Save URL.
1977 // Check the download preference.
1978 if (downloadWithExternalApp) // Download with an external app.
1979 downloadUrlWithExternalApp(currentWebView!!.currentUrl)
1980 else // Handle the download inside of Privacy Browser. The dialog will be displayed once the file size and the content disposition have been acquired.
1981 PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, currentWebView!!.currentUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
1983 // Consume the event.
1987 R.id.save_archive -> {
1988 // Open the file picker with a default file name built from the website title.
1989 saveWebpageArchiveActivityResultLauncher.launch(currentWebView!!.title + ".mht")
1991 // Consume the event.
1995 R.id.save_image -> { // Save image.
1996 // Open the file picker with a default file name built from the current domain name.
1997 saveWebpageImageActivityResultLauncher.launch(currentWebView!!.currentDomainName + ".png")
1999 // Consume the event.
2003 R.id.add_to_homescreen -> { // Add to homescreen.
2004 // Instantiate the create home screen shortcut dialog.
2005 val createHomeScreenShortcutDialogFragment: DialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView!!.title!!, currentWebView!!.url!!, currentWebView!!.getFavoriteIcon())
2007 // Show the create home screen shortcut dialog.
2008 createHomeScreenShortcutDialogFragment.show(supportFragmentManager, getString(R.string.create_shortcut))
2010 // Consume the event.
2014 R.id.view_source -> { // View source.
2015 // Open a new tab according to the current URL.
2016 if (currentWebView!!.currentUrl.startsWith("view-source:")) { // The source is currently viewed.
2017 // Open the rendered website in a new tab.
2018 addNewPage(currentWebView!!.currentUrl.substring(12, currentWebView!!.currentUrl.length), true, moveToTab = true)
2019 } else { // The rendered website is currently viewed.
2020 // Open the source in a new tab.
2021 addNewPage("view-source:${currentWebView!!.currentUrl}", adjacent = true, moveToTab = true)
2024 // Consume the event.
2028 R.id.view_headers -> { // View headers.
2029 // Create an intent to launch the view headers activity.
2030 val viewHeadersIntent = Intent(this, ViewHeadersActivity::class.java)
2032 // Add the variables to the intent.
2033 viewHeadersIntent.putExtra(CURRENT_URL, currentWebView!!.url)
2034 viewHeadersIntent.putExtra(USER_AGENT, currentWebView!!.settings.userAgentString)
2037 startActivity(viewHeadersIntent)
2039 // Consume the event.
2043 R.id.share_message -> { // Share a message.
2044 // Prepare the share string.
2045 val shareString = currentWebView!!.title + " – " + currentWebView!!.url
2047 // Create the share intent.
2048 val shareMessageIntent = Intent(Intent.ACTION_SEND)
2050 // Add the share string to the intent.
2051 shareMessageIntent.putExtra(Intent.EXTRA_TEXT, shareString)
2053 // Set the MIME type.
2054 shareMessageIntent.type = "text/plain"
2056 // Set the intent to open in a new task.
2057 shareMessageIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
2060 startActivity(Intent.createChooser(shareMessageIntent, getString(R.string.share_message)))
2062 // Consume the event.
2066 R.id.share_url -> { // Share URL.
2067 // Create the share intent.
2068 val shareUrlIntent = Intent(Intent.ACTION_SEND)
2070 // Add the URL to the intent.
2071 shareUrlIntent.putExtra(Intent.EXTRA_TEXT, currentWebView!!.url)
2073 // Add the title to the intent.
2074 shareUrlIntent.putExtra(Intent.EXTRA_SUBJECT, currentWebView!!.title)
2076 // Set the MIME type.
2077 shareUrlIntent.type = "text/plain"
2079 // Set the intent to open in a new task.
2080 shareUrlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
2083 startActivity(Intent.createChooser(shareUrlIntent, getString(R.string.share_url)))
2085 // Consume the event.
2089 R.id.open_with_app -> { // Open with app.
2090 // Open the URL with an outside app.
2091 openWithApp(currentWebView!!.url!!)
2093 // Consume the event.
2097 R.id.open_with_browser -> { // Open with browser.
2098 // Open the URL with an outside browser.
2099 openWithBrowser(currentWebView!!.url!!)
2101 // Consume the event.
2105 R.id.add_or_edit_domain -> { // Add or edit domain.
2106 // Reapply the domain settings on returning to the main WebView activity.
2107 reapplyDomainSettingsOnRestart = true
2109 // Check if domain settings are currently applied.
2110 if (currentWebView!!.domainSettingsApplied) { // Edit the current domain settings.
2111 // Create an intent to launch the domains activity.
2112 val domainsIntent = Intent(this, DomainsActivity::class.java)
2114 // Add the extra information to the intent.
2115 domainsIntent.putExtra(LOAD_DOMAIN, currentWebView!!.domainSettingsDatabaseId)
2116 domainsIntent.putExtra(CLOSE_ON_BACK, true)
2117 domainsIntent.putExtra(CURRENT_URL, currentWebView!!.url)
2118 domainsIntent.putExtra(CURRENT_IP_ADDRESSES, currentWebView!!.currentIpAddresses)
2120 // Get the current certificate.
2121 val sslCertificate = currentWebView!!.certificate
2123 // Check to see if the SSL certificate is populated.
2124 if (sslCertificate != null) {
2125 // Extract the certificate to strings.
2126 val issuedToCName = sslCertificate.issuedTo.cName
2127 val issuedToOName = sslCertificate.issuedTo.oName
2128 val issuedToUName = sslCertificate.issuedTo.uName
2129 val issuedByCName = sslCertificate.issuedBy.cName
2130 val issuedByOName = sslCertificate.issuedBy.oName
2131 val issuedByUName = sslCertificate.issuedBy.uName
2132 val startDateLong = sslCertificate.validNotBeforeDate.time
2133 val endDateLong = sslCertificate.validNotAfterDate.time
2135 // Add the certificate to the intent.
2136 domainsIntent.putExtra(SSL_ISSUED_TO_CNAME, issuedToCName)
2137 domainsIntent.putExtra(SSL_ISSUED_TO_ONAME, issuedToOName)
2138 domainsIntent.putExtra(SSL_ISSUED_TO_UNAME, issuedToUName)
2139 domainsIntent.putExtra(SSL_ISSUED_BY_CNAME, issuedByCName)
2140 domainsIntent.putExtra(SSL_ISSUED_BY_ONAME, issuedByOName)
2141 domainsIntent.putExtra(SSL_ISSUED_BY_UNAME, issuedByUName)
2142 domainsIntent.putExtra(SSL_START_DATE, startDateLong)
2143 domainsIntent.putExtra(SSL_END_DATE, endDateLong)
2147 startActivity(domainsIntent)
2148 } else { // Add a new domain.
2149 // Get the current URI.
2150 val currentUri = Uri.parse(currentWebView!!.url)
2152 // Get the current domain from the URI. Use an empty string if it is null.
2153 val currentDomain = currentUri.host?: ""
2155 // Get the current settings status.
2156 val javaScriptInt = calculateSettingsInt(currentWebView!!.settings.javaScriptEnabled, sharedPreferences.getBoolean(getString(R.string.javascript_key), false))
2157 val cookiesInt = calculateSettingsInt(currentWebView!!.acceptCookies, sharedPreferences.getBoolean(getString(R.string.cookies_key), false))
2158 val domStorageInt = calculateSettingsInt(currentWebView!!.settings.domStorageEnabled, sharedPreferences.getBoolean(getString(R.string.dom_storage_key), false))
2159 val easyListInt = calculateSettingsInt(currentWebView!!.easyListEnabled, sharedPreferences.getBoolean(getString(R.string.easylist_key), true))
2160 val easyPrivacyInt = calculateSettingsInt(currentWebView!!.easyPrivacyEnabled, sharedPreferences.getBoolean(getString(R.string.easyprivacy_key), true))
2161 val fanboysAnnoyanceListInt = calculateSettingsInt(currentWebView!!.fanboysAnnoyanceListEnabled, sharedPreferences.getBoolean(getString(R.string.fanboys_annoyance_list_key), true))
2162 val fanboysSocialBlockingListInt = calculateSettingsInt(currentWebView!!.fanboysSocialBlockingListEnabled, sharedPreferences.getBoolean(getString(R.string.fanboys_social_blocking_list_key), true))
2163 val ultraListInt = calculateSettingsInt(currentWebView!!.ultraListEnabled, sharedPreferences.getBoolean(getString(R.string.ultralist_key), true))
2164 val ultraPrivacyInt = calculateSettingsInt(currentWebView!!.ultraPrivacyEnabled, sharedPreferences.getBoolean(getString(R.string.ultraprivacy_key), true))
2165 val blockAllThirdPartyRequestsInt = calculateSettingsInt(currentWebView!!.blockAllThirdPartyRequests, sharedPreferences.getBoolean(getString(R.string.block_all_third_party_requests_key), true))
2166 val swipeToRefreshInt = calculateSettingsInt(currentWebView!!.swipeToRefresh, sharedPreferences.getBoolean(getString(R.string.swipe_to_refresh_key), true))
2167 val wideViewportInt = calculateSettingsInt(currentWebView!!.settings.useWideViewPort, sharedPreferences.getBoolean(getString(R.string.wide_viewport_key), true))
2168 val displayImagesInt = calculateSettingsInt(currentWebView!!.settings.loadsImagesAutomatically, sharedPreferences.getBoolean(getString(R.string.display_webpage_images_key), true))
2170 // Initialize the form data int.
2171 var formDataInt = SYSTEM_DEFAULT
2173 // Set the form data int, which can be removed once the minimum API >= 26.
2174 @Suppress("DEPRECATION")
2175 if (Build.VERSION.SDK_INT < 26) {
2176 // Get the form data status.
2177 val formDataEnabled = currentWebView!!.settings.saveFormData
2179 // Calculate the form data Int.
2180 formDataInt = calculateSettingsInt(formDataEnabled, sharedPreferences.getBoolean(getString(R.string.save_form_data_key), false))
2183 // Get the current user agent string.
2184 val currentUserAgentString = currentWebView!!.settings.userAgentString
2186 // Get the user agent string array position.
2187 val userAgentStringArrayPosition = userAgentDataArrayAdapter.getPosition(currentUserAgentString)
2189 // Set the user agent name.
2190 val userAgentName = if ((userAgentStringArrayPosition >= 0) && (defaultUserAgentName == userAgentNamesArray[userAgentStringArrayPosition])) { // The system default user agent is in use.
2191 getString(R.string.system_default_user_agent)
2192 } else { // An on-the-fly user agent is being used (or the WebView default user agent is applied).
2193 when (userAgentStringArrayPosition) {
2194 UNRECOGNIZED_USER_AGENT -> { // The user agent is unrecognized.
2195 if (currentUserAgentString == webViewDefaultUserAgent) { // The WebView default user agent is being used.
2196 if (defaultUserAgentName == getString(R.string.webview_default)) { // The WebView default user agent is the system default.
2197 // Set the user agent name to be the system default.
2198 getString(R.string.system_default_user_agent)
2199 } else { // The WebView default user agent is set as an on-the-fly setting.
2200 // Set the default user agent name.
2201 getString(R.string.webview_default)
2203 } else { // A custom user agent is being used.
2204 if (defaultUserAgentName == getString(R.string.custom_user_agent_non_translatable)) { // The system custom user agent is in use.
2205 // Set the user agent name to be the system default.
2206 getString(R.string.system_default_user_agent)
2207 } else { // An on-the-fly custom user agent is in use.
2208 // Store the user agent as currently applied.
2209 currentUserAgentString
2214 else -> // Store the standard user agent name.
2215 userAgentNamesArray[userAgentStringArrayPosition]
2219 // Get the current text zoom integer.
2220 val textZoomInt = currentWebView!!.settings.textZoom
2222 // Set the font size integer.
2223 val fontSizeInt = if (textZoomInt == defaultFontSizeString.toInt()) // The current system default is used, which is encoded as a zoom of `0`.
2225 else // A custom font size is used.
2228 // Get the current WebView dark theme status.
2229 val webViewDarkThemeCurrentlyEnabled = if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) // Algorithmic darkening is supported.
2230 WebSettingsCompat.isAlgorithmicDarkeningAllowed(currentWebView!!.settings)
2231 else // Algorithmic darkening is not supported.
2234 // Get the default WebView dark theme setting.
2235 val defaultWebViewDarkThemeEnabled = if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) { // Algorithmic darkening is supported.
2236 when (defaultWebViewTheme) {
2237 webViewThemeEntryValuesStringArray[1] -> // The dark theme is disabled by default.
2240 webViewThemeEntryValuesStringArray[2] -> // The dark theme is enabled by default.
2243 else -> { // The system default theme is selected.
2244 // Get the current app theme status.
2245 val currentAppThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
2247 // Check if the current app theme is dark.
2248 currentAppThemeStatus == Configuration.UI_MODE_NIGHT_YES
2251 } else { // Algorithmic darkening is not supported.
2255 // Set the WebView theme int.
2256 val webViewThemeInt = if (webViewDarkThemeCurrentlyEnabled == defaultWebViewDarkThemeEnabled) // The current WebView theme matches the default.
2258 else if (webViewDarkThemeCurrentlyEnabled) // The current WebView theme is dark and that is not the default.
2260 else // The current WebView theme is light and that is not the default.
2263 // Create the domain and store the database ID.
2264 val newDomainDatabaseId = domainsDatabaseHelper!!.addDomain(currentDomain, javaScriptInt, cookiesInt, domStorageInt, formDataInt, userAgentName, easyListInt, easyPrivacyInt,
2265 fanboysAnnoyanceListInt, fanboysSocialBlockingListInt, ultraListInt, ultraPrivacyInt, blockAllThirdPartyRequestsInt, fontSizeInt,
2266 swipeToRefreshInt, webViewThemeInt, wideViewportInt, displayImagesInt)
2268 // Create an intent to launch the domains activity.
2269 val domainsIntent = Intent(this, DomainsActivity::class.java)
2271 // Add the extra information to the intent.
2272 domainsIntent.putExtra(LOAD_DOMAIN, newDomainDatabaseId)
2273 domainsIntent.putExtra(CLOSE_ON_BACK, true)
2274 domainsIntent.putExtra(CURRENT_URL, currentWebView!!.url)
2275 domainsIntent.putExtra(CURRENT_IP_ADDRESSES, currentWebView!!.currentIpAddresses)
2277 // Get the current certificate.
2278 val sslCertificate = currentWebView!!.certificate
2280 // Check to see if the SSL certificate is populated.
2281 if (sslCertificate != null) {
2282 // Extract the certificate to strings.
2283 val issuedToCName = sslCertificate.issuedTo.cName
2284 val issuedToOName = sslCertificate.issuedTo.oName
2285 val issuedToUName = sslCertificate.issuedTo.uName
2286 val issuedByCName = sslCertificate.issuedBy.cName
2287 val issuedByOName = sslCertificate.issuedBy.oName
2288 val issuedByUName = sslCertificate.issuedBy.uName
2289 val startDateLong = sslCertificate.validNotBeforeDate.time
2290 val endDateLong = sslCertificate.validNotAfterDate.time
2292 // Add the certificate to the intent.
2293 domainsIntent.putExtra(SSL_ISSUED_TO_CNAME, issuedToCName)
2294 domainsIntent.putExtra(SSL_ISSUED_TO_ONAME, issuedToOName)
2295 domainsIntent.putExtra(SSL_ISSUED_TO_UNAME, issuedToUName)
2296 domainsIntent.putExtra(SSL_ISSUED_BY_CNAME, issuedByCName)
2297 domainsIntent.putExtra(SSL_ISSUED_BY_ONAME, issuedByOName)
2298 domainsIntent.putExtra(SSL_ISSUED_BY_UNAME, issuedByUName)
2299 domainsIntent.putExtra(SSL_START_DATE, startDateLong)
2300 domainsIntent.putExtra(SSL_END_DATE, endDateLong)
2304 startActivity(domainsIntent)
2307 // Consume the event.
2311 else -> { // There is no match with the options menu. Pass the event up to the parent method.
2312 // Don't consume the event.
2313 super.onOptionsItemSelected(menuItem)
2318 override fun onNavigationItemSelected(menuItem: MenuItem): Boolean {
2319 // Run the commands that correspond to the selected menu item.
2320 when (menuItem.itemId) {
2321 R.id.clear_and_exit -> { // Clear and exit.
2322 // Clear and exit Privacy Browser.
2326 R.id.home -> { // Home.
2327 // Load the homepage.
2328 loadUrl(currentWebView!!, sharedPreferences.getString(getString(R.string.homepage_key), getString(R.string.homepage_default_value))!!)
2331 R.id.back -> { // Back.
2332 // Check if the WebView can go back.
2333 if (currentWebView!!.canGoBack()) {
2334 // Get the current web back forward list.
2335 val webBackForwardList = currentWebView!!.copyBackForwardList()
2337 // Get the previous entry data.
2338 val previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex - 1).url
2339 val previousFavoriteIcon = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex - 1).favicon!!
2341 // Apply the domain settings.
2342 applyDomainSettings(currentWebView!!, previousUrl, resetTab = false, reloadWebsite = false, loadUrl = false)
2344 // Get the current tab.
2345 val tab = tabLayout.getTabAt(tabLayout.selectedTabPosition)!!
2347 // Get the custom view from the tab.
2348 val tabView = tab.customView!!
2350 // Get the favorite icon image view from the tab.
2351 val tabFavoriteIconImageView = tabView.findViewById<ImageView>(R.id.favorite_icon_imageview)
2353 // Set the previous favorite icon.
2354 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(previousFavoriteIcon, 64, 64, true))
2356 // Load the previous website in the history.
2357 currentWebView!!.goBack()
2359 // Update the URL edit text after a delay.
2360 updateUrlEditTextAfterDelay()
2364 R.id.forward -> { // Forward.
2365 // Check if the WebView can go forward.
2366 if (currentWebView!!.canGoForward()) {
2367 // Get the current web back forward list.
2368 val webBackForwardList = currentWebView!!.copyBackForwardList()
2370 // Get the next entry data.
2371 val nextUrl = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex + 1).url
2372 val nextFavoriteIcon = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex + 1).favicon!!
2374 // Apply the domain settings.
2375 applyDomainSettings(currentWebView!!, nextUrl, resetTab = false, reloadWebsite = false, loadUrl = false)
2377 // Get the current tab.
2378 val tab = tabLayout.getTabAt(tabLayout.selectedTabPosition)!!
2380 // Get the custom view from the tab.
2381 val tabView = tab.customView!!
2383 // Get the favorite icon image view from the tab.
2384 val tabFavoriteIconImageView = tabView.findViewById<ImageView>(R.id.favorite_icon_imageview)
2386 // Set the next favorite icon.
2387 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nextFavoriteIcon, 64, 64, true))
2389 // Load the next website in the history.
2390 currentWebView!!.goForward()
2392 // Update the URL edit text after a delay.
2393 updateUrlEditTextAfterDelay()
2397 R.id.scroll_to_bottom -> { // Scroll to Bottom.
2398 // Check if the WebView is scrolled to the top.
2399 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.
2400 currentWebView!!.scrollTo(0, 1_000_000_000)
2401 } else { // The WebView is not at the top; scroll to the top.
2402 currentWebView!!.scrollTo(0, 0)
2406 R.id.history -> { // History.
2407 // Instantiate the URL history dialog.
2408 val urlHistoryDialogFragment: DialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView!!.webViewFragmentId)
2410 // Show the URL history dialog.
2411 urlHistoryDialogFragment.show(supportFragmentManager, getString(R.string.history))
2414 R.id.open -> { // Open.
2415 // Instantiate the open file dialog.
2416 val openDialogFragment: DialogFragment = OpenDialog()
2418 // Show the open file dialog.
2419 openDialogFragment.show(supportFragmentManager, getString(R.string.open))
2422 R.id.requests -> { // Requests.
2423 // Populate the resource requests.
2424 RequestsActivity.resourceRequests = currentWebView!!.getResourceRequests()
2426 // Create an intent to launch the Requests activity.
2427 val requestsIntent = Intent(this, RequestsActivity::class.java)
2429 // Add the block third-party requests status to the intent.
2430 requestsIntent.putExtra(BLOCK_ALL_THIRD_PARTY_REQUESTS, currentWebView!!.blockAllThirdPartyRequests)
2433 startActivity(requestsIntent)
2436 R.id.downloads -> { // Downloads.
2437 // Try the default system download manager.
2439 // Launch the default system Download Manager.
2440 val defaultDownloadManagerIntent = Intent(DownloadManager.ACTION_VIEW_DOWNLOADS)
2442 // Launch as a new task so that the download manager and Privacy Browser show as separate windows in the recent tasks list.
2443 defaultDownloadManagerIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2446 startActivity(defaultDownloadManagerIntent)
2447 } catch (defaultDownloadManagerException: Exception) { // The system download manager is not available.
2448 // Try a generic file manager.
2450 // Create a generic file manager intent.
2451 val genericFileManagerIntent = Intent(Intent.ACTION_VIEW)
2453 // Open the download directory.
2454 genericFileManagerIntent.setDataAndType(Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()), DocumentsContract.Document.MIME_TYPE_DIR)
2456 // Launch as a new task so that the file manager and Privacy Browser show as separate windows in the recent tasks list.
2457 genericFileManagerIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2460 startActivity(genericFileManagerIntent)
2461 } catch (genericFileManagerException: Exception) { // A generic file manager is not available.
2462 // Try an alternate file manager.
2464 // Create an alternate file manager intent.
2465 val alternateFileManagerIntent = Intent(Intent.ACTION_VIEW)
2467 // Open the download directory.
2468 alternateFileManagerIntent.setDataAndType(Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()), "resource/folder")
2470 // Launch as a new task so that the file manager and Privacy Browser show as separate windows in the recent tasks list.
2471 alternateFileManagerIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2473 // Open the alternate file manager.
2474 startActivity(alternateFileManagerIntent)
2475 } catch (alternateFileManagerException: Exception) {
2476 // Display a snackbar.
2477 Snackbar.make(currentWebView!!, R.string.no_file_manager_detected, Snackbar.LENGTH_INDEFINITE).show()
2483 R.id.domains -> { // Domains.
2484 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2485 reapplyDomainSettingsOnRestart = true
2487 // Create a domains activity intent.
2488 val domainsIntent = Intent(this, DomainsActivity::class.java)
2490 // Add the extra information to the intent.
2491 domainsIntent.putExtra(CURRENT_URL, currentWebView!!.url)
2492 domainsIntent.putExtra(CURRENT_IP_ADDRESSES, currentWebView!!.currentIpAddresses)
2494 // Get the current certificate.
2495 val sslCertificate = currentWebView!!.certificate
2497 // Check to see if the SSL certificate is populated.
2498 if (sslCertificate != null) {
2499 // Extract the certificate to strings.
2500 val issuedToCName = sslCertificate.issuedTo.cName
2501 val issuedToOName = sslCertificate.issuedTo.oName
2502 val issuedToUName = sslCertificate.issuedTo.uName
2503 val issuedByCName = sslCertificate.issuedBy.cName
2504 val issuedByOName = sslCertificate.issuedBy.oName
2505 val issuedByUName = sslCertificate.issuedBy.uName
2506 val startDateLong = sslCertificate.validNotBeforeDate.time
2507 val endDateLong = sslCertificate.validNotAfterDate.time
2509 // Add the certificate to the intent.
2510 domainsIntent.putExtra(SSL_ISSUED_TO_CNAME, issuedToCName)
2511 domainsIntent.putExtra(SSL_ISSUED_TO_ONAME, issuedToOName)
2512 domainsIntent.putExtra(SSL_ISSUED_TO_UNAME, issuedToUName)
2513 domainsIntent.putExtra(SSL_ISSUED_BY_CNAME, issuedByCName)
2514 domainsIntent.putExtra(SSL_ISSUED_BY_ONAME, issuedByOName)
2515 domainsIntent.putExtra(SSL_ISSUED_BY_UNAME, issuedByUName)
2516 domainsIntent.putExtra(SSL_START_DATE, startDateLong)
2517 domainsIntent.putExtra(SSL_END_DATE, endDateLong)
2521 startActivity(domainsIntent)
2524 R.id.settings -> { // Settings.
2525 // Set the reapply on restart flags.
2526 reapplyAppSettingsOnRestart = true
2527 reapplyDomainSettingsOnRestart = true
2529 // Create a settings intent.
2530 val settingsIntent = Intent(this, SettingsActivity::class.java)
2533 startActivity(settingsIntent)
2536 R.id.import_export -> { // Import/Export.
2537 // Create an intent to launch the import/export activity.
2538 val importExportIntent = Intent(this, ImportExportActivity::class.java)
2541 startActivity(importExportIntent)
2544 R.id.logcat -> { // Logcat.
2545 // Create an intent to launch the logcat activity.
2546 val logcatIntent = Intent(this, LogcatActivity::class.java)
2549 startActivity(logcatIntent)
2552 R.id.webview_devtools -> { // WebView DevTools.
2553 // Create a WebView DevTools intent.
2554 val webViewDevToolsIntent = Intent("com.android.webview.SHOW_DEV_UI")
2556 // Launch as a new task so that the WebView DevTools and Privacy Browser show as a separate windows in the recent tasks list.
2557 webViewDevToolsIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2560 startActivity(webViewDevToolsIntent)
2563 R.id.guide -> { // Guide.
2564 // Create an intent to launch the guide activity.
2565 val guideIntent = Intent(this, GuideActivity::class.java)
2568 startActivity(guideIntent)
2571 R.id.about -> { // About
2572 // Create an intent to launch the about activity.
2573 val aboutIntent = Intent(this, AboutActivity::class.java)
2575 // Create a string array for the filter list versions.
2576 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])
2578 // Add the filter list versions to the intent.
2579 aboutIntent.putExtra(FILTERLIST_VERSIONS, filterListVersions)
2582 startActivity(aboutIntent)
2586 // Close the navigation drawer.
2587 drawerLayout.closeDrawer(GravityCompat.START)
2593 override fun onCreateContextMenu(contextMenu: ContextMenu, view: View, contextMenuInfo: ContextMenu.ContextMenuInfo?) {
2594 // Get the hit test result.
2595 val hitTestResult = currentWebView!!.hitTestResult
2597 // Define the URL strings.
2598 val imageUrl: String?
2599 val linkUrl: String?
2601 // Get a handle for the clipboard manager.
2602 val clipboardManager = (getSystemService(CLIPBOARD_SERVICE) as ClipboardManager)
2604 // Process the link according to the type.
2605 when (hitTestResult.type) {
2606 // `SRC_ANCHOR_TYPE` is a link.
2607 WebView.HitTestResult.SRC_ANCHOR_TYPE -> {
2608 // Get the target URL.
2609 linkUrl = hitTestResult.extra!!
2611 // Set the target URL as the context menu title.
2612 contextMenu.setHeaderTitle(linkUrl)
2614 // Add an open in new tab entry.
2615 contextMenu.add(R.string.open_in_new_tab).setOnMenuItemClickListener {
2616 // Load the link URL in a new tab and move to it.
2617 addNewPage(linkUrl, adjacent = true, moveToTab = true)
2619 // Consume the event.
2623 // Add an open in background entry.
2624 contextMenu.add(R.string.open_in_background).setOnMenuItemClickListener {
2625 // Load the link URL in a new tab but do not move to it.
2626 addNewPage(linkUrl, adjacent = true, moveToTab = false)
2628 // Consume the event.
2632 // Add an open with app entry.
2633 contextMenu.add(R.string.open_with_app).setOnMenuItemClickListener {
2634 // Open the URL with another app.
2635 openWithApp(linkUrl)
2637 // Consume the event.
2641 // Add an open with browser entry.
2642 contextMenu.add(R.string.open_with_browser).setOnMenuItemClickListener {
2643 // Open the URL with another browser.
2644 openWithBrowser(linkUrl)
2646 // Consume the event.
2650 // Add a copy URL entry.
2651 contextMenu.add(R.string.copy_url).setOnMenuItemClickListener {
2652 // Save the link URL in a clip data.
2653 val srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl)
2655 // Set the clip data as the clipboard's primary clip.
2656 clipboardManager.setPrimaryClip(srcAnchorTypeClipData)
2658 // Consume the event.
2662 // Add a Save URL entry.
2663 contextMenu.add(R.string.save_url).setOnMenuItemClickListener {
2664 // Check the download preference.
2665 if (downloadWithExternalApp) // Download with an external app.
2666 downloadUrlWithExternalApp(linkUrl)
2667 else // Handle the download inside of Privacy Browser. The dialog will be displayed once the file size and the content disposition have been acquired.
2668 PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, linkUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
2670 // Consume the event.
2674 // Add a Share URL entry.
2675 contextMenu.add(R.string.share_url).setOnMenuItemClickListener {
2676 // Create the share intent.
2677 val shareUrlIntent = Intent(Intent.ACTION_SEND)
2679 // Add the URL to the intent.
2680 shareUrlIntent.putExtra(Intent.EXTRA_TEXT, linkUrl)
2682 // Set the MIME type.
2683 shareUrlIntent.type = "text/plain"
2685 // Set the intent to open in a new task.
2686 shareUrlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
2689 startActivity(Intent.createChooser(shareUrlIntent, getString(R.string.share_url)))
2691 // Consume the event.
2695 // Add an empty cancel entry, which by default closes the context menu.
2696 contextMenu.add(R.string.cancel)
2699 // `IMAGE_TYPE` is an image.
2700 WebView.HitTestResult.IMAGE_TYPE -> {
2701 // Get the image URL.
2702 imageUrl = hitTestResult.extra!!
2704 // Set the context menu title.
2705 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.
2706 contextMenu.setHeaderTitle(imageUrl.substring(0, 100))
2707 else // The image URL does not contain the full image data. Set the image URL as the title of the context menu.
2708 contextMenu.setHeaderTitle(imageUrl)
2710 // Add an open in new tab entry.
2711 contextMenu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener {
2712 // Load the image in a new tab.
2713 addNewPage(imageUrl, adjacent = true, moveToTab = true)
2715 // Consume the event.
2719 // Add an open with app entry.
2720 contextMenu.add(R.string.open_with_app).setOnMenuItemClickListener {
2721 // Open the image URL with an external app.
2722 openWithApp(imageUrl)
2724 // Consume the event.
2728 // Add an open with browser entry.
2729 contextMenu.add(R.string.open_with_browser).setOnMenuItemClickListener {
2730 // Open the image URL with an external browser.
2731 openWithBrowser(imageUrl)
2733 // Consume the event.
2737 // Add a view image entry.
2738 contextMenu.add(R.string.view_image).setOnMenuItemClickListener {
2739 // Load the image in the current tab.
2740 loadUrl(currentWebView!!, imageUrl)
2742 // Consume the event.
2746 // Add a save image entry.
2747 contextMenu.add(R.string.save_image).setOnMenuItemClickListener {
2748 // Check the download preference.
2749 if (downloadWithExternalApp) { // Download with an external app.
2750 downloadUrlWithExternalApp(imageUrl)
2751 } else { // Handle the download inside of Privacy Browser. The dialog will be displayed once the file size and the content disposition have been acquired.
2752 PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, imageUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
2755 // Consume the event.
2759 // Add a copy URL entry.
2760 contextMenu.add(R.string.copy_url).setOnMenuItemClickListener {
2761 // Save the image URL in a clip data.
2762 val imageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl)
2764 // Set the clip data as the clipboard's primary clip.
2765 clipboardManager.setPrimaryClip(imageTypeClipData)
2767 // Consume the event.
2771 // Add a Share URL entry.
2772 contextMenu.add(R.string.share_url).setOnMenuItemClickListener {
2773 // Create the share intent.
2774 val shareUrlIntent = Intent(Intent.ACTION_SEND)
2776 // Add the URL to the intent.
2777 shareUrlIntent.putExtra(Intent.EXTRA_TEXT, imageUrl)
2779 // Set the MIME type.
2780 shareUrlIntent.type = "text/plain"
2782 // Set the intent to open in a new task.
2783 shareUrlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
2786 startActivity(Intent.createChooser(shareUrlIntent, getString(R.string.share_url)))
2788 // Consume the event.
2792 // Add an empty cancel entry, which by default closes the context menu.
2793 contextMenu.add(R.string.cancel)
2796 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2797 WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE -> {
2798 // Get the image URL.
2799 imageUrl = hitTestResult.extra!!
2801 // Instantiate a handler.
2802 val handler = Handler(Looper.getMainLooper())
2804 // Get a handle for the handler message.
2805 val message = handler.obtainMessage()
2807 // Request the image details from the last touched node be returned in the message.
2808 currentWebView!!.requestFocusNodeHref(message)
2810 // Get the link URL from the message data.
2811 linkUrl = message.data.getString("url")!!
2813 // Set the link URL as the title of the context menu.
2814 contextMenu.setHeaderTitle(linkUrl)
2816 // Add an open in new tab entry.
2817 contextMenu.add(R.string.open_in_new_tab).setOnMenuItemClickListener {
2818 // Load the link URL in a new tab and move to it.
2819 addNewPage(linkUrl, adjacent = true, moveToTab = true)
2821 // Consume the event.
2825 // Add an open in background entry.
2826 contextMenu.add(R.string.open_in_background).setOnMenuItemClickListener {
2827 // Lod the link URL in a new tab but do not move to it.
2828 addNewPage(linkUrl, adjacent = true, moveToTab = false)
2830 // Consume the event.
2834 // Add an open image in new tab entry.
2835 contextMenu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener {
2836 // Load the image in a new tab and move to it.
2837 addNewPage(imageUrl, adjacent = true, moveToTab = true)
2839 // Consume the event.
2843 // Add an open with app entry.
2844 contextMenu.add(R.string.open_with_app).setOnMenuItemClickListener {
2845 // Open the link URL with an external app.
2846 openWithApp(linkUrl)
2848 // Consume the event.
2852 // Add an open with browser entry.
2853 contextMenu.add(R.string.open_with_browser).setOnMenuItemClickListener {
2854 // Open the link URL with an external browser.
2855 openWithBrowser(linkUrl)
2857 // Consume the event.
2861 // Add a view image entry.
2862 contextMenu.add(R.string.view_image).setOnMenuItemClickListener {
2863 // View the image in the current tab.
2864 loadUrl(currentWebView!!, imageUrl)
2866 // Consume the event.
2870 // Add a Save Image entry.
2871 contextMenu.add(R.string.save_image).setOnMenuItemClickListener {
2872 // Check the download preference.
2873 if (downloadWithExternalApp) // Download with an external app.
2874 downloadUrlWithExternalApp(imageUrl)
2875 else // Handle the download inside of Privacy Browser. The dialog will be displayed once the file size and the content disposition have been acquired.
2876 PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, imageUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
2878 // Consume the event.
2882 // Add a Share Image entry.
2883 contextMenu.add(R.string.share_image).setOnMenuItemClickListener {
2884 // Create the share intent.
2885 val shareUrlIntent = Intent(Intent.ACTION_SEND)
2887 // Add the URL to the intent.
2888 shareUrlIntent.putExtra(Intent.EXTRA_TEXT, imageUrl)
2890 // Set the MIME type.
2891 shareUrlIntent.type = "text/plain"
2893 // Set the intent to open in a new task.
2894 shareUrlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
2897 startActivity(Intent.createChooser(shareUrlIntent, getString(R.string.share_url)))
2899 // Consume the event.
2903 // Add a copy URL entry.
2904 contextMenu.add(R.string.copy_url).setOnMenuItemClickListener {
2905 // Save the link URL in a clip data.
2906 val srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl)
2908 // Set the clip data as the clipboard's primary clip.
2909 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData)
2911 // Consume the event.
2915 // Add a save URL entry.
2916 contextMenu.add(R.string.save_url).setOnMenuItemClickListener {
2917 // Check the download preference.
2918 if (downloadWithExternalApp) // Download with an external app.
2919 downloadUrlWithExternalApp(linkUrl)
2920 else // Handle the download inside of Privacy Browser. The dialog will be displayed once the file size and the content disposition have been acquired.
2921 PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, linkUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
2923 // Consume the event.
2927 // Add a Share URL entry.
2928 contextMenu.add(R.string.share_url).setOnMenuItemClickListener {
2929 // Create the share intent.
2930 val shareUrlIntent = Intent(Intent.ACTION_SEND)
2932 // Add the URL to the intent.
2933 shareUrlIntent.putExtra(Intent.EXTRA_TEXT, linkUrl)
2935 // Set the MIME type.
2936 shareUrlIntent.type = "text/plain"
2938 // Set the intent to open in a new task.
2939 shareUrlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
2942 startActivity(Intent.createChooser(shareUrlIntent, getString(R.string.share_url)))
2944 // Consume the event.
2948 // Add an empty cancel entry, which by default closes the context menu.
2949 contextMenu.add(R.string.cancel)
2952 WebView.HitTestResult.EMAIL_TYPE -> {
2953 // Get the target URL.
2954 linkUrl = hitTestResult.extra
2956 // Set the target URL as the title of the context menu.
2957 contextMenu.setHeaderTitle(linkUrl)
2959 // Add a write email entry.
2960 contextMenu.add(R.string.write_email).setOnMenuItemClickListener {
2961 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2962 val emailIntent = Intent(Intent.ACTION_SENDTO)
2964 // Parse the url and set it as the data for the intent.
2965 emailIntent.data = Uri.parse("mailto:$linkUrl")
2967 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2968 emailIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2972 startActivity(emailIntent)
2973 } catch (exception: ActivityNotFoundException) {
2974 // Display a snackbar.
2975 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
2978 // Consume the event.
2982 // Add a copy email address entry.
2983 contextMenu.add(R.string.copy_email_address).setOnMenuItemClickListener {
2984 // Save the email address in a clip data.
2985 val srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl)
2987 // Set the clip data as the clipboard's primary clip.
2988 clipboardManager.setPrimaryClip(srcEmailTypeClipData)
2990 // Consume the event.
2994 // Add an empty cancel entry, which by default closes the context menu.
2995 contextMenu.add(R.string.cancel)
3000 // The view parameter cannot be removed because it is called from the layout onClick.
3001 fun addTab(@Suppress("UNUSED_PARAMETER")view: View?) {
3002 // Add a new tab with a blank URL.
3003 addNewPage(urlString = "", adjacent = true, moveToTab = true)
3006 private fun addNewPage(urlString: String, adjacent: Boolean, moveToTab: Boolean) {
3007 // Clear the focus from the URL edit text, so that it will be populated with the information from the new tab.
3008 urlEditText.clearFocus()
3010 // Add the new tab after the tab layout has quiesced.
3011 // 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>
3013 // Get the new tab position.
3014 val newTabPosition = if (adjacent) // The new tab position is immediately to the right of the current tab position.
3015 tabLayout.selectedTabPosition + 1
3016 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.
3019 // Add the new WebView page.
3020 webViewStateAdapter!!.addPage(newTabPosition, urlString)
3023 addNewTab(newTabPosition, moveToTab)
3027 private fun addNewTab(newTabPosition: Int, moveToTab: Boolean) {
3028 // Check to see if the new page is ready.
3029 if (webViewStateAdapter!!.itemCount >= tabLayout.tabCount) { // The new page is ready.
3030 // Create a new tab.
3031 val newTab = tabLayout.newTab()
3033 // Set a custom view on the new tab.
3034 newTab.setCustomView(R.layout.tab_custom_view)
3037 tabLayout.addTab(newTab, newTabPosition, moveToTab)
3039 // 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.
3040 if (newTabPosition == 0)
3041 tabLayout.selectTab(newTab)
3043 // Scroll to the new tab position if moving to the new tab.
3046 tabLayout.setScrollPosition(newTabPosition, 0F, false, false)
3049 // Show the app bar if it is at the bottom of the screen and the new tab is taking focus.
3050 if (bottomAppBar && moveToTab && appBarLayout.translationY != 0f) {
3051 // Animate the bottom app bar onto the screen.
3052 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0f)
3055 objectAnimator.start()
3057 } else { // The new page is not ready.
3058 // Create a new tab handler.
3059 val newTabHandler = Handler(Looper.getMainLooper())
3061 // Create a new tab runnable.
3062 val newTabRunnable = Runnable {
3063 // Create the new tab.
3064 addNewTab(newTabPosition, moveToTab)
3067 // Try adding the new tab again after 50 milliseconds.
3068 newTabHandler.postDelayed(newTabRunnable, 50)
3072 private fun applyAppSettings() {
3073 // 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.
3074 defaultJavaScript = sharedPreferences.getBoolean(getString(R.string.javascript_key), false)
3075 defaultCookies = sharedPreferences.getBoolean(getString(R.string.cookies_key), false)
3076 defaultDomStorage = sharedPreferences.getBoolean(getString(R.string.dom_storage_key), false)
3077 defaultFormData = sharedPreferences.getBoolean(getString(R.string.save_form_data_key), false) // Form data can be removed once the minimum API >= 26.
3078 defaultEasyList = sharedPreferences.getBoolean(getString(R.string.easylist_key), true)
3079 defaultEasyPrivacy = sharedPreferences.getBoolean(getString(R.string.easyprivacy_key), true)
3080 defaultFanboysAnnoyanceList = sharedPreferences.getBoolean(getString(R.string.fanboys_annoyance_list_key), true)
3081 defaultFanboysSocialBlockingList = sharedPreferences.getBoolean(getString(R.string.fanboys_social_blocking_list_key), true)
3082 defaultUltraList = sharedPreferences.getBoolean(getString(R.string.ultralist_key), true)
3083 defaultUltraPrivacy = sharedPreferences.getBoolean(getString(R.string.ultraprivacy_key), true)
3084 defaultBlockAllThirdPartyRequests = sharedPreferences.getBoolean(getString(R.string.block_all_third_party_requests_key), false)
3085 defaultFontSizeString = sharedPreferences.getString(getString(R.string.font_size_key), getString(R.string.font_size_default_value))!!
3086 defaultUserAgentName = sharedPreferences.getString(getString(R.string.user_agent_key), getString(R.string.user_agent_default_value))!!
3087 defaultSwipeToRefresh = sharedPreferences.getBoolean(getString(R.string.swipe_to_refresh_key), true)
3088 defaultWebViewTheme = sharedPreferences.getString(getString(R.string.webview_theme_key), getString(R.string.webview_theme_default_value))!!
3089 defaultWideViewport = sharedPreferences.getBoolean(getString(R.string.wide_viewport_key), true)
3090 defaultDisplayWebpageImages = sharedPreferences.getBoolean(getString(R.string.display_webpage_images_key), true)
3092 // Get the WebView theme entry values string array. This is done here so that expensive resource requests are not made each time a domain is loaded.
3093 webViewThemeEntryValuesStringArray = resources.getStringArray(R.array.webview_theme_entry_values)
3095 // Get the user agent string arrays. These are done here so that expensive resource requests are not made each time a domain is loaded.
3096 userAgentDataArray = resources.getStringArray(R.array.user_agent_data)
3097 userAgentNamesArray = resources.getStringArray(R.array.user_agent_names)
3099 // Get the user agent array adapters. These are done here so that expensive resource requests are not made each time a domain is loaded.
3100 userAgentDataArrayAdapter = ArrayAdapter.createFromResource(this, R.array.user_agent_data, R.layout.spinner_item)
3101 userAgentNamesArrayAdapter = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item)
3103 // Store the values from the shared preferences in variables.
3104 incognitoModeEnabled = sharedPreferences.getBoolean(getString(R.string.incognito_mode_key), false)
3105 sanitizeTrackingQueries = sharedPreferences.getBoolean(getString(R.string.tracking_queries_key), true)
3106 sanitizeAmpRedirects = sharedPreferences.getBoolean(getString(R.string.amp_redirects_key), true)
3107 proxyMode = sharedPreferences.getString(getString(R.string.proxy_key), getString(R.string.proxy_default_value))!!
3108 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean(getString(R.string.full_screen_browsing_mode_key), false)
3109 hideAppBar = sharedPreferences.getBoolean(getString(R.string.hide_app_bar_key), true)
3110 downloadWithExternalApp = sharedPreferences.getBoolean(getString(R.string.download_with_external_app_key), false)
3111 scrollAppBar = sharedPreferences.getBoolean(getString(R.string.scroll_app_bar_key), false)
3113 // Apply the saved proxy mode if the app has been restarted.
3114 if (savedProxyMode != null) {
3115 // Apply the saved proxy mode.
3116 proxyMode = savedProxyMode!!
3118 // Reset the saved proxy mode.
3119 savedProxyMode = null
3122 // Get the search string.
3123 val searchString = sharedPreferences.getString(getString(R.string.search_key), getString(R.string.search_default_value))!!
3125 // Set the search string, using the custom search URL if specified.
3126 searchURL = if (searchString == getString(R.string.custom_url_item))
3127 sharedPreferences.getString(getString(R.string.search_custom_url_key), getString(R.string.search_custom_url_default_value))!!
3134 // Adjust the layout and scrolling parameters according to the position of the app bar.
3135 if (bottomAppBar) { // The app bar is on the bottom.
3137 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) { // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
3138 // Reset the WebView padding to fill the available space.
3139 swipeRefreshLayout.setPadding(0, 0, 0, 0)
3140 } else { // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
3141 // Move the WebView above the app bar layout.
3142 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
3144 // Show the app bar if it is scrolled off the screen.
3145 if (appBarLayout.translationY != 0f) {
3146 // Animate the bottom app bar onto the screen.
3147 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0f)
3150 objectAnimator.start()
3153 } else { // The app bar is on the top.
3154 // Get the current layout parameters. Using coordinator layout parameters allows the `setBehavior()` command and using app bar layout parameters allows the `setScrollFlags()` command.
3155 val swipeRefreshLayoutParams = swipeRefreshLayout.layoutParams as CoordinatorLayout.LayoutParams
3156 val toolbarLayoutParams = toolbar.layoutParams as AppBarLayout.LayoutParams
3157 val findOnPageLayoutParams = findOnPageLinearLayout.layoutParams as AppBarLayout.LayoutParams
3158 val tabsLayoutParams = tabsLinearLayout.layoutParams as AppBarLayout.LayoutParams
3160 // Add the scrolling behavior to the layout parameters.
3162 // Enable scrolling of the app bar.
3163 swipeRefreshLayoutParams.behavior = AppBarLayout.ScrollingViewBehavior()
3164 toolbarLayoutParams.scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS or AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP
3165 findOnPageLayoutParams.scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS or AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP
3166 tabsLayoutParams.scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS or AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP
3168 // Disable scrolling of the app bar.
3169 swipeRefreshLayoutParams.behavior = null
3170 toolbarLayoutParams.scrollFlags = 0
3171 findOnPageLayoutParams.scrollFlags = 0
3172 tabsLayoutParams.scrollFlags = 0
3174 // Expand the app bar if it is currently collapsed.
3175 appBarLayout.setExpanded(true)
3178 // Set the app bar scrolling for each WebView.
3179 for (i in 0 until webViewStateAdapter!!.itemCount) {
3180 // Get the WebView tab fragment.
3181 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
3183 // Get the fragment view.
3184 val fragmentView = webViewTabFragment.view
3186 // Only modify the WebViews if they exist.
3187 if (fragmentView != null) {
3188 // Get the nested scroll WebView from the tab fragment.
3189 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
3191 // Set the app bar scrolling.
3192 nestedScrollWebView.isNestedScrollingEnabled = scrollAppBar
3197 // Update the full screen browsing mode settings.
3198 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
3199 // Update the visibility of the app bar, which might have changed in the settings.
3201 // Hide the tab linear layout.
3202 tabsLinearLayout.visibility = View.GONE
3204 // Hide the app bar.
3207 // Show the tab linear layout.
3208 tabsLinearLayout.visibility = View.VISIBLE
3210 // Show the app bar.
3214 /* Hide the system bars.
3215 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3216 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
3217 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3218 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3221 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
3222 @Suppress("DEPRECATION")
3223 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
3224 } else { // Privacy Browser is not in full screen browsing mode.
3225 // 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.
3226 inFullScreenBrowsingMode = false
3228 // Show the tab linear layout.
3229 tabsLinearLayout.visibility = View.VISIBLE
3231 // Show the app bar.
3234 // Remove the `SYSTEM_UI` flags from the root frame layout. The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
3235 @Suppress("DEPRECATION")
3236 rootFrameLayout.systemUiVisibility = 0
3240 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
3241 @SuppressLint("SetJavaScriptEnabled")
3242 private fun applyDomainSettings(nestedScrollWebView: NestedScrollWebView, url: String?, resetTab: Boolean, reloadWebsite: Boolean, loadUrl: Boolean) {
3243 // Store the current URL.
3244 nestedScrollWebView.currentUrl = url!!
3246 // Parse the URL into a URI.
3247 val uri = Uri.parse(url)
3249 // Extract the domain from the URI.
3250 var newHostName = uri.host
3252 // Strings don't like to be null.
3253 if (newHostName == null)
3256 // 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.
3257 if ((nestedScrollWebView.currentDomainName != newHostName) || (newHostName == "")) { // A new domain is being loaded.
3258 // Set the new host name as the current domain name.
3259 nestedScrollWebView.currentDomainName = newHostName
3261 // Reset the ignoring of pinned domain information.
3262 nestedScrollWebView.ignorePinnedDomainInformation = false
3264 // Clear any pinned SSL certificate or IP addresses.
3265 nestedScrollWebView.clearPinnedSslCertificate()
3266 nestedScrollWebView.pinnedIpAddresses = ""
3268 // Reset the favorite icon if specified.
3270 // Initialize the favorite icon.
3271 nestedScrollWebView.initializeFavoriteIcon()
3273 // Get the current page position.
3274 val currentPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
3276 // Get the corresponding tab.
3277 val tab = tabLayout.getTabAt(currentPagePosition)
3279 // Update the tab if it isn't null, which sometimes happens when restarting from the background.
3281 // Get the tab custom view.
3282 val tabCustomView = tab.customView!!
3284 // Get the tab views.
3285 val tabFavoriteIconImageView = tabCustomView.findViewById<ImageView>(R.id.favorite_icon_imageview)
3286 val tabTitleTextView = tabCustomView.findViewById<TextView>(R.id.title_textview)
3288 // Store the current values in case they need to be restored.
3289 nestedScrollWebView.previousFavoriteIconDrawable = tabFavoriteIconImageView.drawable
3290 nestedScrollWebView.previousWebpageTitle = tabTitleTextView.text.toString()
3292 // Set the default favorite icon as the favorite icon for this tab.
3293 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nestedScrollWebView.getFavoriteIcon(), 64, 64, true))
3295 // Set the loading title text.
3296 tabTitleTextView.setText(R.string.loading)
3300 // Initialize the domain name in database variable.
3301 var domainNameInDatabase: String? = null
3303 // Check the hostname against the domain settings set.
3304 if (domainsSettingsSet.contains(newHostName)) { // The hostname is contained in the domain settings set.
3305 // Record the domain name in the database.
3306 domainNameInDatabase = newHostName
3308 // Set the domain settings applied tracker to true.
3309 nestedScrollWebView.domainSettingsApplied = true
3310 } else { // The hostname is not contained in the domain settings set.
3311 // Set the domain settings applied tracker to false.
3312 nestedScrollWebView.domainSettingsApplied = false
3315 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3316 while (!nestedScrollWebView.domainSettingsApplied && newHostName!!.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the hostname.
3317 if (domainsSettingsSet.contains("*.$newHostName")) { // Check the host name prepended by `*.`.
3318 // Set the domain settings applied tracker to true.
3319 nestedScrollWebView.domainSettingsApplied = true
3321 // Store the applied domain names as it appears in the database.
3322 domainNameInDatabase = "*.$newHostName"
3325 // Strip out the lowest subdomain of of the host name.
3326 newHostName = newHostName.substring(newHostName.indexOf(".") + 1)
3329 // Apply either the domain settings or the default settings.
3330 if (nestedScrollWebView.domainSettingsApplied) { // The url has custom domain settings.
3331 // Get a cursor for the current host.
3332 val currentDomainSettingsCursor = domainsDatabaseHelper!!.getCursorForDomainName(domainNameInDatabase!!)
3334 // Move to the first position.
3335 currentDomainSettingsCursor.moveToFirst()
3337 // Get the settings from the cursor.
3338 nestedScrollWebView.domainSettingsDatabaseId = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ID))
3339 val javaScriptInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_JAVASCRIPT))
3340 val cookiesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(COOKIES))
3341 val domStorageInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_DOM_STORAGE))
3342 val formDataInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_FORM_DATA)) // Form data can be removed once the minimum API >= 26.
3343 val easyListInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_EASYLIST))
3344 val easyPrivacyInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_EASYPRIVACY))
3345 val fanboysAnnoyanceListInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_FANBOYS_ANNOYANCE_LIST))
3346 val fanboysSocialBlockingListInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST))
3347 val ultraListInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.ULTRALIST))
3348 val ultraPrivacyInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_ULTRAPRIVACY))
3349 val blockAllThirdPartyRequestsInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.BLOCK_ALL_THIRD_PARTY_REQUESTS))
3350 val userAgentName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.USER_AGENT))
3351 val fontSize = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(FONT_SIZE))
3352 val swipeToRefreshInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(SWIPE_TO_REFRESH))
3353 val webViewThemeInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(WEBVIEW_THEME))
3354 val wideViewportInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(WIDE_VIEWPORT))
3355 val displayWebpageImagesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DISPLAY_IMAGES))
3356 val pinnedSslCertificate = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(PINNED_SSL_CERTIFICATE)) == 1)
3357 val pinnedSslIssuedToCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_TO_COMMON_NAME))
3358 val pinnedSslIssuedToOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_TO_ORGANIZATION))
3359 val pinnedSslIssuedToUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_TO_ORGANIZATIONAL_UNIT))
3360 val pinnedSslIssuedByCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_BY_COMMON_NAME))
3361 val pinnedSslIssuedByOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_BY_ORGANIZATION))
3362 val pinnedSslIssuedByUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_BY_ORGANIZATIONAL_UNIT))
3363 val pinnedSslStartDate = Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.SSL_START_DATE)))
3364 val pinnedSslEndDate = Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.SSL_END_DATE)))
3365 val pinnedIpAddresses = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(PINNED_IP_ADDRESSES)) == 1)
3366 val pinnedHostIpAddresses = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(IP_ADDRESSES))
3368 // Close the current host domain settings cursor.
3369 currentDomainSettingsCursor.close()
3371 // Set the JavaScript status.
3372 when (javaScriptInt) {
3373 SYSTEM_DEFAULT -> nestedScrollWebView.settings.javaScriptEnabled = defaultJavaScript
3374 ENABLED -> nestedScrollWebView.settings.javaScriptEnabled = true
3375 DISABLED -> nestedScrollWebView.settings.javaScriptEnabled = false
3378 // Store the cookies status.
3380 SYSTEM_DEFAULT -> nestedScrollWebView.acceptCookies = defaultCookies
3381 ENABLED -> nestedScrollWebView.acceptCookies = true
3382 DISABLED -> nestedScrollWebView.acceptCookies = false
3385 // Apply the cookies status.
3386 cookieManager.setAcceptCookie(nestedScrollWebView.acceptCookies)
3388 // Set the DOM storage status.
3389 when (domStorageInt) {
3390 SYSTEM_DEFAULT -> nestedScrollWebView.settings.domStorageEnabled = defaultDomStorage
3391 ENABLED -> nestedScrollWebView.settings.domStorageEnabled = true
3392 DISABLED -> nestedScrollWebView.settings.domStorageEnabled = false
3395 // Apply the form data setting if the API < 26.
3396 @Suppress("DEPRECATION")
3397 if (Build.VERSION.SDK_INT < 26) {
3398 // Set the form data status.
3399 when (formDataInt) {
3400 SYSTEM_DEFAULT -> nestedScrollWebView.settings.saveFormData = defaultFormData
3401 ENABLED -> nestedScrollWebView.settings.saveFormData = true
3402 DISABLED -> nestedScrollWebView.settings.saveFormData = false
3406 // Set the EasyList status.
3407 when (easyListInt) {
3408 SYSTEM_DEFAULT -> nestedScrollWebView.easyListEnabled = defaultEasyList
3409 ENABLED -> nestedScrollWebView.easyListEnabled = true
3410 DISABLED -> nestedScrollWebView.easyListEnabled = false
3413 // Set the EasyPrivacy status.
3414 when (easyPrivacyInt) {
3415 SYSTEM_DEFAULT -> nestedScrollWebView.easyPrivacyEnabled = defaultEasyPrivacy
3416 ENABLED -> nestedScrollWebView.easyPrivacyEnabled = true
3417 DISABLED -> nestedScrollWebView.easyPrivacyEnabled = false
3420 // Set the Fanboy's Annoyance List status.
3421 when (fanboysAnnoyanceListInt) {
3422 SYSTEM_DEFAULT -> nestedScrollWebView.fanboysAnnoyanceListEnabled = defaultFanboysAnnoyanceList
3423 ENABLED -> nestedScrollWebView.fanboysAnnoyanceListEnabled = true
3424 DISABLED -> nestedScrollWebView.fanboysAnnoyanceListEnabled = false
3427 // Set the Fanboy's Social Blocking List status.
3428 when (fanboysSocialBlockingListInt) {
3429 SYSTEM_DEFAULT -> nestedScrollWebView.fanboysSocialBlockingListEnabled = defaultFanboysSocialBlockingList
3430 ENABLED -> nestedScrollWebView.fanboysSocialBlockingListEnabled = true
3431 DISABLED -> nestedScrollWebView.fanboysSocialBlockingListEnabled = false
3434 // Set the UltraList status.
3435 when (ultraListInt) {
3436 SYSTEM_DEFAULT -> nestedScrollWebView.ultraListEnabled = defaultUltraList
3437 ENABLED -> nestedScrollWebView.ultraListEnabled = true
3438 DISABLED -> nestedScrollWebView.ultraListEnabled = false
3441 // Set the UltraPrivacy status.
3442 when (ultraPrivacyInt) {
3443 SYSTEM_DEFAULT -> nestedScrollWebView.ultraPrivacyEnabled = defaultUltraPrivacy
3444 ENABLED -> nestedScrollWebView.ultraPrivacyEnabled = true
3445 DISABLED -> nestedScrollWebView.ultraPrivacyEnabled = false
3448 // Set the block all third-party requests status.
3449 when (blockAllThirdPartyRequestsInt) {
3450 SYSTEM_DEFAULT -> nestedScrollWebView.blockAllThirdPartyRequests = defaultBlockAllThirdPartyRequests
3451 ENABLED -> nestedScrollWebView.blockAllThirdPartyRequests = true
3452 DISABLED -> nestedScrollWebView.blockAllThirdPartyRequests = false
3455 // Set the user agent.
3456 if (userAgentName == getString(R.string.system_default_user_agent)) { // Use the system default user agent.
3457 // Set the user agent according to the system default.
3458 when (val defaultUserAgentArrayPosition = userAgentNamesArrayAdapter.getPosition(defaultUserAgentName)) {
3459 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.
3460 nestedScrollWebView.settings.userAgentString = defaultUserAgentName
3462 SETTINGS_WEBVIEW_DEFAULT_USER_AGENT -> // Set the user agent to `""`, which uses the default value.
3463 nestedScrollWebView.settings.userAgentString = ""
3465 SETTINGS_CUSTOM_USER_AGENT -> // Set the default custom user agent.
3466 nestedScrollWebView.settings.userAgentString = sharedPreferences.getString(getString(R.string.custom_user_agent_key), getString(R.string.custom_user_agent_default_value))
3468 else -> // Get the user agent string from the user agent data array
3469 nestedScrollWebView.settings.userAgentString = userAgentDataArray[defaultUserAgentArrayPosition]
3471 } else { // Set the user agent according to the stored name.
3472 // Set the user agent.
3473 when (val userAgentArrayPosition = userAgentNamesArrayAdapter.getPosition(userAgentName)) {
3474 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3475 UNRECOGNIZED_USER_AGENT ->
3476 nestedScrollWebView.settings.userAgentString = userAgentName
3478 // Set the user agent to `""`, which uses the default value.
3479 SETTINGS_WEBVIEW_DEFAULT_USER_AGENT ->
3480 nestedScrollWebView.settings.userAgentString = ""
3482 // Get the user agent string from the user agent data array.
3484 nestedScrollWebView.settings.userAgentString = userAgentDataArray[userAgentArrayPosition]
3488 // Apply the font size.
3489 try { // Try the specified font size to see if it is valid.
3490 if (fontSize == 0) { // Apply the default font size.
3491 // Set the font size from the value in the app settings.
3492 nestedScrollWebView.settings.textZoom = defaultFontSizeString.toInt()
3493 } else { // Apply the font size from domain settings.
3494 nestedScrollWebView.settings.textZoom = fontSize
3496 } catch (exception: Exception) { // The specified font size is invalid
3497 // Set the font size to be 100%
3498 nestedScrollWebView.settings.textZoom = 100
3501 // Set swipe to refresh.
3502 when (swipeToRefreshInt) {
3504 // Store the swipe to refresh status in the nested scroll WebView.
3505 nestedScrollWebView.swipeToRefresh = defaultSwipeToRefresh
3507 // Update the swipe refresh layout.
3508 if (defaultSwipeToRefresh) { // Swipe to refresh is enabled.
3509 // 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).
3510 if (currentWebView != null) {
3511 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
3512 swipeRefreshLayout.isEnabled = (currentWebView!!.scrollY == 0)
3514 } else { // Swipe to refresh is disabled.
3515 // Disable the swipe refresh layout.
3516 swipeRefreshLayout.isEnabled = false
3521 // Store the swipe to refresh status in the nested scroll WebView.
3522 nestedScrollWebView.swipeToRefresh = true
3524 // 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).
3525 if (currentWebView != null) {
3526 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
3527 swipeRefreshLayout.isEnabled = (currentWebView!!.scrollY == 0)
3532 // Store the swipe to refresh status in the nested scroll WebView.
3533 nestedScrollWebView.swipeToRefresh = false
3535 // Disable swipe to refresh.
3536 swipeRefreshLayout.isEnabled = false
3540 // Set the WebView theme if algorithmic darkening is supported.
3541 if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {
3542 // Set the WebView theme.
3543 when (webViewThemeInt) {
3544 SYSTEM_DEFAULT -> // Set the WebView theme.
3545 when (defaultWebViewTheme) {
3546 webViewThemeEntryValuesStringArray[1] -> // The light theme is selected. Turn off algorithmic darkening.
3547 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
3549 webViewThemeEntryValuesStringArray[2] -> // The dark theme is selected. Turn on algorithmic darkening.
3550 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
3552 else -> { // The system default theme is selected.
3553 // Get the current system theme status.
3554 val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
3556 // Set the algorithmic darkening according to the current system theme status.
3557 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, currentThemeStatus == Configuration.UI_MODE_NIGHT_YES)
3561 LIGHT_THEME -> // Turn off algorithmic darkening.
3562 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
3564 DARK_THEME -> // Turn on algorithmic darkening.
3565 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
3569 // Set the wide viewport status.
3570 when (wideViewportInt) {
3571 SYSTEM_DEFAULT -> nestedScrollWebView.settings.useWideViewPort = defaultWideViewport
3572 ENABLED -> nestedScrollWebView.settings.useWideViewPort = true
3573 DISABLED -> nestedScrollWebView.settings.useWideViewPort = false
3576 // Set the display webpage images status.
3577 when (displayWebpageImagesInt) {
3578 SYSTEM_DEFAULT -> nestedScrollWebView.settings.loadsImagesAutomatically = defaultDisplayWebpageImages
3579 ENABLED -> nestedScrollWebView.settings.loadsImagesAutomatically = true
3580 DISABLED -> nestedScrollWebView.settings.loadsImagesAutomatically = false
3583 // If there is a pinned SSL certificate, store it in the WebView.
3584 if (pinnedSslCertificate)
3585 nestedScrollWebView.setPinnedSslCertificate(pinnedSslIssuedToCName, pinnedSslIssuedToOName, pinnedSslIssuedToUName, pinnedSslIssuedByCName, pinnedSslIssuedByOName, pinnedSslIssuedByUName,
3586 pinnedSslStartDate, pinnedSslEndDate)
3588 // If there is a pinned IP address, store it in the WebView.
3589 if (pinnedIpAddresses)
3590 nestedScrollWebView.pinnedIpAddresses = pinnedHostIpAddresses
3592 // Set a background on the URL relative layout to indicate that custom domain settings are being used.
3593 urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.drawable.domain_settings_url_background)
3594 } else { // The new URL does not have custom domain settings. Load the defaults.
3595 // Store the values from the shared preferences.
3596 nestedScrollWebView.settings.javaScriptEnabled = defaultJavaScript
3597 nestedScrollWebView.acceptCookies = defaultCookies
3598 nestedScrollWebView.settings.domStorageEnabled = defaultDomStorage
3599 nestedScrollWebView.easyListEnabled = defaultEasyList
3600 nestedScrollWebView.easyPrivacyEnabled = defaultEasyPrivacy
3601 nestedScrollWebView.fanboysAnnoyanceListEnabled = defaultFanboysAnnoyanceList
3602 nestedScrollWebView.fanboysSocialBlockingListEnabled = defaultFanboysSocialBlockingList
3603 nestedScrollWebView.ultraListEnabled = defaultUltraList
3604 nestedScrollWebView.ultraPrivacyEnabled = defaultUltraPrivacy
3605 nestedScrollWebView.blockAllThirdPartyRequests = defaultBlockAllThirdPartyRequests
3607 // Apply the default cookie setting.
3608 cookieManager.setAcceptCookie(nestedScrollWebView.acceptCookies)
3610 // Apply the form data setting if the API < 26.
3611 if (Build.VERSION.SDK_INT < 26)
3612 @Suppress("DEPRECATION")
3613 nestedScrollWebView.settings.saveFormData = defaultFormData
3615 // Apply the default font size setting.
3617 // Try to set the font size from the value in the app settings.
3618 nestedScrollWebView.settings.textZoom = defaultFontSizeString.toInt()
3619 } catch (exception: Exception) {
3620 // If the app settings value is invalid, set the font size to 100%.
3621 nestedScrollWebView.settings.textZoom = 100
3624 // Store the swipe to refresh status in the nested scroll WebView.
3625 nestedScrollWebView.swipeToRefresh = defaultSwipeToRefresh
3627 // Update the swipe refresh layout.
3628 if (defaultSwipeToRefresh) { // Swipe to refresh is enabled.
3629 // 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).
3630 if (currentWebView != null) {
3631 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
3632 swipeRefreshLayout.isEnabled = currentWebView!!.scrollY == 0
3634 } else { // Swipe to refresh is disabled.
3635 // Disable the swipe refresh layout.
3636 swipeRefreshLayout.isEnabled = false
3639 // Reset the domain settings database ID.
3640 nestedScrollWebView.domainSettingsDatabaseId = -1
3642 // Set the user agent.
3643 when (val userAgentArrayPosition = userAgentNamesArrayAdapter.getPosition(defaultUserAgentName)) {
3644 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.
3645 nestedScrollWebView.settings.userAgentString = defaultUserAgentName
3647 SETTINGS_WEBVIEW_DEFAULT_USER_AGENT -> // Set the user agent to `""`, which uses the default value.
3648 nestedScrollWebView.settings.userAgentString = ""
3650 SETTINGS_CUSTOM_USER_AGENT -> // Set the default custom user agent.
3651 nestedScrollWebView.settings.userAgentString = sharedPreferences.getString(getString(R.string.custom_user_agent_key), getString(R.string.custom_user_agent_default_value))
3653 else -> // Get the user agent string from the user agent data array
3654 nestedScrollWebView.settings.userAgentString = userAgentDataArray[userAgentArrayPosition]
3657 // Set the WebView theme if algorithmic darkening is supported.
3658 if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {
3659 // Set the WebView theme.
3660 when (defaultWebViewTheme) {
3661 webViewThemeEntryValuesStringArray[1] -> // The light theme is selected. Turn off algorithmic darkening.
3662 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
3664 webViewThemeEntryValuesStringArray[2] -> // The dark theme is selected. Turn on algorithmic darkening.
3665 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
3667 else -> { // The system default theme is selected. Get the current system theme status.
3668 // Get the current theme status.
3669 val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
3671 // Set the algorithmic darkening according to the current system theme status.
3672 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, currentThemeStatus == Configuration.UI_MODE_NIGHT_YES)
3677 // Set the viewport.
3678 nestedScrollWebView.settings.useWideViewPort = defaultWideViewport
3680 // Set the loading of webpage images.
3681 nestedScrollWebView.settings.loadsImagesAutomatically = defaultDisplayWebpageImages
3683 // Set a transparent background on the URL relative layout.
3684 urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.color.transparent)
3687 // Update the privacy icons.
3688 updatePrivacyIcons(true)
3691 // Reload the website if returning from the Domains activity.
3693 nestedScrollWebView.reload()
3695 // Disable the wide viewport if the source is being viewed.
3696 if (url.startsWith("view-source:"))
3697 nestedScrollWebView.settings.useWideViewPort = false
3699 // 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.
3701 nestedScrollWebView.loadUrl(url)
3704 private fun applyProxy(reloadWebViews: Boolean) {
3705 // Set the proxy according to the mode.
3706 proxyHelper.setProxy(applicationContext, appBarLayout, proxyMode)
3708 // Reset the waiting for proxy tracker.
3709 waitingForProxy = false
3713 ProxyHelper.NONE -> {
3714 // Initialize a color background typed value.
3715 val colorBackgroundTypedValue = TypedValue()
3717 // Get the color background from the theme.
3718 theme.resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true)
3720 // Get the color background int from the typed value.
3721 val colorBackgroundInt = colorBackgroundTypedValue.data
3723 // Set the default app bar layout background.
3724 appBarLayout.setBackgroundColor(colorBackgroundInt)
3727 ProxyHelper.TOR -> {
3728 // Set the app bar background to indicate proxying is enabled.
3729 appBarLayout.setBackgroundResource(R.color.blue_background)
3731 // Check to see if Orbot is installed.
3733 // Get the package manager.
3734 val packageManager = packageManager
3736 // 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.
3737 packageManager.getPackageInfo("org.torproject.android", 0)
3739 // Check to see if the proxy is ready.
3740 if (orbotStatus != ProxyHelper.ORBOT_STATUS_ON) { // Orbot is not ready.
3741 // Set the waiting for proxy status.
3742 waitingForProxy = true
3744 // Show the waiting for proxy dialog if it isn't already displayed.
3745 if (supportFragmentManager.findFragmentByTag(getString(R.string.waiting_for_proxy_dialog)) == null) {
3746 // Get a handle for the waiting for proxy alert dialog.
3747 val waitingForProxyDialogFragment = WaitingForProxyDialog()
3749 // Try to show the dialog. Sometimes the window is not yet active if returning from Settings.
3751 // Show the waiting for proxy alert dialog.
3752 waitingForProxyDialogFragment.show(supportFragmentManager, getString(R.string.waiting_for_proxy_dialog))
3753 } catch (waitingForTorException: Exception) {
3754 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
3755 pendingDialogsArrayList.add(PendingDialogDataClass(waitingForProxyDialogFragment, getString(R.string.waiting_for_proxy_dialog)))
3759 } catch (exception: PackageManager.NameNotFoundException) { // Orbot is not installed.
3760 // Show the Orbot not installed dialog if it is not already displayed.
3761 if (supportFragmentManager.findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
3762 // Get a handle for the Orbot not installed alert dialog.
3763 val orbotNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode)
3765 // Try to show the dialog. Sometimes the window is not yet active if returning from Settings.
3767 // Display the Orbot not installed alert dialog.
3768 orbotNotInstalledDialogFragment.show(supportFragmentManager, getString(R.string.proxy_not_installed_dialog))
3769 } catch (orbotNotInstalledException: Exception) {
3770 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
3771 pendingDialogsArrayList.add(PendingDialogDataClass(orbotNotInstalledDialogFragment, getString(R.string.proxy_not_installed_dialog)))
3777 ProxyHelper.I2P -> {
3778 // Set the app bar background to indicate proxying is enabled.
3779 appBarLayout.setBackgroundResource(R.color.blue_background)
3781 // Check to see if I2P is installed.
3783 // 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.
3784 packageManager.getPackageInfo("net.i2p.android.router", 0)
3785 } catch (fdroidException: PackageManager.NameNotFoundException) { // The F-Droid flavor is not installed.
3787 // 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.
3788 packageManager.getPackageInfo("net.i2p.android", 0)
3789 } catch (googlePlayException: PackageManager.NameNotFoundException) { // The Google Play flavor is not installed.
3790 // Sow the I2P not installed dialog if it is not already displayed.
3791 if (supportFragmentManager.findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
3792 // Get a handle for the waiting for proxy alert dialog.
3793 val i2pNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode)
3795 // Try to show the dialog. Sometimes the window is not yet active if returning from Settings.
3797 // Display the I2P not installed alert dialog.
3798 i2pNotInstalledDialogFragment.show(supportFragmentManager, getString(R.string.proxy_not_installed_dialog))
3799 } catch (i2pNotInstalledException: Exception) {
3800 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
3801 pendingDialogsArrayList.add(PendingDialogDataClass(i2pNotInstalledDialogFragment, getString(R.string.proxy_not_installed_dialog)))
3808 ProxyHelper.CUSTOM ->
3809 // Set the app bar background to indicate proxying is enabled.
3810 appBarLayout.setBackgroundResource(R.color.blue_background)
3813 // Reload the WebViews if requested and not waiting for the proxy.
3814 if (reloadWebViews && !waitingForProxy) {
3815 // Reload the WebViews.
3816 for (i in 0 until webViewStateAdapter!!.itemCount) {
3817 // Get the WebView tab fragment.
3818 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
3820 // Get the fragment view.
3821 val fragmentView = webViewTabFragment.view
3823 // Only reload the WebViews if they exist.
3824 if (fragmentView != null) {
3825 // Get the nested scroll WebView from the tab fragment.
3826 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
3828 // Reload the WebView.
3829 nestedScrollWebView.reload()
3835 // The view parameter cannot be removed because it is called from the layout onClick.
3836 fun bookmarksBack(@Suppress("UNUSED_PARAMETER")view: View?) {
3837 if (currentBookmarksFolderId == HOME_FOLDER_ID) { // The home folder is displayed.
3838 // close the bookmarks drawer.
3839 drawerLayout.closeDrawer(GravityCompat.END)
3840 } else { // A subfolder is displayed.
3841 // Set the former parent folder as the current folder.
3842 currentBookmarksFolderId = bookmarksDatabaseHelper!!.getParentFolderId(currentBookmarksFolderId)
3844 // Load the new folder.
3845 loadBookmarksFolder()
3849 private fun calculateSettingsInt(settingCurrentlyEnabled: Boolean, settingEnabledByDefault: Boolean): Int {
3850 return if (settingCurrentlyEnabled == settingEnabledByDefault) // The current system default is used.
3852 else if (settingCurrentlyEnabled) // The setting is enabled, which is different from the system default.
3854 else // The setting is disabled, which is different from the system default.
3858 private fun clearAndExit() {
3859 // Close the bookmarks cursor if it exists.
3860 bookmarksCursor?.close()
3862 // Close the databases helpers if they exist.
3863 bookmarksDatabaseHelper?.close()
3864 domainsDatabaseHelper?.close()
3866 // Get the status of the clear everything preference.
3867 val clearEverything = sharedPreferences.getBoolean(getString(R.string.clear_everything_key), true)
3869 // Get a handle for the runtime.
3870 val runtime = Runtime.getRuntime()
3872 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
3873 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
3874 val privateDataDirectoryString = applicationInfo.dataDir
3877 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_cookies_key), true)) {
3878 // Ass the cookie manager to delete all the cookies.
3879 cookieManager.removeAllCookies(null)
3881 // Ask the cookie manager to flush the cookie database.
3882 cookieManager.flush()
3884 // Manually delete the cookies database, as the cookie manager sometimes will not flush its changes to disk before system exit is run.
3886 // Two commands must be used because `Runtime.exec()` does not like `*`.
3887 val deleteCookiesProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/Cookies")
3888 val deleteCookiesJournalProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/Cookies-journal")
3890 // Wait until the processes have finished.
3891 deleteCookiesProcess.waitFor()
3892 deleteCookiesJournalProcess.waitFor()
3893 } catch (exception: Exception) {
3894 // Do nothing if an error is thrown.
3898 // Clear DOM storage.
3899 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_dom_storage_key), true)) {
3900 // Ask web storage to clear the DOM storage.
3901 WebStorage.getInstance().deleteAllData()
3903 // Manually delete the DOM storage files and directories, as web storage sometimes will not flush its changes to disk before system exit is run.
3905 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
3906 val deleteLocalStorageProcess = runtime.exec(arrayOf("rm", "-rf", "$privateDataDirectoryString/app_webview/Local Storage/"))
3908 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
3909 val deleteIndexProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview/IndexedDB")
3910 val deleteQuotaManagerProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/QuotaManager")
3911 val deleteQuotaManagerJournalProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/QuotaManager-journal")
3912 val deleteDatabaseProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview/databases")
3914 // Wait until the processes have finished.
3915 deleteLocalStorageProcess.waitFor()
3916 deleteIndexProcess.waitFor()
3917 deleteQuotaManagerProcess.waitFor()
3918 deleteQuotaManagerJournalProcess.waitFor()
3919 deleteDatabaseProcess.waitFor()
3920 } catch (exception: Exception) {
3921 // Do nothing if an error is thrown.
3925 // Clear form data if the API < 26.
3926 if (Build.VERSION.SDK_INT < 26 && (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_form_data_key), true))) {
3927 // Ask the WebView database to clear the form data.
3928 @Suppress("DEPRECATION")
3929 WebViewDatabase.getInstance(this).clearFormData()
3931 // Manually delete the form data database, as the WebView database sometimes will not flush its changes to disk before system exit is run.
3933 // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
3934 val deleteWebDataProcess = runtime.exec(arrayOf("rm", "-f", "$privateDataDirectoryString/app_webview/Web Data"))
3935 val deleteWebDataJournalProcess = runtime.exec(arrayOf("rm", "-f", "$privateDataDirectoryString/app_webview/Web Data-journal"))
3937 // Wait until the processes have finished.
3938 deleteWebDataProcess.waitFor()
3939 deleteWebDataJournalProcess.waitFor()
3940 } catch (exception: Exception) {
3941 // Do nothing if an error is thrown.
3945 // Clear the logcat.
3946 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_logcat_key), true)) {
3948 // Clear the logcat. `-c` clears the logcat. `-b all` clears all the buffers (instead of just crash, main, and system).
3949 val process = Runtime.getRuntime().exec("logcat -b all -c")
3951 // Wait for the process to finish.
3953 } catch (exception: IOException) {
3955 } catch (exception: InterruptedException) {
3961 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_cache_key), true)) {
3962 // Clear the cache from each WebView.
3963 for (i in 0 until webViewStateAdapter!!.itemCount) {
3964 // Get the WebView tab fragment.
3965 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
3967 // Get the WebView fragment view.
3968 val webViewFragmentView = webViewTabFragment.view
3970 // Only clear the cache if the WebView exists.
3971 if (webViewFragmentView != null) {
3972 // Get the nested scroll WebView from the tab fragment.
3973 val nestedScrollWebView = webViewFragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
3975 // Clear the cache for this WebView.
3976 nestedScrollWebView.clearCache(true)
3980 // Manually delete the cache directories.
3982 // Delete the main cache directory.
3983 val deleteCacheProcess = runtime.exec("rm -rf $privateDataDirectoryString/cache")
3985 // Delete the secondary `Service Worker` cache directory.
3986 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
3987 val deleteServiceWorkerProcess = runtime.exec(arrayOf("rm", "-rf", "$privateDataDirectoryString/app_webview/Default/Service Worker/"))
3989 // Wait until the processes have finished.
3990 deleteCacheProcess.waitFor()
3991 deleteServiceWorkerProcess.waitFor()
3992 } catch (exception: Exception) {
3993 // Do nothing if an error is thrown.
3997 // Wipe out each WebView.
3998 for (i in 0 until webViewStateAdapter!!.itemCount) {
3999 // Get the WebView tab fragment.
4000 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
4002 // Get the WebView frame layout.
4003 val webViewFrameLayout = webViewTabFragment.view as FrameLayout?
4005 // Only wipe out the WebView if it exists.
4006 if (webViewFrameLayout != null) {
4007 // Get the nested scroll WebView from the tab fragment.
4008 val nestedScrollWebView = webViewFrameLayout.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
4010 // Clear SSL certificate preferences for this WebView.
4011 nestedScrollWebView.clearSslPreferences()
4013 // Clear the back/forward history for this WebView.
4014 nestedScrollWebView.clearHistory()
4016 // Remove all the views from the frame layout.
4017 webViewFrameLayout.removeAllViews()
4019 // Destroy the internal state of the WebView.
4020 nestedScrollWebView.destroy()
4024 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
4025 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
4026 if (clearEverything) {
4028 // Delete the folder.
4029 val deleteAppWebviewProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview")
4031 // Wait until the process has finished.
4032 deleteAppWebviewProcess.waitFor()
4033 } catch (exception: Exception) {
4034 // Do nothing if an error is thrown.
4038 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
4039 finishAndRemoveTask()
4041 // Remove the terminated program from RAM. The status code is `0`.
4045 // The view parameter cannot be removed because it is called from the layout onClick.
4046 fun closeFindOnPage(@Suppress("UNUSED_PARAMETER")view: View?) {
4047 // Delete the contents of the find on page edit text.
4048 findOnPageEditText.text = null
4050 // Clear the highlighted phrases if the WebView is not null.
4051 currentWebView?.clearMatches()
4053 // Hide the find on page linear layout.
4054 findOnPageLinearLayout.visibility = View.GONE
4056 // Show the toolbar.
4057 toolbar.visibility = View.VISIBLE
4059 // Get a handle for the input method manager.
4060 val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
4062 // Hide the keyboard.
4063 inputMethodManager.hideSoftInputFromWindow(toolbar.windowToken, 0)
4066 // The view parameter cannot be removed because it is called from the layout onClick.
4067 fun closeTab(@Suppress("UNUSED_PARAMETER")view: View?) {
4068 // Run the command according to the number of tabs.
4069 if (tabLayout.tabCount > 1) { // There is more than one tab open.
4070 // Get the current tab number.
4071 val currentTabNumber = tabLayout.selectedTabPosition
4073 // Delete the current tab.
4074 tabLayout.removeTabAt(currentTabNumber)
4076 // 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,
4077 // meaning that the current WebView must be reset. Otherwise it will happen automatically as the selected tab number changes.
4078 if (webViewStateAdapter!!.deletePage(currentTabNumber, webViewViewPager2))
4079 setCurrentWebView(currentTabNumber)
4080 } else { // There is only one tab open.
4085 override fun createBookmark(dialogFragment: DialogFragment, favoriteIconBitmap: Bitmap) {
4087 val dialog = dialogFragment.dialog!!
4089 // Get the views from the dialog fragment.
4090 val createBookmarkNameEditText = dialog.findViewById<EditText>(R.id.create_bookmark_name_edittext)
4091 val createBookmarkUrlEditText = dialog.findViewById<EditText>(R.id.create_bookmark_url_edittext)
4093 // Extract the strings from the edit texts.
4094 val bookmarkNameString = createBookmarkNameEditText.text.toString()
4095 val bookmarkUrlString = createBookmarkUrlEditText.text.toString()
4097 // Create a favorite icon byte array output stream.
4098 val favoriteIconByteArrayOutputStream = ByteArrayOutputStream()
4100 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
4101 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream)
4103 // Convert the favorite icon byte array stream to a byte array.
4104 val favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray()
4106 // Display the new bookmark below the current items in the (0 indexed) list.
4107 val newBookmarkDisplayOrder = bookmarksListView.count
4109 // Create the bookmark.
4110 bookmarksDatabaseHelper!!.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolderId, newBookmarkDisplayOrder, favoriteIconByteArray)
4112 // Update the bookmarks cursor with the current contents of this folder.
4113 bookmarksCursor = bookmarksDatabaseHelper!!.getBookmarksByDisplayOrder(currentBookmarksFolderId)
4115 // Update the list view.
4116 bookmarksCursorAdapter.changeCursor(bookmarksCursor)
4118 // Scroll to the new bookmark.
4119 bookmarksListView.setSelection(newBookmarkDisplayOrder)
4122 override fun createBookmarkFolder(dialogFragment: DialogFragment, favoriteIconBitmap: Bitmap) {
4124 val dialog = dialogFragment.dialog!!
4126 // Get handles for the views in the dialog fragment.
4127 val folderNameEditText = dialog.findViewById<EditText>(R.id.folder_name_edittext)
4128 val defaultIconRadioButton = dialog.findViewById<RadioButton>(R.id.default_icon_radiobutton)
4129 val defaultIconImageView = dialog.findViewById<ImageView>(R.id.default_icon_imageview)
4131 // Get new folder name string.
4132 val folderNameString = folderNameEditText.text.toString()
4134 // Set the folder icon bitmap according to the dialog.
4135 val folderIconBitmap: Bitmap = if (defaultIconRadioButton.isChecked) { // Use the default folder icon.
4136 // Get the default folder icon drawable.
4137 val folderIconDrawable = defaultIconImageView.drawable
4139 // Convert the folder icon drawable to a bitmap drawable.
4140 val folderIconBitmapDrawable = folderIconDrawable as BitmapDrawable
4142 // Convert the folder icon bitmap drawable to a bitmap.
4143 folderIconBitmapDrawable.bitmap
4144 } else { // Use the WebView favorite icon.
4145 // Copy the favorite icon bitmap to the folder icon bitmap.
4149 // Create a folder icon byte array output stream.
4150 val folderIconByteArrayOutputStream = ByteArrayOutputStream()
4152 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
4153 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream)
4155 // Convert the folder icon byte array stream to a byte array.
4156 val folderIconByteArray = folderIconByteArrayOutputStream.toByteArray()
4158 // Move all the bookmarks down one in the display order.
4159 for (i in 0 until bookmarksListView.count) {
4160 // Get the bookmark database id.
4161 val databaseId = bookmarksListView.getItemIdAtPosition(i).toInt()
4163 // Move the bookmark down one slot.
4164 bookmarksDatabaseHelper!!.updateDisplayOrder(databaseId, displayOrder = i + 1)
4167 // Create the folder, which will be placed at the top of the list view.
4168 bookmarksDatabaseHelper!!.createFolder(folderNameString, currentBookmarksFolderId, displayOrder = 0, folderIconByteArray)
4170 // Update the bookmarks cursor with the current contents of this folder.
4171 bookmarksCursor = bookmarksDatabaseHelper!!.getBookmarksByDisplayOrder(currentBookmarksFolderId)
4173 // Update the list view.
4174 bookmarksCursorAdapter.changeCursor(bookmarksCursor)
4176 // Scroll to the new folder.
4177 bookmarksListView.setSelection(0)
4180 private fun downloadUrlWithExternalApp(url: String) {
4181 // Create a download intent. Not specifying the action type will display the maximum number of options.
4182 val downloadIntent = Intent()
4184 // Set the URI and the mime type.
4185 downloadIntent.setDataAndType(Uri.parse(url), "text/html")
4187 // Flag the intent to open in a new task.
4188 downloadIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
4190 // Show the chooser.
4191 startActivity(Intent.createChooser(downloadIntent, getString(R.string.download_with_external_app)))
4194 private fun exitFullScreenVideo() {
4195 // Re-enable the screen timeout.
4196 fullScreenVideoFrameLayout.keepScreenOn = false
4198 // Unset the full screen video flag.
4199 displayingFullScreenVideo = false
4201 // Remove all the views from the full screen video frame layout.
4202 fullScreenVideoFrameLayout.removeAllViews()
4204 // Hide the full screen video frame layout.
4205 fullScreenVideoFrameLayout.visibility = View.GONE
4207 // Enable the sliding drawers.
4208 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED)
4210 // Show the coordinator layout.
4211 coordinatorLayout.visibility = View.VISIBLE
4213 // Apply the appropriate full screen mode flags.
4214 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
4215 // Hide the app bar if specified.
4217 // Hide the tab linear layout.
4218 tabsLinearLayout.visibility = View.GONE
4220 // Hide the app bar.
4224 /* Hide the system bars.
4225 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4226 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4227 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4228 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4231 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4232 @Suppress("DEPRECATION")
4233 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
4234 } else { // Switch to normal viewing mode.
4235 // Remove the `SYSTEM_UI` flags from the root frame layout. The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4236 @Suppress("DEPRECATION")
4237 rootFrameLayout.systemUiVisibility = 0
4241 // The view parameter cannot be removed because it is called from the layout onClick.
4242 fun findNextOnPage(@Suppress("UNUSED_PARAMETER")view: View?) {
4243 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
4244 currentWebView!!.findNext(true)
4247 // The view parameter cannot be removed because it is called from the layout onClick.
4248 fun findPreviousOnPage(@Suppress("UNUSED_PARAMETER")view: View?) {
4249 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
4250 currentWebView!!.findNext(false)
4253 override fun finishedPopulatingFilterLists(combinedFilterLists: ArrayList<ArrayList<List<Array<String>>>>) {
4254 // Store the filter lists.
4255 easyList = combinedFilterLists[0]
4256 easyPrivacy = combinedFilterLists[1]
4257 fanboysAnnoyanceList = combinedFilterLists[2]
4258 fanboysSocialList = combinedFilterLists[3]
4259 ultraList = combinedFilterLists[4]
4260 ultraPrivacy = combinedFilterLists[5]
4262 // Check to see if the activity has been restarted with a saved state.
4263 if ((savedStateArrayList == null) || (savedStateArrayList!!.size == 0)) { // The activity has not been restarted or it was restarted on start to change the theme.
4264 // Add the first tab.
4265 addNewPage(urlString = "", adjacent = false, moveToTab = false)
4266 } else { // The activity has been restarted with a saved state.
4267 // Restore each tab.
4268 for (i in savedStateArrayList!!.indices) {
4270 tabLayout.addTab(tabLayout.newTab())
4273 val newTab = tabLayout.getTabAt(i)!!
4275 // Set a custom view on the new tab.
4276 newTab.setCustomView(R.layout.tab_custom_view)
4278 // Add the new page.
4279 webViewStateAdapter!!.restorePage(savedStateArrayList!![i], savedNestedScrollWebViewStateArrayList!![i])
4282 // Reset the saved state variables.
4283 savedStateArrayList = null
4284 savedNestedScrollWebViewStateArrayList = null
4286 // Get the intent that started the app.
4289 // Reset the intent. This prevents a duplicate tab from being created on restart.
4292 // Get the information from the intent.
4293 val intentAction = intent.action
4294 val intentUriData = intent.data
4295 val intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT)
4297 // Determine if this is a web search.
4298 val isWebSearch = (intentAction != null) && (intentAction == Intent.ACTION_WEB_SEARCH)
4300 // 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.
4301 if ((intentUriData != null) || (intentStringExtra != null) || isWebSearch) { // A new tab is being loaded.
4302 // Get the URL string.
4303 val urlString = if (isWebSearch) { // The intent is a web search.
4304 // Sanitize the search input.
4305 val encodedSearchString: String = try {
4306 URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8")
4307 } catch (exception: UnsupportedEncodingException) {
4311 // Add the base search URL.
4312 searchURL + encodedSearchString
4313 } else { // The intent contains a URL formatted as a URI or a URL in the string extra.
4314 // Get the URL string.
4315 intentUriData?.toString() ?: intentStringExtra!!
4318 // Add a new tab if specified in the preferences.
4319 if (sharedPreferences.getBoolean(getString(R.string.open_intents_in_new_tab_key), true)) { // Load the URL in a new tab.
4320 // Set the loading new intent flag.
4321 loadingNewIntent = true
4324 addNewPage(urlString, adjacent = false, moveToTab = true)
4325 } else { // Load the URL in the current tab.
4327 loadUrl(currentWebView!!, urlString)
4329 } else { // A new tab is not being loaded.
4330 // Restore the selected tab position.
4331 if (savedTabPosition == 0) { // The first tab is selected.
4332 // Set the first page as the current WebView.
4333 setCurrentWebView(0)
4334 } else { // The first tab is not selected.
4335 // Select the tab when the layout has finished populating.
4337 // Get a handle for the tab.
4338 val tab = tabLayout.getTabAt(savedTabPosition)!!
4348 // Remove the warning that `OnTouchListener()` needs to override `performClick()`, as the only purpose of setting the `OnTouchListener()` is to make it do nothing.
4349 @SuppressLint("ClickableViewAccessibility")
4350 private fun initializeApp() {
4351 // Get a handle for the input method.
4352 val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
4354 // Initialize the color spans for highlighting the URLs.
4355 initialGrayColorSpan = ForegroundColorSpan(getColor(R.color.gray_500))
4356 finalGrayColorSpan = ForegroundColorSpan(getColor(R.color.gray_500))
4357 redColorSpan = ForegroundColorSpan(getColor(R.color.red_text))
4359 // Remove the formatting from the URL edit text when the user is editing the text.
4360 urlEditText.onFocusChangeListener = View.OnFocusChangeListener { _: View?, hasFocus: Boolean ->
4361 if (hasFocus) { // The user is editing the URL text box.
4362 // Remove the syntax highlighting.
4363 urlEditText.text.removeSpan(redColorSpan)
4364 urlEditText.text.removeSpan(initialGrayColorSpan)
4365 urlEditText.text.removeSpan(finalGrayColorSpan)
4366 } else { // The user has stopped editing the URL text box.
4367 // Move to the beginning of the string.
4368 urlEditText.setSelection(0)
4370 // Reapply the syntax highlighting.
4371 UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
4375 // Set the go button on the keyboard to load the URL in url text box.
4376 urlEditText.setOnKeyListener { _: View?, keyCode: Int, keyEvent: KeyEvent ->
4377 // If the event is a key-down event on the `enter` button, load the URL.
4378 if ((keyEvent.action == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The enter key was pressed.
4380 loadUrlFromTextBox()
4382 // Consume the event.
4383 return@setOnKeyListener true
4384 } else { // Some other key was pressed.
4385 // Do not consume the event.
4386 return@setOnKeyListener false
4390 // Create an Orbot status broadcast receiver.
4391 orbotStatusBroadcastReceiver = object : BroadcastReceiver() {
4392 override fun onReceive(context: Context, intent: Intent) {
4393 // Get the content of the status message.
4394 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS")!!
4396 // If Privacy Browser is waiting on the proxy, load the website now that Orbot is connected.
4397 if ((orbotStatus == ProxyHelper.ORBOT_STATUS_ON) && waitingForProxy) {
4398 // Reset the waiting for proxy status.
4399 waitingForProxy = false
4401 // Get a list of the current fragments.
4402 val fragmentList = supportFragmentManager.fragments
4404 // Check each fragment to see if it is a waiting for proxy dialog. Sometimes more than one is displayed.
4405 for (i in fragmentList.indices) {
4406 // Get the fragment tag.
4407 val fragmentTag = fragmentList[i].tag
4409 // Check to see if it is the waiting for proxy dialog.
4410 if (fragmentTag != null && fragmentTag == getString(R.string.waiting_for_proxy_dialog)) {
4411 // Dismiss the waiting for proxy dialog.
4412 (fragmentList[i] as DialogFragment).dismiss()
4416 // Reload existing URLs and load any URLs that are waiting for the proxy.
4417 for (i in 0 until webViewStateAdapter!!.itemCount) {
4418 // Get the WebView tab fragment.
4419 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
4421 // Get the fragment view.
4422 val fragmentView = webViewTabFragment.view
4424 // Only process the WebViews if they exist.
4425 if (fragmentView != null) {
4426 // Get the nested scroll WebView from the tab fragment.
4427 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
4429 // Get the waiting for proxy URL string.
4430 val waitingForProxyUrlString = nestedScrollWebView.waitingForProxyUrlString
4432 // Load the pending URL if it exists.
4433 if (waitingForProxyUrlString.isNotEmpty()) { // A URL is waiting to be loaded.
4435 loadUrl(nestedScrollWebView, waitingForProxyUrlString)
4437 // Reset the waiting for proxy URL string.
4438 nestedScrollWebView.waitingForProxyUrlString = ""
4439 } else { // No URL is waiting to be loaded.
4440 // Reload the existing URL.
4441 nestedScrollWebView.reload()
4449 // Register the Orbot status broadcast receiver. `ContextCompat` must be used until the minimum API >= 34.
4450 ContextCompat.registerReceiver(this, orbotStatusBroadcastReceiver, IntentFilter("org.torproject.android.intent.action.STATUS"), ContextCompat.RECEIVER_EXPORTED)
4452 // Get handles for views that need to be modified.
4453 val bookmarksHeaderLinearLayout = findViewById<LinearLayout>(R.id.bookmarks_header_linearlayout)
4454 val launchBookmarksActivityFab = findViewById<FloatingActionButton>(R.id.launch_bookmarks_activity_fab)
4455 val createBookmarkFolderFab = findViewById<FloatingActionButton>(R.id.create_bookmark_folder_fab)
4456 val createBookmarkFab = findViewById<FloatingActionButton>(R.id.create_bookmark_fab)
4458 // Handle tab selections.
4459 tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
4460 override fun onTabSelected(tab: TabLayout.Tab) {
4461 // Close the find on page bar if it is open.
4462 closeFindOnPage(null)
4464 // 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.
4465 webViewViewPager2.post {
4466 // Select the same page in the view pager.
4467 webViewViewPager2.currentItem = tab.position
4469 // 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>
4471 setCurrentWebView(tab.position)
4476 override fun onTabUnselected(tab: TabLayout.Tab) {}
4478 override fun onTabReselected(tab: TabLayout.Tab) {
4479 // Only display the view SSL certificate dialog if the current WebView is not null.
4480 // This can happen if the tab is programmatically reselected while the app is being restarted and is not yet populated.
4481 if (currentWebView != null) {
4482 // Instantiate the View SSL Certificate dialog.
4483 val viewSslCertificateDialogFragment: DialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView!!.webViewFragmentId, currentWebView!!.getFavoriteIcon())
4485 // Display the View SSL Certificate dialog.
4486 viewSslCertificateDialogFragment.show(supportFragmentManager, getString(R.string.view_ssl_certificate))
4491 // Set a touch listener on the bookmarks header linear layout so that touches don't pass through to the button underneath.
4492 bookmarksHeaderLinearLayout.setOnTouchListener { _: View?, _: MotionEvent? -> true }
4494 // Set the launch bookmarks activity floating action button to launch the bookmarks activity.
4495 launchBookmarksActivityFab.setOnClickListener {
4496 // Get a copy of the favorite icon bitmap.
4497 val currentFavoriteIconBitmap = currentWebView!!.getFavoriteIcon()
4499 // Create a favorite icon byte array output stream.
4500 val currentFavoriteIconByteArrayOutputStream = ByteArrayOutputStream()
4502 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
4503 currentFavoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, currentFavoriteIconByteArrayOutputStream)
4505 // Convert the favorite icon byte array stream to a byte array.
4506 val currentFavoriteIconByteArray = currentFavoriteIconByteArrayOutputStream.toByteArray()
4508 // Create an intent to launch the bookmarks activity.
4509 val bookmarksIntent = Intent(applicationContext, BookmarksActivity::class.java)
4511 // Add the extra information to the intent.
4512 bookmarksIntent.putExtra(CURRENT_FOLDER_ID, currentBookmarksFolderId)
4513 bookmarksIntent.putExtra(CURRENT_TITLE, currentWebView!!.title)
4514 bookmarksIntent.putExtra(CURRENT_URL, currentWebView!!.url)
4515 bookmarksIntent.putExtra(CURRENT_FAVORITE_ICON_BYTE_ARRAY, currentFavoriteIconByteArray)
4518 startActivity(bookmarksIntent)
4521 // Set the create new bookmark folder floating action button to display an alert dialog.
4522 createBookmarkFolderFab.setOnClickListener {
4523 // Create a create bookmark folder dialog.
4524 val createBookmarkFolderDialog: DialogFragment = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView!!.getFavoriteIcon())
4526 // Show the create bookmark folder dialog.
4527 createBookmarkFolderDialog.show(supportFragmentManager, getString(R.string.create_folder))
4530 // Set the create new bookmark floating action button to display an alert dialog.
4531 createBookmarkFab.setOnClickListener {
4532 // Instantiate the create bookmark dialog.
4533 val createBookmarkDialog: DialogFragment = CreateBookmarkDialog.createBookmark(currentWebView!!.url!!, currentWebView!!.title!!, currentWebView!!.getFavoriteIcon())
4535 // Display the create bookmark dialog.
4536 createBookmarkDialog.show(supportFragmentManager, getString(R.string.create_bookmark))
4539 // Search for the string on the page whenever a character changes in the find on page edit text.
4540 findOnPageEditText.addTextChangedListener(object : TextWatcher {
4541 override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
4543 override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
4545 override fun afterTextChanged(s: Editable) {
4546 // 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.
4547 currentWebView?.findAllAsync(findOnPageEditText.text.toString())
4551 // Set the `check mark` button for the find on page edit text keyboard to close the soft keyboard.
4552 findOnPageEditText.setOnKeyListener { _: View?, keyCode: Int, keyEvent: KeyEvent ->
4553 if ((keyEvent.action == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
4554 // Hide the soft keyboard.
4555 inputMethodManager.hideSoftInputFromWindow(currentWebView!!.windowToken, 0)
4557 // Consume the event.
4558 return@setOnKeyListener true
4559 } else { // A different key was pressed.
4560 // Do not consume the event.
4561 return@setOnKeyListener false
4565 // Implement swipe to refresh.
4566 swipeRefreshLayout.setOnRefreshListener {
4567 // Reload the website.
4568 currentWebView!!.reload()
4571 // Store the default progress view offsets.
4572 defaultProgressViewStartOffset = swipeRefreshLayout.progressViewStartOffset
4573 defaultProgressViewEndOffset = swipeRefreshLayout.progressViewEndOffset
4575 // Set the refresh color scheme according to the theme.
4576 swipeRefreshLayout.setColorSchemeResources(R.color.blue_text)
4578 // Initialize a color background typed value.
4579 val colorBackgroundTypedValue = TypedValue()
4581 // Get the color background from the theme.
4582 theme.resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true)
4584 // Get the color background int from the typed value.
4585 val colorBackgroundInt = colorBackgroundTypedValue.data
4587 // Set the swipe refresh background color.
4588 swipeRefreshLayout.setProgressBackgroundColorSchemeColor(colorBackgroundInt)
4590 // Set the drawer titles, which identify the drawer layouts in accessibility mode.
4591 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer))
4592 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks))
4594 // Load the bookmarks folder.
4595 loadBookmarksFolder()
4597 // Handle clicks on bookmarks.
4598 bookmarksListView.onItemClickListener = AdapterView.OnItemClickListener { _: AdapterView<*>?, _: View?, _: Int, id: Long ->
4599 // Convert the id from long to int to match the format of the bookmarks database.
4600 val databaseId = id.toInt()
4602 // Get the bookmark cursor for this ID.
4603 val bookmarkCursor = bookmarksDatabaseHelper!!.getBookmark(databaseId)
4605 // Move the bookmark cursor to the first row.
4606 bookmarkCursor.moveToFirst()
4608 // Act upon the bookmark according to the type.
4609 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndexOrThrow(IS_FOLDER)) == 1) { // The selected bookmark is a folder.
4610 // Store the folder ID.
4611 currentBookmarksFolderId = bookmarkCursor.getLong(bookmarkCursor.getColumnIndexOrThrow(FOLDER_ID))
4613 // Load the new folder.
4614 loadBookmarksFolder()
4615 } else { // The selected bookmark is not a folder.
4616 // Load the bookmark URL.
4617 loadUrl(currentWebView!!, bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BOOKMARK_URL)))
4619 // Close the bookmarks drawer if it is not pinned.
4620 if (!bookmarksDrawerPinned)
4621 drawerLayout.closeDrawer(GravityCompat.END)
4624 // Close the cursor.
4625 bookmarkCursor.close()
4628 // Handle long-presses on bookmarks.
4629 bookmarksListView.onItemLongClickListener = AdapterView.OnItemLongClickListener { _: AdapterView<*>?, _: View?, _: Int, id: Long ->
4630 // Convert the database ID from `long` to `int`.
4631 val databaseId = id.toInt()
4633 // Run the commands associated with the type.
4634 if (bookmarksDatabaseHelper!!.isFolder(databaseId)) { // The bookmark is a folder.
4635 // Get the folder ID.
4636 val folderId = bookmarksDatabaseHelper!!.getFolderId(databaseId)
4638 // Get a cursor of all the bookmarks in the folder.
4639 val bookmarksCursor = bookmarksDatabaseHelper!!.getFolderBookmarks(folderId)
4641 // Move to the first entry in the cursor.
4642 bookmarksCursor.moveToFirst()
4644 // Open each bookmark
4645 for (i in 0 until bookmarksCursor.count) {
4646 // Load the bookmark in a new tab, moving to the tab for the first bookmark if the drawer is not pinned.
4647 addNewPage(bookmarksCursor.getString(bookmarksCursor.getColumnIndexOrThrow(BOOKMARK_URL)), adjacent = false, moveToTab = !bookmarksDrawerPinned && (i == 0))
4649 // Move to the next bookmark.
4650 bookmarksCursor.moveToNext()
4653 // Close the cursor.
4654 bookmarksCursor.close()
4655 } else { // The bookmark is not a folder.
4656 // Get the bookmark cursor for this ID.
4657 val bookmarkCursor = bookmarksDatabaseHelper!!.getBookmark(databaseId)
4659 // Move the bookmark cursor to the first row.
4660 bookmarkCursor.moveToFirst()
4662 // Load the bookmark in a new tab and move to the tab if the drawer is not pinned.
4663 addNewPage(bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BOOKMARK_URL)), adjacent = true, moveToTab = !bookmarksDrawerPinned)
4665 // Close the cursor.
4666 bookmarkCursor.close()
4669 // Close the bookmarks drawer if it is not pinned.
4670 if (!bookmarksDrawerPinned)
4671 drawerLayout.closeDrawer(GravityCompat.END)
4673 // Consume the event.
4677 // The drawer listener is used to update the navigation menu.
4678 drawerLayout.addDrawerListener(object : DrawerLayout.DrawerListener {
4679 override fun onDrawerSlide(drawerView: View, slideOffset: Float) {}
4681 override fun onDrawerOpened(drawerView: View) {}
4683 override fun onDrawerClosed(drawerView: View) {}
4685 override fun onDrawerStateChanged(newState: Int) {
4686 if (newState == DrawerLayout.STATE_SETTLING || newState == DrawerLayout.STATE_DRAGGING) { // A drawer is opening or closing.
4687 // Update the navigation menu items if the WebView is not null.
4688 if (currentWebView != null) {
4689 // Set the enabled status of the menu items.
4690 navigationBackMenuItem.isEnabled = currentWebView!!.canGoBack()
4691 navigationForwardMenuItem.isEnabled = currentWebView!!.canGoForward()
4692 navigationScrollToBottomMenuItem.isEnabled = (currentWebView!!.canScrollVertically(-1) || currentWebView!!.canScrollVertically(1))
4693 navigationHistoryMenuItem.isEnabled = currentWebView!!.canGoBack() || currentWebView!!.canGoForward()
4695 // Update the scroll menu item.
4696 if (currentWebView!!.scrollY == 0) { // The WebView is scrolled to the top.
4698 navigationScrollToBottomMenuItem.title = getString(R.string.scroll_to_bottom)
4701 navigationScrollToBottomMenuItem.icon = AppCompatResources.getDrawable(applicationContext, R.drawable.move_down_enabled)
4702 } else { // The WebView is not scrolled to the top.
4704 navigationScrollToBottomMenuItem.title = getString(R.string.scroll_to_top)
4707 navigationScrollToBottomMenuItem.icon = AppCompatResources.getDrawable(applicationContext, R.drawable.move_up_enabled)
4710 // Display the number of blocked requests.
4711 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + currentWebView!!.getRequestsCount(BLOCKED_REQUESTS)
4713 // Hide the keyboard (if displayed).
4714 inputMethodManager.hideSoftInputFromWindow(currentWebView!!.windowToken, 0)
4717 // 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.
4718 urlEditText.clearFocus()
4720 // 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.
4721 // Clearing the focus from the WebView removes any text selection markers and context menus, which otherwise draw above the open drawers.
4722 currentWebView?.clearFocus()
4724 if (bottomAppBar && navigationDrawerFirstView) {
4725 // Reset the navigation drawer first view flag.
4726 navigationDrawerFirstView = false
4728 // Get a handle for the navigation recycler view.
4729 val navigationRecyclerView = navigationView.getChildAt(0) as RecyclerView
4731 // Get the navigation linear layout manager.
4732 val navigationLinearLayoutManager = navigationRecyclerView.layoutManager as LinearLayoutManager
4734 // Scroll the navigation drawer to the bottom.
4735 navigationLinearLayoutManager.scrollToPositionWithOffset(13, 0)
4741 // Inflate a bare WebView to get the default user agent. It is not used to render content on the screen.
4742 @SuppressLint("InflateParams") val webViewLayout = layoutInflater.inflate(R.layout.bare_webview, null, false)
4744 // Get a handle for the WebView.
4745 val bareWebView = webViewLayout.findViewById<WebView>(R.id.bare_webview)
4747 // Store the default user agent.
4748 webViewDefaultUserAgent = bareWebView.settings.userAgentString
4750 // Destroy the bare WebView.
4751 bareWebView.destroy()
4753 // Update the domains settings set.
4754 updateDomainsSettingsSet()
4756 // Instantiate the check filter list helper.
4757 checkFilterListHelper = CheckFilterListHelper()
4760 @SuppressLint("ClickableViewAccessibility")
4761 override fun initializeWebView(nestedScrollWebView: NestedScrollWebView, pagePosition: Int, progressBar: ProgressBar, urlString: String, restoringState: Boolean) {
4762 // Get the WebView theme.
4763 val webViewTheme = sharedPreferences.getString(getString(R.string.webview_theme_key), getString(R.string.webview_theme_default_value))
4765 // Get the WebView theme entry values string array.
4766 val webViewThemeEntryValuesStringArray = resources.getStringArray(R.array.webview_theme_entry_values)
4768 // Set the WebView theme if algorithmic darkening is supported.
4769 if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {
4770 // Set the WebView them. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
4771 if (webViewTheme == webViewThemeEntryValuesStringArray[1]) { // The light theme is selected.
4772 // Turn off algorithmic darkening.
4773 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
4775 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
4776 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
4777 nestedScrollWebView.visibility = View.VISIBLE
4778 } else if (webViewTheme == webViewThemeEntryValuesStringArray[2]) { // The dark theme is selected.
4779 // Turn on algorithmic darkening.
4780 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
4781 } else { // The system default theme is selected.
4782 // Get the current theme status.
4783 val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
4785 // Set the algorithmic darkening according to the current system theme status.
4786 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) { // The system is in day mode.
4787 // Turn off algorithmic darkening.
4788 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
4790 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
4791 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
4792 nestedScrollWebView.visibility = View.VISIBLE
4793 } else { // The system is in night mode.
4794 // Turn on algorithmic darkening.
4795 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
4800 // Get a handle for the input method manager.
4801 val inputMethodManager = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
4803 // Set the app bar scrolling.
4804 nestedScrollWebView.isNestedScrollingEnabled = scrollAppBar
4806 // Allow pinch to zoom.
4807 nestedScrollWebView.settings.builtInZoomControls = true
4809 // Hide zoom controls.
4810 nestedScrollWebView.settings.displayZoomControls = false
4812 // Don't allow mixed content (HTTP and HTTPS) on the same website.
4813 nestedScrollWebView.settings.mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW
4815 // Set the WebView to load in overview mode (zoomed out to the maximum width).
4816 nestedScrollWebView.settings.loadWithOverviewMode = true
4818 // Explicitly disable geolocation.
4819 nestedScrollWebView.settings.setGeolocationEnabled(false)
4821 // Allow loading of file:// URLs. This is necessary for opening MHT web archives, which are copied into a temporary cache location.
4822 nestedScrollWebView.settings.allowFileAccess = true
4824 // Create a double-tap gesture detector to toggle full-screen mode.
4825 val doubleTapGestureDetector = GestureDetector(this, object : GestureDetector.SimpleOnGestureListener() {
4826 // Override `onDoubleTap()`. All other events are handled using the default settings.
4827 override fun onDoubleTap(motionEvent: MotionEvent): Boolean {
4828 return if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
4829 // Toggle the full screen browsing mode tracker.
4830 inFullScreenBrowsingMode = !inFullScreenBrowsingMode
4832 // Toggle the full screen browsing mode.
4833 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
4834 // Hide the app bar if specified.
4835 if (hideAppBar) { // App bar hiding is enabled.
4836 // Close the find on page bar if it is visible.
4837 closeFindOnPage(null)
4839 // Hide the tab linear layout.
4840 tabsLinearLayout.visibility = View.GONE
4842 // Hide the app bar.
4845 // Set layout and scrolling parameters according to the position of the app bar.
4846 if (bottomAppBar) { // The app bar is at the bottom.
4847 // Reset the WebView padding to fill the available space.
4848 swipeRefreshLayout.setPadding(0, 0, 0, 0)
4849 } else { // The app bar is at the top.
4850 // Check to see if the app bar is normally scrolled.
4851 if (scrollAppBar) { // The app bar is scrolled when it is displayed.
4852 // Get the swipe refresh layout parameters.
4853 val swipeRefreshLayoutParams = swipeRefreshLayout.layoutParams as CoordinatorLayout.LayoutParams
4855 // Remove the off-screen scrolling layout.
4856 swipeRefreshLayoutParams.behavior = null
4857 } else { // The app bar is not scrolled when it is displayed.
4858 // Remove the padding from the top of the swipe refresh layout.
4859 swipeRefreshLayout.setPadding(0, 0, 0, 0)
4861 // The swipe refresh circle must be moved above the now removed status bar location.
4862 swipeRefreshLayout.setProgressViewOffset(false, -200, defaultProgressViewEndOffset)
4865 } else { // App bar hiding is not enabled.
4866 // Adjust the UI for the bottom app bar.
4868 // Adjust the UI according to the scrolling of the app bar.
4870 // Reset the WebView padding to fill the available space.
4871 swipeRefreshLayout.setPadding(0, 0, 0, 0)
4873 // Move the WebView above the app bar layout.
4874 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
4879 /* Hide the system bars.
4880 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4881 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4882 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4883 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4886 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4887 @Suppress("DEPRECATION")
4888 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
4889 } else { // Switch to normal viewing mode.
4890 // Show the app bar if it was hidden.
4892 // Show the tab linear layout.
4893 tabsLinearLayout.visibility = View.VISIBLE
4895 // Show the app bar.
4899 // Set layout and scrolling parameters according to the position of the app bar.
4900 if (bottomAppBar) { // The app bar is at the bottom.
4903 // Reset the WebView padding to fill the available space.
4904 swipeRefreshLayout.setPadding(0, 0, 0, 0)
4906 // Move the WebView above the app bar layout.
4907 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
4909 } else { // The app bar is at the top.
4910 // Check to see if the app bar is normally scrolled.
4911 if (scrollAppBar) { // The app bar is scrolled when it is displayed.
4912 // Get the swipe refresh layout parameters.
4913 val swipeRefreshLayoutParams = swipeRefreshLayout.layoutParams as CoordinatorLayout.LayoutParams
4915 // Add the off-screen scrolling layout.
4916 swipeRefreshLayoutParams.behavior = AppBarLayout.ScrollingViewBehavior()
4917 } else { // The app bar is not scrolled when it is displayed.
4918 // The swipe refresh layout must be manually moved below the app bar layout.
4919 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0)
4921 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
4922 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight)
4926 // Remove the `SYSTEM_UI` flags from the root frame layout. The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4927 @Suppress("DEPRECATION")
4928 rootFrameLayout.systemUiVisibility = 0
4931 // Consume the double-tap.
4933 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
4939 override fun onFling(motionEvent1: MotionEvent?, motionEvent2: MotionEvent, velocityX: Float, velocityY: Float): Boolean {
4940 // Scroll the bottom app bar if enabled.
4941 if (bottomAppBar && scrollAppBar && !objectAnimator.isRunning && (motionEvent1 != null)) {
4942 // Calculate the Y change.
4943 val motionY = motionEvent2.y - motionEvent1.y
4945 // Scroll the app bar if the change is greater than 50 pixels.
4947 // Animate the bottom app bar onto the screen.
4948 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0f)
4949 } else if (motionY < -50) {
4950 // Animate the bottom app bar off the screen.
4951 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", appBarLayout.height.toFloat())
4955 objectAnimator.start()
4958 // Do not consume the event.
4963 // Pass all touch events on the WebView through the double-tap gesture detector.
4964 nestedScrollWebView.setOnTouchListener { view: View, motionEvent: MotionEvent? ->
4965 // Call `performClick()` on the view, which is required for accessibility.
4968 // Check for double-taps.
4969 doubleTapGestureDetector.onTouchEvent(motionEvent!!)
4972 // Register the WebView for a context menu. This is used to see link targets and download images.
4973 registerForContextMenu(nestedScrollWebView)
4975 // Allow the downloading of files.
4976 nestedScrollWebView.setDownloadListener { downloadUrlString: String?, userAgent: String?, contentDisposition: String?, mimetype: String?, contentLength: Long ->
4977 // Check the download preference.
4978 if (downloadWithExternalApp) { // Download with an external app.
4979 downloadUrlWithExternalApp(downloadUrlString!!)
4980 } else { // Handle the download inside of Privacy Browser.
4981 // Define a formatted file size string.
4983 // Process the content length if it contains data.
4984 val formattedFileSizeString = if (contentLength > 0) { // The content length is greater than 0.
4985 // Format the content length as a string.
4986 NumberFormat.getInstance().format(contentLength) + " " + getString(R.string.bytes)
4987 } else { // The content length is not greater than 0.
4988 // Set the formatted file size string to be `unknown size`.
4989 getString(R.string.unknown_size)
4992 // Get the file name from the content disposition.
4993 val fileNameString = UrlHelper.getFileName(this, contentDisposition, mimetype, downloadUrlString!!)
4995 // Instantiate the save dialog.
4996 val saveDialogFragment = SaveDialog.saveUrl(downloadUrlString, fileNameString, formattedFileSizeString, userAgent!!, nestedScrollWebView.acceptCookies)
4998 // 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.
5000 // Show the save dialog.
5001 saveDialogFragment.show(supportFragmentManager, getString(R.string.save_dialog))
5002 } catch (exception: Exception) { // The dialog could not be shown.
5003 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
5004 pendingDialogsArrayList.add(PendingDialogDataClass(saveDialogFragment, getString(R.string.save_dialog)))
5008 // Get the current page position.
5009 val currentPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
5011 // Get the corresponding tab.
5012 val tab = tabLayout.getTabAt(currentPagePosition)!!
5014 // Get the tab custom view.
5015 val tabCustomView = tab.customView!!
5017 // Get the tab views.
5018 val tabFavoriteIconImageView = tabCustomView.findViewById<ImageView>(R.id.favorite_icon_imageview)
5019 val tabTitleTextView = tabCustomView.findViewById<TextView>(R.id.title_textview)
5021 // Restore the previous webpage favorite icon and title if the title is currently set to `Loading...`.
5022 if (tabTitleTextView.text.toString() == getString(R.string.loading)) {
5023 // Restore the previous webpage title text.
5024 tabTitleTextView.text = nestedScrollWebView.previousWebpageTitle
5026 // Restore the previous webpage favorite icon if it is not null.
5027 if (nestedScrollWebView.previousFavoriteIconDrawable != null)
5028 tabFavoriteIconImageView.setImageDrawable(nestedScrollWebView.previousFavoriteIconDrawable)
5032 // Update the find on page count.
5033 nestedScrollWebView.setFindListener { activeMatchOrdinal, numberOfMatches, isDoneCounting ->
5034 if (isDoneCounting && (numberOfMatches == 0)) { // There are no matches.
5035 // Set the find on page count text view to be `0/0`.
5036 findOnPageCountTextView.setText(R.string.zero_of_zero)
5037 } else if (isDoneCounting) { // There are matches.
5038 // The active match ordinal is zero-based.
5039 val activeMatch = activeMatchOrdinal + 1
5041 // Build the match string.
5042 val matchString = "$activeMatch/$numberOfMatches"
5044 // Update the find on page count text view.
5045 findOnPageCountTextView.text = matchString
5049 // Process scroll changes.
5050 nestedScrollWebView.setOnScrollChangeListener { _: View?, _: Int, _: Int, _: Int, _: Int ->
5051 // Set the swipe to refresh status.
5052 if (nestedScrollWebView.swipeToRefresh) // Only enable swipe to refresh if the WebView is scrolled to the top.
5053 swipeRefreshLayout.isEnabled = nestedScrollWebView.scrollY == 0
5054 else // Disable swipe to refresh.
5055 swipeRefreshLayout.isEnabled = false
5057 // Reinforce the system UI visibility flags if in full screen browsing mode.
5058 // This hides the status and navigation bars, which are displayed if other elements are shown, like dialog boxes, the options menu, or the keyboard.
5059 if (inFullScreenBrowsingMode) {
5060 /* Hide the system bars.
5061 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5062 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5063 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5064 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5067 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
5068 @Suppress("DEPRECATION")
5069 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
5073 // Set the web chrome client.
5074 nestedScrollWebView.webChromeClient = object : WebChromeClient() {
5075 // Update the progress bar when a page is loading.
5076 override fun onProgressChanged(view: WebView, progress: Int) {
5077 // Update the progress bar.
5078 progressBar.progress = progress
5080 // Set the visibility of the progress bar.
5081 if (progress < 100) {
5082 // Show the progress bar.
5083 progressBar.visibility = View.VISIBLE
5085 // Hide the progress bar.
5086 progressBar.visibility = View.GONE
5088 //Stop the swipe to refresh indicator if it is running
5089 swipeRefreshLayout.isRefreshing = false
5091 // 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.
5092 nestedScrollWebView.visibility = View.VISIBLE
5096 // Set the favorite icon when it changes.
5097 override fun onReceivedIcon(view: WebView, icon: Bitmap) {
5098 // 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.
5099 // This prevents low resolution icons from replacing high resolution one.
5100 // The check for the visibility of the progress bar can possibly be removed once https://redmine.stoutner.com/issues/747 is fixed.
5101 if ((progressBar.visibility == View.GONE) && (icon.height > nestedScrollWebView.getFavoriteIconHeight())) {
5102 // Store the new favorite icon.
5103 nestedScrollWebView.setFavoriteIcon(icon)
5105 // Get the current page position.
5106 val currentPosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
5108 // Get the current tab.
5109 val tab = tabLayout.getTabAt(currentPosition)
5111 // Check to see if the tab has been populated.
5113 // Get the custom view from the tab.
5114 val tabView = tab.customView
5116 // Check to see if the custom tab view has been populated.
5117 if (tabView != null) {
5118 // Get the favorite icon image view from the tab.
5119 val tabFavoriteIconImageView = tabView.findViewById<ImageView>(R.id.favorite_icon_imageview)
5121 // Display the favorite icon in the tab.
5122 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true))
5128 // Save a copy of the title when it changes.
5129 override fun onReceivedTitle(view: WebView, title: String) {
5130 // Get the current page position.
5131 val currentPosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
5133 // Get the current tab.
5134 val tab = tabLayout.getTabAt(currentPosition)
5136 // Only populate the title text view if the tab has been fully created.
5138 // Get the custom view from the tab.
5139 val tabView = tab.customView
5141 // Only populate the title text view if the tab view has been fully populated.
5142 if (tabView != null) {
5143 // Get the title text view from the tab.
5144 val tabTitleTextView = tabView.findViewById<TextView>(R.id.title_textview)
5146 // Set the title according to the URL.
5147 if (title == "about:blank") {
5148 // Set the title to indicate a new tab.
5149 tabTitleTextView.setText(R.string.new_tab)
5151 // Set the title as the tab text.
5152 tabTitleTextView.text = title
5158 // Enter full screen video.
5159 override fun onShowCustomView(video: View, callback: CustomViewCallback) {
5160 // Set the full screen video flag.
5161 displayingFullScreenVideo = true
5163 // Hide the keyboard.
5164 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.windowToken, 0)
5166 // Hide the coordinator layout.
5167 coordinatorLayout.visibility = View.GONE
5169 /* Hide the system bars.
5170 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5171 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5172 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5173 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5176 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
5177 @Suppress("DEPRECATION")
5178 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
5180 // Disable the sliding drawers.
5181 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
5183 // Add the video view to the full screen video frame layout.
5184 fullScreenVideoFrameLayout.addView(video)
5186 // Show the full screen video frame layout.
5187 fullScreenVideoFrameLayout.visibility = View.VISIBLE
5189 // Disable the screen timeout while the video is playing. YouTube does this automatically, but not all other videos do.
5190 fullScreenVideoFrameLayout.keepScreenOn = true
5193 // Exit full screen video.
5194 override fun onHideCustomView() {
5195 // Exit the full screen video.
5196 exitFullScreenVideo()
5200 override fun onShowFileChooser(webView: WebView, filePathCallback: ValueCallback<Array<Uri>>, fileChooserParams: FileChooserParams): Boolean {
5201 // Store the file path callback.
5202 fileChooserCallback = filePathCallback
5204 // Create an intent to open a chooser based on the file chooser parameters.
5205 val fileChooserIntent = fileChooserParams.createIntent()
5207 // Check to see if the file chooser intent resolves to an installed package.
5208 if (fileChooserIntent.resolveActivity(packageManager) != null) { // The file chooser intent is fine.
5209 // Launch the file chooser intent.
5210 browseFileUploadActivityResultLauncher.launch(fileChooserIntent)
5211 } else { // The file chooser intent will cause a crash.
5212 // Create a generic intent to open a chooser.
5213 val genericFileChooserIntent = Intent(Intent.ACTION_GET_CONTENT)
5215 // Request an openable file.
5216 genericFileChooserIntent.addCategory(Intent.CATEGORY_OPENABLE)
5218 // Set the file type to everything.
5219 genericFileChooserIntent.type = "*/*"
5221 // Launch the generic file chooser intent.
5222 browseFileUploadActivityResultLauncher.launch(genericFileChooserIntent)
5225 // Handle the event.
5229 nestedScrollWebView.webViewClient = object : WebViewClient() {
5230 // `shouldOverrideUrlLoading` makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
5231 override fun shouldOverrideUrlLoading(view: WebView, webResourceRequest: WebResourceRequest): Boolean {
5232 // Get the URL from the web resource request.
5233 var requestUrlString = webResourceRequest.url.toString()
5235 // Sanitize the url.
5236 requestUrlString = sanitizeUrl(requestUrlString)
5238 // Handle the URL according to the type.
5239 return if (requestUrlString.startsWith("http")) { // Load the URL in Privacy Browser.
5240 // Load the URL. By using `loadUrl()`, instead of `loadUrlFromBase()`, the Referer header will never be sent.
5241 loadUrl(nestedScrollWebView, requestUrlString)
5243 // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
5244 // Custom headers cannot be added if false is returned and the WebView handles the loading of the URL.
5246 } else if (requestUrlString.startsWith("mailto:")) { // Load the email address in an external email program.
5247 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
5248 val emailIntent = Intent(Intent.ACTION_SENDTO)
5250 // Parse the url and set it as the data for the intent.
5251 emailIntent.data = Uri.parse(requestUrlString)
5253 // Open the email program in a new task instead of as part of Privacy Browser.
5254 emailIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
5258 startActivity(emailIntent)
5259 } catch (exception: ActivityNotFoundException) {
5260 // Display a snackbar.
5261 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
5264 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5266 } else if (requestUrlString.startsWith("tel:")) { // Load the phone number in the dialer.
5267 // Create a dial intent.
5268 val dialIntent = Intent(Intent.ACTION_DIAL)
5270 // Add the phone number to the intent.
5271 dialIntent.data = Uri.parse(requestUrlString)
5273 // Open the dialer in a new task instead of as part of Privacy Browser.
5274 dialIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
5278 startActivity(dialIntent)
5279 } catch (exception: ActivityNotFoundException) {
5280 // Display a snackbar.
5281 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
5284 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5286 } else { // Load a system chooser to select an app that can handle the URL.
5287 // Create a generic intent to open an app.
5288 val genericIntent = Intent(Intent.ACTION_VIEW)
5290 // Add the URL to the intent.
5291 genericIntent.data = Uri.parse(requestUrlString)
5293 // List all apps that can handle the URL instead of just opening the first one.
5294 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE)
5296 // Open the app in a new task instead of as part of Privacy Browser.
5297 genericIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
5301 startActivity(genericIntent)
5302 } catch (exception: ActivityNotFoundException) {
5303 // Display a snackbar.
5304 Snackbar.make(nestedScrollWebView, getString(R.string.unrecognized_url, requestUrlString), Snackbar.LENGTH_SHORT).show()
5307 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5312 // Check requests against the block lists.
5313 override fun shouldInterceptRequest(view: WebView, webResourceRequest: WebResourceRequest): WebResourceResponse? {
5315 val requestUrlString = webResourceRequest.url.toString()
5317 // Check to see if the resource request is for the main URL.
5318 if (requestUrlString == nestedScrollWebView.currentUrl) {
5319 // `return null` loads the resource request, which should never be blocked if it is the main URL.
5323 // 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.
5324 while (ultraPrivacy == null) {
5326 // Check to see if the filter lists have been populated after 100 ms.
5328 } catch (exception: InterruptedException) {
5333 // Create an empty web resource response to be used if the resource request is blocked.
5334 val emptyWebResourceResponse = WebResourceResponse("text/plain", "utf8", ByteArrayInputStream("".toByteArray()))
5336 // Initialize the variables.
5337 var allowListResultStringArray: Array<String>? = null
5338 var isThirdPartyRequest = false
5340 // Get the current URL. `.getUrl()` throws an error because operations on the WebView cannot be made from this thread.
5341 var currentBaseDomain = nestedScrollWebView.currentDomainName
5343 // Store a copy of the current domain for use in later requests.
5344 val currentDomain = currentBaseDomain
5346 // Get the request host name.
5347 var requestBaseDomain = webResourceRequest.url.host
5349 // Only check for third-party requests if the current base domain is not empty and the request domain is not null.
5350 if (currentBaseDomain.isNotEmpty() && (requestBaseDomain != null)) {
5351 // Determine the current base domain.
5352 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5353 // Remove the first subdomain.
5354 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1)
5357 // Determine the request base domain.
5358 while (requestBaseDomain!!.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5359 // Remove the first subdomain.
5360 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1)
5363 // Update the third party request tracker.
5364 isThirdPartyRequest = currentBaseDomain != requestBaseDomain
5367 // Get the current WebView page position.
5368 val webViewPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
5370 // Determine if the WebView is currently displayed.
5371 val webViewDisplayed = (webViewPagePosition == tabLayout.selectedTabPosition)
5373 // Block third-party requests if enabled.
5374 if (isThirdPartyRequest && nestedScrollWebView.blockAllThirdPartyRequests) {
5375 // Add the result to the resource requests.
5376 nestedScrollWebView.addResourceRequest(arrayOf(REQUEST_THIRD_PARTY, requestUrlString))
5378 // Increment the blocked requests counters.
5379 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5380 nestedScrollWebView.incrementRequestsCount(THIRD_PARTY_REQUESTS)
5382 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5383 if (webViewDisplayed) {
5384 // Updating the UI must be run from the UI thread.
5386 // Update the menu item titles.
5387 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5389 // Update the options menu if it has been populated.
5390 if (optionsMenu != null) {
5391 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5392 optionsBlockAllThirdPartyRequestsMenuItem.title =
5393 nestedScrollWebView.getRequestsCount(THIRD_PARTY_REQUESTS).toString() + " - " + getString(R.string.block_all_third_party_requests)
5398 // The resource request was blocked. Return an empty web resource response.
5399 return emptyWebResourceResponse
5402 // Check UltraList if it is enabled.
5403 if (nestedScrollWebView.ultraListEnabled) {
5404 // Check the URL against UltraList.
5405 val ultraListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, ultraList)
5407 // Process the UltraList results.
5408 if (ultraListResults[0] == REQUEST_BLOCKED) { // The resource request matched UltraList's block list.
5409 // Add the result to the resource requests.
5410 nestedScrollWebView.addResourceRequest(arrayOf(ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]))
5412 // Increment the blocked requests counters.
5413 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5414 nestedScrollWebView.incrementRequestsCount(com.stoutner.privacybrowser.views.ULTRALIST)
5416 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5417 if (webViewDisplayed) {
5418 // Updating the UI must be run from the UI thread.
5420 // Update the menu item titles.
5421 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5423 // Update the options menu if it has been populated.
5424 if (optionsMenu != null) {
5425 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5426 optionsUltraListMenuItem.title = nestedScrollWebView.getRequestsCount(com.stoutner.privacybrowser.views.ULTRALIST).toString() + " - " + getString(R.string.ultralist)
5431 // The resource request was blocked. Return an empty web resource response.
5432 return emptyWebResourceResponse
5433 } else if (ultraListResults[0] == REQUEST_ALLOWED) { // The resource request matched UltraList's allow list.
5434 // Add an allow list entry to the resource requests array.
5435 nestedScrollWebView.addResourceRequest(arrayOf(ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]))
5437 // The resource request has been allowed by UltraList. `return null` loads the requested resource.
5442 // Check UltraPrivacy if it is enabled.
5443 if (nestedScrollWebView.ultraPrivacyEnabled) {
5444 // Check the URL against UltraPrivacy.
5445 val ultraPrivacyResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, ultraPrivacy!!)
5447 // Process the UltraPrivacy results.
5448 if (ultraPrivacyResults[0] == REQUEST_BLOCKED) { // The resource request matched UltraPrivacy's block list.
5449 // Add the result to the resource requests.
5450 nestedScrollWebView.addResourceRequest(arrayOf(ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5451 ultraPrivacyResults[5]))
5453 // Increment the blocked requests counters.
5454 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5455 nestedScrollWebView.incrementRequestsCount(ULTRAPRIVACY)
5457 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5458 if (webViewDisplayed) {
5459 // Updating the UI must be run from the UI thread.
5461 // Update the menu item titles.
5462 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5464 // Update the options menu if it has been populated.
5465 if (optionsMenu != null) {
5466 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5467 optionsUltraPrivacyMenuItem.title = nestedScrollWebView.getRequestsCount(ULTRAPRIVACY).toString() + " - " + getString(R.string.ultraprivacy)
5472 // The resource request was blocked. Return an empty web resource response.
5473 return emptyWebResourceResponse
5474 } else if (ultraPrivacyResults[0] == REQUEST_ALLOWED) { // The resource request matched UltraPrivacy's allow list.
5475 // Add an allow list entry to the resource requests array.
5476 nestedScrollWebView.addResourceRequest(arrayOf(ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5477 ultraPrivacyResults[5]))
5479 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
5484 // Check EasyList if it is enabled.
5485 if (nestedScrollWebView.easyListEnabled) {
5486 // Check the URL against EasyList.
5487 val easyListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, easyList)
5489 // Process the EasyList results.
5490 if (easyListResults[0] == REQUEST_BLOCKED) { // The resource request matched EasyList's block list.
5491 // Add the result to the resource requests.
5492 nestedScrollWebView.addResourceRequest(arrayOf(easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]))
5494 // Increment the blocked requests counters.
5495 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5496 nestedScrollWebView.incrementRequestsCount(EASYLIST)
5498 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5499 if (webViewDisplayed) {
5500 // Updating the UI must be run from the UI thread.
5502 // Update the menu item titles.
5503 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5505 // Update the options menu if it has been populated.
5506 if (optionsMenu != null) {
5507 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5508 optionsEasyListMenuItem.title = nestedScrollWebView.getRequestsCount(EASYLIST).toString() + " - " + getString(R.string.easylist)
5513 // The resource request was blocked. Return an empty web resource response.
5514 return emptyWebResourceResponse
5515 } else if (easyListResults[0] == REQUEST_ALLOWED) { // The resource request matched EasyList's allow list.
5516 // Update the allow list result string array tracker.
5517 allowListResultStringArray = arrayOf(easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5])
5521 // Check EasyPrivacy if it is enabled.
5522 if (nestedScrollWebView.easyPrivacyEnabled) {
5523 // Check the URL against EasyPrivacy.
5524 val easyPrivacyResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, easyPrivacy)
5526 // Process the EasyPrivacy results.
5527 if (easyPrivacyResults[0] == REQUEST_BLOCKED) { // The resource request matched EasyPrivacy's block list.
5528 // Add the result to the resource requests.
5529 nestedScrollWebView.addResourceRequest(arrayOf(easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5]))
5531 // Increment the blocked requests counters.
5532 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5533 nestedScrollWebView.incrementRequestsCount(EASYPRIVACY)
5535 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5536 if (webViewDisplayed) {
5537 // Updating the UI must be run from the UI thread.
5539 // Update the menu item titles.
5540 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5542 // Update the options menu if it has been populated.
5543 if (optionsMenu != null) {
5544 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5545 optionsEasyPrivacyMenuItem.title = nestedScrollWebView.getRequestsCount(EASYPRIVACY).toString() + " - " + getString(R.string.easyprivacy)
5550 // The resource request was blocked. Return an empty web resource response.
5551 return emptyWebResourceResponse
5552 } else if (easyPrivacyResults[0] == REQUEST_ALLOWED) { // The resource request matched EasyPrivacy's allow list.
5553 // Update the allow list result string array tracker.
5554 allowListResultStringArray = arrayOf(easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5])
5558 // Check Fanboy’s Annoyance List if it is enabled.
5559 if (nestedScrollWebView.fanboysAnnoyanceListEnabled) {
5560 // Check the URL against Fanboy's Annoyance List.
5561 val fanboysAnnoyanceListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, fanboysAnnoyanceList)
5563 // Process the Fanboy's Annoyance List results.
5564 if (fanboysAnnoyanceListResults[0] == REQUEST_BLOCKED) { // The resource request matched Fanboy's Annoyance List's block list.
5565 // Add the result to the resource requests.
5566 nestedScrollWebView.addResourceRequest(arrayOf(fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5567 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]))
5569 // Increment the blocked requests counters.
5570 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5571 nestedScrollWebView.incrementRequestsCount(FANBOYS_ANNOYANCE_LIST)
5573 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5574 if (webViewDisplayed) {
5575 // Updating the UI must be run from the UI thread.
5577 // Update the menu item titles.
5578 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5580 // Update the options menu if it has been populated.
5581 if (optionsMenu != null) {
5582 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5583 optionsFanboysAnnoyanceListMenuItem.title = nestedScrollWebView.getRequestsCount(FANBOYS_ANNOYANCE_LIST).toString() + " - " + getString(R.string.fanboys_annoyance_list)
5588 // The resource request was blocked. Return an empty web resource response.
5589 return emptyWebResourceResponse
5590 } else if (fanboysAnnoyanceListResults[0] == REQUEST_ALLOWED) { // The resource request matched Fanboy's Annoyance List's allow list.
5591 // Update the allow list result string array tracker.
5592 allowListResultStringArray = arrayOf(fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5593 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5])
5595 } else if (nestedScrollWebView.fanboysSocialBlockingListEnabled) { // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
5596 // Check the URL against Fanboy's Annoyance List.
5597 val fanboysSocialListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, fanboysSocialList)
5599 // Process the Fanboy's Social Blocking List results.
5600 if (fanboysSocialListResults[0] == REQUEST_BLOCKED) { // The resource request matched Fanboy's Social Blocking List's block list.
5601 // Add the result to the resource requests.
5602 nestedScrollWebView.addResourceRequest(arrayOf(fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5603 fanboysSocialListResults[4], fanboysSocialListResults[5]))
5605 // Increment the blocked requests counters.
5606 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5607 nestedScrollWebView.incrementRequestsCount(FANBOYS_SOCIAL_BLOCKING_LIST)
5609 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5610 if (webViewDisplayed) {
5611 // Updating the UI must be run from the UI thread.
5613 // Update the menu item titles.
5614 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5616 // Update the options menu if it has been populated.
5617 if (optionsMenu != null) {
5618 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5619 optionsFanboysSocialBlockingListMenuItem.title =
5620 nestedScrollWebView.getRequestsCount(FANBOYS_SOCIAL_BLOCKING_LIST).toString() + " - " + getString(R.string.fanboys_social_blocking_list)
5625 // The resource request was blocked. Return an empty web resource response.
5626 return emptyWebResourceResponse
5627 } else if (fanboysSocialListResults[0] == REQUEST_ALLOWED) { // The resource request matched Fanboy's Social Blocking List's allow list.
5628 // Update the allow list result string array tracker.
5629 allowListResultStringArray = arrayOf(fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3], fanboysSocialListResults[4],
5630 fanboysSocialListResults[5])
5634 // Add the request to the log because it hasn't been processed by any of the previous checks.
5635 if (allowListResultStringArray != null) { // The request was processed by an allow list.
5636 nestedScrollWebView.addResourceRequest(allowListResultStringArray)
5637 } else { // The request didn't match any filter list entry. Log it as a default request.
5638 nestedScrollWebView.addResourceRequest(arrayOf(REQUEST_DEFAULT, requestUrlString))
5641 // The resource request has not been blocked. `return null` loads the requested resource.
5645 // Handle HTTP authentication requests.
5646 override fun onReceivedHttpAuthRequest(view: WebView, handler: HttpAuthHandler, host: String, realm: String) {
5647 // Store the handler.
5648 nestedScrollWebView.httpAuthHandler = handler
5650 // Instantiate an HTTP authentication dialog.
5651 val httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm, nestedScrollWebView.webViewFragmentId)
5653 // Show the HTTP authentication dialog.
5654 httpAuthenticationDialogFragment.show(supportFragmentManager, getString(R.string.http_authentication))
5657 override fun onPageStarted(webView: WebView, url: String, favicon: Bitmap?) {
5658 // Get the app bar layout height. This can't be done in `applyAppSettings()` because the app bar is not yet populated there.
5659 // 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.
5660 if (appBarLayout.height > 0)
5661 appBarHeight = appBarLayout.height
5663 // Set the padding and layout settings according to the position of the app bar.
5664 if (bottomAppBar) { // The app bar is on the bottom.
5666 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) { // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
5667 // Reset the WebView padding to fill the available space.
5668 swipeRefreshLayout.setPadding(0, 0, 0, 0)
5669 } else { // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
5670 // Move the WebView above the app bar layout.
5671 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
5673 } else { // The app bar is on the top.
5674 // 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.
5675 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) { // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
5676 // No padding is needed because it will automatically be placed below the app bar layout due to the scrolling layout behavior.
5677 swipeRefreshLayout.setPadding(0, 0, 0, 0)
5679 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5680 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10, defaultProgressViewEndOffset)
5681 } else { // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
5682 // The swipe refresh layout must be manually moved below the app bar layout.
5683 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0)
5685 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5686 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight)
5690 // Reset the list of resource requests.
5691 nestedScrollWebView.clearResourceRequests()
5693 // Reset the requests counters.
5694 nestedScrollWebView.resetRequestsCounters()
5696 // Get the current page position.
5697 val currentPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
5699 // Update the URL text bar if the page is currently selected and the URL edit text is not currently being edited.
5700 if ((tabLayout.selectedTabPosition == currentPagePosition) && !urlEditText.hasFocus()) {
5701 // Display the formatted URL text. The nested scroll WebView current URL preserves any initial `view-source:`, and opposed to the method URL variable.
5702 urlEditText.setText(nestedScrollWebView.currentUrl)
5704 // Highlight the URL syntax.
5705 UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
5707 // Hide the keyboard.
5708 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.windowToken, 0)
5711 // Reset the list of host IP addresses.
5712 nestedScrollWebView.currentIpAddresses = ""
5714 // Get a URI for the current URL.
5715 val currentUri = Uri.parse(url)
5717 // Get the current domain name.
5718 val currentDomainName = currentUri.host
5720 // Get the IP addresses for the current domain.
5721 if (!currentDomainName.isNullOrEmpty())
5722 GetHostIpAddressesCoroutine.checkPinnedMismatch(currentDomainName, nestedScrollWebView, supportFragmentManager, getString(R.string.pinned_mismatch))
5724 // 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.)
5725 if ((optionsMenu != null) && (webView == currentWebView)) {
5727 optionsRefreshMenuItem.setTitle(R.string.stop)
5729 // Set the icon if it is displayed in the AppBar.
5730 if (displayAdditionalAppBarIcons)
5731 optionsRefreshMenuItem.setIcon(R.drawable.close_blue)
5735 override fun onPageFinished(webView: WebView, url: String) {
5736 // Flush any cookies to persistent storage. The cookie manager has become very lazy about flushing cookies in recent versions.
5737 if (nestedScrollWebView.acceptCookies)
5738 cookieManager.flush()
5740 // Update the Refresh menu item if the options menu has been created and the WebView is currently displayed.
5741 if (optionsMenu != null && (webView == currentWebView)) {
5742 // Reset the Refresh title.
5743 optionsRefreshMenuItem.setTitle(R.string.refresh)
5745 // Reset the icon if it is displayed in the app bar.
5746 if (displayAdditionalAppBarIcons)
5747 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled)
5750 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
5751 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
5752 val privateDataDirectoryString = applicationInfo.dataDir
5754 // Clear the cache, history, and logcat if Incognito Mode is enabled.
5755 if (incognitoModeEnabled) {
5756 // Clear the cache. `true` includes disk files.
5757 nestedScrollWebView.clearCache(true)
5759 // Clear the back/forward history.
5760 nestedScrollWebView.clearHistory()
5762 // Manually delete cache folders.
5764 // Delete the main cache directory.
5765 Runtime.getRuntime().exec("rm -rf $privateDataDirectoryString/cache")
5766 } catch (exception: IOException) {
5767 // Do nothing if an error is thrown.
5770 // Clear the logcat.
5772 // Clear the logcat. `-c` clears the logcat. `-b all` clears all the buffers (instead of just crash, main, and system).
5773 Runtime.getRuntime().exec("logcat -b all -c")
5774 } catch (exception: IOException) {
5779 // Clear the `Service Worker` directory.
5781 // A string array must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
5782 Runtime.getRuntime().exec(arrayOf("rm", "-rf", "$privateDataDirectoryString/app_webview/Default/Service Worker/"))
5783 } catch (exception: IOException) {
5787 // Get the current page position.
5788 val currentPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
5790 // 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.
5791 val currentUrl = nestedScrollWebView.url
5793 // Get the current tab.
5794 val tab = tabLayout.getTabAt(currentPagePosition)
5796 // Update the URL text bar if the page is currently selected and the user is not currently typing in the URL edit text.
5797 // Crash records show that, in some crazy way, it is possible for the current URL to be blank at this point.
5798 // Probably some sort of race condition when Privacy Browser is being resumed.
5799 if ((tabLayout.selectedTabPosition == currentPagePosition) && !urlEditText.hasFocus() && (currentUrl != null)) {
5800 // Check to see if the URL is `about:blank`.
5801 if (currentUrl == "about:blank") { // The WebView is blank.
5802 // Display the hint in the URL edit text.
5803 urlEditText.setText("")
5805 // Request focus for the URL text box.
5806 urlEditText.requestFocus()
5808 // Display the keyboard.
5809 inputMethodManager.showSoftInput(urlEditText, 0)
5811 // Apply the domain settings. This clears any settings from the previous domain.
5812 applyDomainSettings(nestedScrollWebView, "", resetTab = true, reloadWebsite = false, loadUrl = false)
5814 // Only populate the title text view if the tab has been fully created.
5816 // Get the custom view from the tab.
5817 val tabView = tab.customView!!
5819 // Get the title text view from the tab.
5820 val tabTitleTextView = tabView.findViewById<TextView>(R.id.title_textview)
5822 // Set the title as the tab text.
5823 tabTitleTextView.setText(R.string.new_tab)
5825 } else { // The WebView has loaded a webpage.
5826 // Update the URL edit text if it is not currently being edited.
5827 if (!urlEditText.hasFocus()) {
5828 // 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.
5829 val sanitizedUrl = sanitizeUrl(currentUrl)
5831 // Display the final URL. Getting the URL from the WebView instead of using the one provided by `onPageFinished()` makes websites like YouTube function correctly.
5832 urlEditText.setText(sanitizedUrl)
5834 // Highlight the URL syntax.
5835 UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
5838 // Only populate the title text view if the tab has been fully created.
5840 // Get the custom view from the tab.
5841 val tabView = tab.customView!!
5843 // Get the title text view from the tab.
5844 val tabTitleTextView = tabView.findViewById<TextView>(R.id.title_textview)
5846 // Set the title as the tab text. Sometimes `onReceivedTitle()` is not called, especially when navigating history.
5847 tabTitleTextView.text = nestedScrollWebView.title
5853 // Handle SSL Certificate errors. Suppress the lint warning that ignoring the error might be dangerous.
5854 @SuppressLint("WebViewClientOnReceivedSslError")
5855 override fun onReceivedSslError(view: WebView, handler: SslErrorHandler, error: SslError) {
5856 // Get the current website SSL certificate.
5857 val currentWebsiteSslCertificate = error.certificate
5859 // Extract the individual pieces of information from the current website SSL certificate.
5860 val currentWebsiteIssuedToCName = currentWebsiteSslCertificate.issuedTo.cName
5861 val currentWebsiteIssuedToOName = currentWebsiteSslCertificate.issuedTo.oName
5862 val currentWebsiteIssuedToUName = currentWebsiteSslCertificate.issuedTo.uName
5863 val currentWebsiteIssuedByCName = currentWebsiteSslCertificate.issuedBy.cName
5864 val currentWebsiteIssuedByOName = currentWebsiteSslCertificate.issuedBy.oName
5865 val currentWebsiteIssuedByUName = currentWebsiteSslCertificate.issuedBy.uName
5866 val currentWebsiteSslStartDate = currentWebsiteSslCertificate.validNotBeforeDate
5867 val currentWebsiteSslEndDate = currentWebsiteSslCertificate.validNotAfterDate
5869 // Get the pinned SSL certificate.
5870 val (pinnedSslCertificateStringArray, pinnedSslCertificateDateArray) = nestedScrollWebView.getPinnedSslCertificate()
5872 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
5873 if (nestedScrollWebView.hasPinnedSslCertificate() &&
5874 (currentWebsiteIssuedToCName == pinnedSslCertificateStringArray[0]) &&
5875 (currentWebsiteIssuedToOName == pinnedSslCertificateStringArray[1]) &&
5876 (currentWebsiteIssuedToUName == pinnedSslCertificateStringArray[2]) &&
5877 (currentWebsiteIssuedByCName == pinnedSslCertificateStringArray[3]) &&
5878 (currentWebsiteIssuedByOName == pinnedSslCertificateStringArray[4]) &&
5879 (currentWebsiteIssuedByUName == pinnedSslCertificateStringArray[5]) &&
5880 (currentWebsiteSslStartDate == pinnedSslCertificateDateArray[0]) &&
5881 (currentWebsiteSslEndDate == pinnedSslCertificateDateArray[1])) {
5883 // An SSL certificate is pinned and matches the current domain certificate. Proceed to the website without displaying an error.
5885 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
5886 // Store the SSL error handler.
5887 nestedScrollWebView.sslErrorHandler = handler
5889 // Instantiate an SSL certificate error alert dialog.
5890 val sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error, nestedScrollWebView.webViewFragmentId)
5892 // Try to show the dialog. The SSL error handler continues to function even when the WebView is paused. Attempting to display a dialog in that state leads to a crash.
5894 // Show the SSL certificate error dialog.
5895 sslCertificateErrorDialogFragment.show(supportFragmentManager, getString(R.string.ssl_certificate_error))
5896 } catch (exception: Exception) {
5897 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
5898 pendingDialogsArrayList.add(PendingDialogDataClass(sslCertificateErrorDialogFragment, getString(R.string.ssl_certificate_error)))
5904 // Check to see if the state is being restored.
5905 if (restoringState) { // The state is being restored.
5906 // Resume the nested scroll WebView JavaScript timers.
5907 nestedScrollWebView.resumeTimers()
5908 } else if (pagePosition == 0) { // The first page is being loaded.
5909 // Set this nested scroll WebView as the current WebView.
5910 currentWebView = nestedScrollWebView
5912 // Get the intent that started the app.
5913 val launchingIntent = intent
5915 // Reset the intent. This prevents a duplicate tab from being created on restart.
5918 // Get the information from the intent.
5919 val launchingIntentAction = launchingIntent.action
5920 val launchingIntentUriData = launchingIntent.data
5921 val launchingIntentStringExtra = launchingIntent.getStringExtra(Intent.EXTRA_TEXT)
5923 // Parse the launching intent URL. Suppress the suggestions of using elvis expressions as they make the logic very difficult to follow.
5924 @Suppress("IfThenToElvis") val urlToLoadString = if ((launchingIntentAction != null) && (launchingIntentAction == Intent.ACTION_WEB_SEARCH)) { // The intent contains a search string.
5925 // Sanitize the search input and convert it to a search.
5926 val encodedSearchString = try {
5927 URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8")
5928 } catch (exception: UnsupportedEncodingException) {
5932 // Add the search URL to the encodedSearchString
5933 searchURL + encodedSearchString
5934 } else if (launchingIntentUriData != null) { // The launching intent contains a URL formatted as a URI.
5935 // Get the URL from the URI.
5936 launchingIntentUriData.toString()
5937 } else if (launchingIntentStringExtra != null) { // The launching intent contains text that might be a URL.
5938 // Get the URL from the string extra.
5939 launchingIntentStringExtra
5940 } else if (urlString != "") { // The activity has been restarted.
5941 // Load the saved URL.
5943 } else { // The is no saved URL and there is no URL in the intent.
5944 // Load the homepage.
5945 sharedPreferences.getString("homepage", getString(R.string.homepage_default_value))
5948 // Load the website if not waiting for the proxy.
5949 if (waitingForProxy) { // Store the URL to be loaded in the Nested Scroll WebView.
5950 nestedScrollWebView.waitingForProxyUrlString = urlToLoadString!!
5951 } else { // Load the URL.
5952 loadUrl(nestedScrollWebView, urlToLoadString!!)
5954 } else { // This is not the first tab.
5956 loadUrl(nestedScrollWebView, urlString)
5958 // Set the focus and display the keyboard if the URL is blank.
5959 if (urlString == "") {
5960 // Request focus for the URL text box.
5961 urlEditText.requestFocus()
5963 // Display the keyboard once the tab layout has settled.
5965 inputMethodManager.showSoftInput(urlEditText, 0)
5971 private fun loadBookmarksFolder() {
5972 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
5973 bookmarksCursor = bookmarksDatabaseHelper!!.getBookmarksByDisplayOrder(currentBookmarksFolderId)
5975 // Populate the bookmarks cursor adapter.
5976 bookmarksCursorAdapter = object : CursorAdapter(this, bookmarksCursor, false) {
5977 override fun newView(context: Context, cursor: Cursor, parent: ViewGroup): View {
5978 // Inflate the individual item layout.
5979 return layoutInflater.inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false)
5982 override fun bindView(view: View, context: Context, cursor: Cursor) {
5983 // Get handles for the views.
5984 val bookmarkFavoriteIcon = view.findViewById<ImageView>(R.id.bookmark_favorite_icon)
5985 val bookmarkNameTextView = view.findViewById<TextView>(R.id.bookmark_name)
5987 // Get the favorite icon byte array from the cursor.
5988 val favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndexOrThrow(FAVORITE_ICON))
5990 // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
5991 val favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.size)
5993 // Display the bitmap in the bookmark favorite icon.
5994 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap)
5996 // Display the bookmark name from the cursor in the bookmark name text view.
5997 bookmarkNameTextView.text = cursor.getString(cursor.getColumnIndexOrThrow(BOOKMARK_NAME))
5999 // Make the font bold for folders.
6000 if (cursor.getInt(cursor.getColumnIndexOrThrow(IS_FOLDER)) == 1)
6001 bookmarkNameTextView.typeface = Typeface.DEFAULT_BOLD
6002 else // Reset the font to default for normal bookmarks.
6003 bookmarkNameTextView.typeface = Typeface.DEFAULT
6007 // Populate the list view with the adapter.
6008 bookmarksListView.adapter = bookmarksCursorAdapter
6010 // Set the bookmarks drawer title.
6011 if (currentBookmarksFolderId == HOME_FOLDER_ID) // The current bookmarks folder is the home folder.
6012 bookmarksTitleTextView.setText(R.string.bookmarks)
6014 bookmarksTitleTextView.text = bookmarksDatabaseHelper!!.getFolderName(currentBookmarksFolderId)
6017 private fun loadUrl(nestedScrollWebView: NestedScrollWebView, url: String) {
6018 // Sanitize the URL.
6019 val urlString = sanitizeUrl(url)
6021 // Apply the domain settings and load the URL.
6022 applyDomainSettings(nestedScrollWebView, urlString, resetTab = true, reloadWebsite = false, loadUrl = true)
6025 private fun loadUrlFromTextBox() {
6026 // 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.
6027 var unformattedUrlString = urlEditText.text.toString().trim { it <= ' ' }
6029 // Create the formatted URL string.
6032 // Check to see if the unformatted URL string is a valid URL. Otherwise, convert it into a search.
6033 if (unformattedUrlString.startsWith("content://") || unformattedUrlString.startsWith("view-source:")) { // This is a content or source URL.
6034 // Load the entire content URL.
6035 urlString = unformattedUrlString
6036 } else if (Patterns.WEB_URL.matcher(unformattedUrlString).matches() || unformattedUrlString.startsWith("http://") || unformattedUrlString.startsWith("https://") ||
6037 unformattedUrlString.startsWith("file://")) { // This is a standard URL.
6039 // Add `https://` at the beginning if there is no protocol. Otherwise the app will segfault.
6040 if (!unformattedUrlString.startsWith("http") && !unformattedUrlString.startsWith("file://"))
6041 unformattedUrlString = "https://$unformattedUrlString"
6043 // Initialize the unformatted URL.
6044 var unformattedUrl: URL? = null
6046 // Convert the unformatted URL string to a URL.
6048 unformattedUrl = URL(unformattedUrlString)
6049 } catch (exception: MalformedURLException) {
6050 exception.printStackTrace()
6053 // Get the components of the URL.
6054 val scheme = unformattedUrl?.protocol
6055 val authority = unformattedUrl?.authority
6056 val path = unformattedUrl?.path
6057 val query = unformattedUrl?.query
6058 val fragment = unformattedUrl?.ref
6061 val uri = Uri.Builder()
6063 // Build the URI from the components of the URL.
6064 uri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment)
6066 // Decode the URI as a UTF-8 string in.
6068 urlString = URLDecoder.decode(uri.build().toString(), "UTF-8")
6069 } catch (exception: UnsupportedEncodingException) {
6070 // Do nothing. The formatted URL string will remain blank.
6072 } else if (unformattedUrlString.isNotEmpty()) { // This is not a URL, but rather a search string.
6073 // Sanitize the search input.
6074 val encodedSearchString = try {
6075 URLEncoder.encode(unformattedUrlString, "UTF-8")
6076 } catch (exception: UnsupportedEncodingException) {
6080 // Add the base search URL.
6081 urlString = searchURL + encodedSearchString
6084 // 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.
6085 urlEditText.clearFocus()
6088 loadUrl(currentWebView!!, urlString)
6091 override fun navigateHistory(url: String, steps: Int) {
6092 // Apply the domain settings.
6093 applyDomainSettings(currentWebView!!, url, resetTab = false, reloadWebsite = false, loadUrl = false)
6095 // Load the history entry.
6096 currentWebView!!.goBackOrForward(steps)
6098 // Update the URL edit text after a delay.
6099 updateUrlEditTextAfterDelay()
6102 override fun openFile(dialogFragment: DialogFragment) {
6104 val dialog = dialogFragment.dialog!!
6106 // Get handles for the views.
6107 val fileNameEditText = dialog.findViewById<EditText>(R.id.file_name_edittext)
6108 val mhtCheckBox = dialog.findViewById<CheckBox>(R.id.mht_checkbox)
6110 // Get the file path string.
6111 val openFilePath = fileNameEditText.text.toString()
6113 // Apply the domain settings. This resets the favorite icon and removes any domain settings.
6114 applyDomainSettings(currentWebView!!, openFilePath, resetTab = true, reloadWebsite = false, loadUrl = false)
6116 // Open the file according to the type.
6117 if (mhtCheckBox.isChecked) { // Force opening of an MHT file.
6119 // Get the MHT file input stream.
6120 val mhtFileInputStream = contentResolver.openInputStream(Uri.parse(openFilePath))
6122 // Create a temporary MHT file.
6123 val temporaryMhtFile = File.createTempFile(TEMPORARY_MHT_FILE, ".mht", cacheDir)
6125 // Get a file output stream for the temporary MHT file.
6126 val temporaryMhtFileOutputStream = FileOutputStream(temporaryMhtFile)
6128 // Create a transfer byte array.
6129 val transferByteArray = ByteArray(1024)
6131 // Create an integer to track the number of bytes read.
6134 // Copy the temporary MHT file input stream to the MHT output stream.
6135 while (mhtFileInputStream!!.read(transferByteArray).also { bytesRead = it } > 0)
6136 temporaryMhtFileOutputStream.write(transferByteArray, 0, bytesRead)
6138 // Flush the temporary MHT file output stream.
6139 temporaryMhtFileOutputStream.flush()
6141 // Close the streams.
6142 temporaryMhtFileOutputStream.close()
6143 mhtFileInputStream.close()
6145 // Load the temporary MHT file.
6146 currentWebView!!.loadUrl(temporaryMhtFile.toString())
6147 } catch (exception: Exception) {
6148 // Display a snackbar.
6149 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
6151 } else { // Let the WebView handle opening of the file.
6153 currentWebView!!.loadUrl(openFilePath)
6156 // The view parameter cannot be removed because it is called from the layout onClick.
6157 fun openNavigationDrawer(@Suppress("UNUSED_PARAMETER")view: View) {
6158 // Open the navigation drawer.
6159 drawerLayout.openDrawer(GravityCompat.START)
6162 private fun openWithApp(url: String) {
6163 // Create an open with app intent with `ACTION_VIEW`.
6164 val openWithAppIntent = Intent(Intent.ACTION_VIEW)
6166 // Set the URI but not the MIME type. This should open all available apps.
6167 openWithAppIntent.data = Uri.parse(url)
6169 // Flag the intent to open in a new task.
6170 openWithAppIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
6174 // Show the chooser.
6175 startActivity(openWithAppIntent)
6176 } catch (exception: ActivityNotFoundException) { // There are no apps available to open the URL.
6177 // Show a snackbar with the error.
6178 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
6182 private fun openWithBrowser(url: String) {
6184 // Create an open with browser intent with `ACTION_VIEW`.
6185 val openWithBrowserIntent = Intent(Intent.ACTION_VIEW)
6187 // Set the URI and the MIME type. `"text/html"` should load browser options.
6188 openWithBrowserIntent.setDataAndType(Uri.parse(url), "text/html")
6190 // Flag the intent to open in a new task.
6191 openWithBrowserIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
6195 // Show the chooser.
6196 startActivity(openWithBrowserIntent)
6197 } catch (exception: ActivityNotFoundException) { // There are no browsers available to open the URL.
6198 // Show a snackbar with the error.
6199 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
6203 override fun pinnedErrorGoBack() {
6204 // Get the current web back forward list.
6205 val webBackForwardList = currentWebView!!.copyBackForwardList()
6207 // Get the previous entry URL.
6208 val previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex - 1).url
6210 // Apply the domain settings.
6211 applyDomainSettings(currentWebView!!, previousUrl, resetTab = false, reloadWebsite = false, loadUrl = false)
6214 currentWebView!!.goBack()
6216 // Update the URL edit text after a delay.
6217 updateUrlEditTextAfterDelay()
6220 private fun sanitizeUrl(urlString: String): String {
6221 // Initialize a sanitized URL string.
6222 var sanitizedUrlString = urlString
6224 // Sanitize tracking queries.
6225 if (sanitizeTrackingQueries)
6226 sanitizedUrlString = SanitizeUrlHelper.sanitizeTrackingQueries(sanitizedUrlString)
6228 // Sanitize AMP redirects.
6229 if (sanitizeAmpRedirects)
6230 sanitizedUrlString = SanitizeUrlHelper.sanitizeAmpRedirects(sanitizedUrlString)
6232 // Return the sanitized URL string.
6233 return sanitizedUrlString
6236 override fun saveUrl(originalUrlString: String, fileNameString: String, dialogFragment: DialogFragment) {
6237 // Store the URL. This will be used in the save URL activity result launcher.
6238 saveUrlString = if (originalUrlString.startsWith("data:")) {
6239 // Save the original URL.
6243 val dialog = dialogFragment.dialog!!
6245 // Get a handle for the dialog URL edit text.
6246 val dialogUrlEditText = dialog.findViewById<EditText>(R.id.url_edittext)
6248 // Get the URL from the edit text, which may have been modified.
6249 dialogUrlEditText.text.toString()
6252 // Open the file picker.
6253 saveUrlActivityResultLauncher.launch(fileNameString)
6256 private fun setCurrentWebView(pageNumber: Int) {
6257 // Stop the swipe to refresh indicator if it is running
6258 swipeRefreshLayout.isRefreshing = false
6260 // Try to set the current WebView. This will fail if the WebView has not yet been populated.
6262 // Get the WebView tab fragment.
6263 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(pageNumber)
6265 // Get the fragment view.
6266 val webViewFragmentView = webViewTabFragment.view
6268 // Store the current WebView.
6269 currentWebView = webViewFragmentView!!.findViewById(R.id.nestedscroll_webview)
6271 // Update the status of swipe to refresh.
6272 if (currentWebView!!.swipeToRefresh) { // Swipe to refresh is enabled.
6273 // Enable the swipe refresh layout if the WebView is scrolled all the way to the top. It is updated every time the scroll changes.
6274 swipeRefreshLayout.isEnabled = (currentWebView!!.scrollY == 0)
6275 } else { // Swipe to refresh is disabled.
6276 // Disable the swipe refresh layout.
6277 swipeRefreshLayout.isEnabled = false
6280 // Set the cookie status.
6281 cookieManager.setAcceptCookie(currentWebView!!.acceptCookies)
6283 // Update the privacy icons. `true` redraws the icons in the app bar.
6284 updatePrivacyIcons(true)
6286 // Get a handle for the input method manager.
6287 val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
6289 // Get the current URL.
6290 val urlString = currentWebView!!.url
6292 // Update the URL edit text if not loading a new intent. Otherwise, this will be handled by `onPageStarted()` (if called) and `onPageFinished()`.
6293 if (!loadingNewIntent) { // A new intent is not being loaded.
6294 if ((urlString == null) || (urlString == "about:blank")) { // The WebView is blank.
6295 // Display the hint in the URL edit text.
6296 urlEditText.setText("")
6298 // Request focus for the URL text box.
6299 urlEditText.requestFocus()
6301 // Display the keyboard.
6302 inputMethodManager.showSoftInput(urlEditText, 0)
6303 } else { // The WebView has a loaded URL.
6304 // Clear the focus from the URL text box.
6305 urlEditText.clearFocus()
6307 // Hide the soft keyboard.
6308 inputMethodManager.hideSoftInputFromWindow(currentWebView!!.windowToken, 0)
6310 // Display the current URL in the URL text box.
6311 urlEditText.setText(urlString)
6313 // Highlight the URL syntax.
6314 UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
6316 } else { // A new intent is being loaded.
6317 // Reset the loading new intent flag.
6318 loadingNewIntent = false
6321 // Set the background to indicate the domain settings status.
6322 if (currentWebView!!.domainSettingsApplied) {
6323 // Set a background on the URL relative layout to indicate that custom domain settings are being used.
6324 urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.drawable.domain_settings_url_background)
6326 // Remove any background on the URL relative layout.
6327 urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.color.transparent)
6329 } catch (exception: Exception) { // Try again in 10 milliseconds if the WebView has not yet been populated.
6330 // Create a handler to set the current WebView.
6331 val setCurrentWebViewHandler = Handler(Looper.getMainLooper())
6333 // Create a runnable to set the current WebView.
6334 val setCurrentWebWebRunnable = Runnable {
6335 // Set the current WebView.
6336 setCurrentWebView(pageNumber)
6339 // Try setting the current WebView again after 10 milliseconds.
6340 setCurrentWebViewHandler.postDelayed(setCurrentWebWebRunnable, 10)
6344 // The view parameter cannot be removed because it is called from the layout onClick.
6345 fun toggleBookmarksDrawerPinned(@Suppress("UNUSED_PARAMETER")view: View?) {
6346 // Toggle the bookmarks drawer pinned tracker.
6347 bookmarksDrawerPinned = !bookmarksDrawerPinned
6349 // Update the bookmarks drawer pinned image view.
6350 updateBookmarksDrawerPinnedImageView()
6353 private fun updateBookmarksDrawerPinnedImageView() {
6354 // Set the current icon.
6355 if (bookmarksDrawerPinned)
6356 bookmarksDrawerPinnedImageView.setImageResource(R.drawable.pin_selected)
6358 bookmarksDrawerPinnedImageView.setImageResource(R.drawable.pin)
6361 private fun updateDomainsSettingsSet() {
6362 // Reset the domains settings set.
6363 domainsSettingsSet = HashSet()
6365 // Get a domains cursor.
6366 val domainsCursor = domainsDatabaseHelper!!.domainNameCursorOrderedByDomain
6368 // Get the current count of domains.
6369 val domainsCount = domainsCursor.count
6371 // Get the domain name column index.
6372 val domainNameColumnIndex = domainsCursor.getColumnIndexOrThrow(DOMAIN_NAME)
6374 // Populate the domain settings set.
6375 for (i in 0 until domainsCount) {
6376 // Move the domains cursor to the current row.
6377 domainsCursor.moveToPosition(i)
6379 // Store the domain name in the domain settings set.
6380 domainsSettingsSet.add(domainsCursor.getString(domainNameColumnIndex))
6383 // Close the domains cursor.
6384 domainsCursor.close()
6387 override fun updateFontSize(dialogFragment: DialogFragment) {
6389 val dialog = dialogFragment.dialog!!
6391 // Get a handle for the font size edit text.
6392 val fontSizeEditText = dialog.findViewById<EditText>(R.id.font_size_edittext)
6394 // Initialize the new font size variable with the current font size.
6395 var newFontSize = currentWebView!!.settings.textZoom
6397 // Get the font size from the edit text.
6399 newFontSize = fontSizeEditText.text.toString().toInt()
6400 } catch (exception: Exception) {
6401 // If the edit text does not contain a valid font size do nothing.
6404 // Apply the new font size.
6405 currentWebView!!.settings.textZoom = newFontSize
6408 private fun updatePrivacyIcons(runInvalidateOptionsMenu: Boolean) {
6409 // Only update the privacy icons if the options menu and the current WebView have already been populated.
6410 if ((optionsMenu != null) && (currentWebView != null)) {
6411 // Update the privacy icon.
6412 if (currentWebView!!.settings.javaScriptEnabled) // JavaScript is enabled.
6413 optionsPrivacyMenuItem.setIcon(R.drawable.javascript_enabled)
6414 else if (currentWebView!!.acceptCookies) // JavaScript is disabled but cookies are enabled.
6415 optionsPrivacyMenuItem.setIcon(R.drawable.warning)
6416 else // All the dangerous features are disabled.
6417 optionsPrivacyMenuItem.setIcon(R.drawable.privacy_mode)
6419 // Update the cookies icon.
6420 if (currentWebView!!.acceptCookies)
6421 optionsCookiesMenuItem.setIcon(R.drawable.cookies_enabled)
6423 optionsCookiesMenuItem.setIcon(R.drawable.cookies_disabled)
6425 // Update the refresh icon.
6426 if (optionsRefreshMenuItem.title == getString(R.string.refresh)) // The refresh icon is displayed.
6427 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled)
6428 else // The stop icon is displayed.
6429 optionsRefreshMenuItem.setIcon(R.drawable.close_blue)
6431 // `invalidateOptionsMenu()` calls `onPrepareOptionsMenu()` and redraws the icons in the app bar.
6432 if (runInvalidateOptionsMenu)
6433 invalidateOptionsMenu()
6437 fun updateUrlEditTextAfterDelay() {
6438 // Create a handler to update the URL edit box.
6439 val urlEditTextUpdateHandler = Handler(Looper.getMainLooper())
6441 // Create a runnable to update the URL edit box.
6442 val urlEditTextUpdateRunnable = Runnable {
6443 // Update the URL edit text.
6444 urlEditText.setText(currentWebView!!.url)
6446 // Disable the wide viewport if the source is being viewed.
6447 if (currentWebView!!.url!!.startsWith("view-source:"))
6448 currentWebView!!.settings.useWideViewPort = false
6451 // Update the URL edit text after 50 milliseconds, so that the WebView has enough time to navigate to the new URL.
6452 urlEditTextUpdateHandler.postDelayed(urlEditTextUpdateRunnable, 50)