2 * Copyright 2015-2023 Soren Stoutner <soren@stoutner.com>.
4 * Download cookie code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
6 * This file is part of Privacy Browser Android <https://www.stoutner.com/privacy-browser-android>.
8 * Privacy Browser Android is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
13 * Privacy Browser Android is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with Privacy Browser Android. If not, see <http://www.gnu.org/licenses/>.
22 package com.stoutner.privacybrowser.activities
24 import android.animation.ObjectAnimator
25 import android.annotation.SuppressLint
26 import android.app.DownloadManager
27 import android.app.SearchManager
28 import android.content.ActivityNotFoundException
29 import android.content.BroadcastReceiver
30 import android.content.ClipData
31 import android.content.ClipboardManager
32 import android.content.Context
33 import android.content.Intent
34 import android.content.IntentFilter
35 import android.content.SharedPreferences
36 import android.content.pm.PackageManager
37 import android.content.res.Configuration
38 import android.database.Cursor
39 import android.graphics.Bitmap
40 import android.graphics.BitmapFactory
41 import android.graphics.Typeface
42 import android.graphics.drawable.BitmapDrawable
43 import android.net.Uri
44 import android.net.http.SslError
45 import android.os.Build
46 import android.os.Bundle
47 import android.os.Environment
48 import android.os.Handler
49 import android.os.Looper
50 import android.print.PrintManager
51 import android.provider.DocumentsContract
52 import android.provider.OpenableColumns
53 import android.text.Editable
54 import android.text.TextWatcher
55 import android.text.style.ForegroundColorSpan
56 import android.util.Patterns
57 import android.util.TypedValue
58 import android.view.ContextMenu
59 import android.view.GestureDetector
60 import android.view.KeyEvent
61 import android.view.Menu
62 import android.view.MenuItem
63 import android.view.MotionEvent
64 import android.view.View
65 import android.view.ViewGroup
66 import android.view.WindowManager
67 import android.view.inputmethod.InputMethodManager
68 import android.webkit.CookieManager
69 import android.webkit.HttpAuthHandler
70 import android.webkit.ValueCallback
71 import android.webkit.SslErrorHandler
72 import android.webkit.WebChromeClient
73 import android.webkit.WebResourceRequest
74 import android.webkit.WebResourceResponse
75 import android.webkit.WebSettings
76 import android.webkit.WebStorage
77 import android.webkit.WebView
78 import android.webkit.WebViewClient
79 import android.webkit.WebViewDatabase
80 import android.widget.AdapterView
81 import android.widget.ArrayAdapter
82 import android.widget.CheckBox
83 import android.widget.EditText
84 import android.widget.FrameLayout
85 import android.widget.ImageView
86 import android.widget.LinearLayout
87 import android.widget.ListView
88 import android.widget.ProgressBar
89 import android.widget.RadioButton
90 import android.widget.RelativeLayout
91 import android.widget.TextView
93 import androidx.activity.OnBackPressedCallback
94 import androidx.activity.result.contract.ActivityResultContracts
95 import androidx.appcompat.app.ActionBar
96 import androidx.appcompat.app.ActionBarDrawerToggle
97 import androidx.appcompat.app.AppCompatActivity
98 import androidx.appcompat.app.AppCompatDelegate
99 import androidx.appcompat.content.res.AppCompatResources
100 import androidx.appcompat.widget.Toolbar
101 import androidx.coordinatorlayout.widget.CoordinatorLayout
102 import androidx.core.content.ContextCompat
103 import androidx.core.view.GravityCompat
104 import androidx.cursoradapter.widget.CursorAdapter
105 import androidx.drawerlayout.widget.DrawerLayout
106 import androidx.fragment.app.DialogFragment
107 import androidx.preference.PreferenceManager
108 import androidx.recyclerview.widget.LinearLayoutManager
109 import androidx.recyclerview.widget.RecyclerView
110 import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
111 import androidx.viewpager2.widget.ViewPager2
112 import androidx.webkit.WebSettingsCompat
113 import androidx.webkit.WebViewFeature
115 import com.google.android.material.appbar.AppBarLayout
116 import com.google.android.material.floatingactionbutton.FloatingActionButton
117 import com.google.android.material.navigation.NavigationView
118 import com.google.android.material.snackbar.Snackbar
119 import com.google.android.material.tabs.TabLayout
121 import com.stoutner.privacybrowser.R
122 import com.stoutner.privacybrowser.adapters.WebViewStateAdapter
123 import com.stoutner.privacybrowser.coroutines.GetHostIpAddressesCoroutine
124 import com.stoutner.privacybrowser.coroutines.PopulateFilterListsCoroutine
125 import com.stoutner.privacybrowser.coroutines.PrepareSaveDialogCoroutine
126 import com.stoutner.privacybrowser.coroutines.SaveUrlCoroutine
127 import com.stoutner.privacybrowser.coroutines.SaveWebpageImageCoroutine
128 import com.stoutner.privacybrowser.dataclasses.PendingDialogDataClass
129 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog
130 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog
131 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog
132 import com.stoutner.privacybrowser.dialogs.FontSizeDialog
133 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog
134 import com.stoutner.privacybrowser.dialogs.OpenDialog
135 import com.stoutner.privacybrowser.dialogs.PinnedMismatchDialog
136 import com.stoutner.privacybrowser.dialogs.ProxyNotInstalledDialog
137 import com.stoutner.privacybrowser.dialogs.SaveDialog
138 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog
139 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog
140 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog
141 import com.stoutner.privacybrowser.dialogs.WaitingForProxyDialog
142 import com.stoutner.privacybrowser.fragments.WebViewTabFragment
143 import com.stoutner.privacybrowser.helpers.BOOKMARK_NAME
144 import com.stoutner.privacybrowser.helpers.BOOKMARK_URL
145 import com.stoutner.privacybrowser.helpers.COOKIES
146 import com.stoutner.privacybrowser.helpers.DARK_THEME
147 import com.stoutner.privacybrowser.helpers.DISABLED
148 import com.stoutner.privacybrowser.helpers.DISPLAY_IMAGES
149 import com.stoutner.privacybrowser.helpers.DOMAIN_NAME
150 import com.stoutner.privacybrowser.helpers.ENABLE_DOM_STORAGE
151 import com.stoutner.privacybrowser.helpers.ENABLE_EASYLIST
152 import com.stoutner.privacybrowser.helpers.ENABLE_EASYPRIVACY
153 import com.stoutner.privacybrowser.helpers.ENABLE_FANBOYS_ANNOYANCE_LIST
154 import com.stoutner.privacybrowser.helpers.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST
155 import com.stoutner.privacybrowser.helpers.ENABLE_FORM_DATA
156 import com.stoutner.privacybrowser.helpers.ENABLE_JAVASCRIPT
157 import com.stoutner.privacybrowser.helpers.ENABLE_ULTRAPRIVACY
158 import com.stoutner.privacybrowser.helpers.ENABLED
159 import com.stoutner.privacybrowser.helpers.FAVORITE_ICON
160 import com.stoutner.privacybrowser.helpers.FOLDER_ID
161 import com.stoutner.privacybrowser.helpers.FONT_SIZE
162 import com.stoutner.privacybrowser.helpers.ID
163 import com.stoutner.privacybrowser.helpers.IP_ADDRESSES
164 import com.stoutner.privacybrowser.helpers.IS_FOLDER
165 import com.stoutner.privacybrowser.helpers.LIGHT_THEME
166 import com.stoutner.privacybrowser.helpers.PINNED_IP_ADDRESSES
167 import com.stoutner.privacybrowser.helpers.PINNED_SSL_CERTIFICATE
168 import com.stoutner.privacybrowser.helpers.REQUEST_ALLOWED
169 import com.stoutner.privacybrowser.helpers.REQUEST_BLOCKED
170 import com.stoutner.privacybrowser.helpers.REQUEST_DEFAULT
171 import com.stoutner.privacybrowser.helpers.REQUEST_THIRD_PARTY
172 import com.stoutner.privacybrowser.helpers.SSL_ISSUED_BY_COMMON_NAME
173 import com.stoutner.privacybrowser.helpers.SSL_ISSUED_BY_ORGANIZATION
174 import com.stoutner.privacybrowser.helpers.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT
175 import com.stoutner.privacybrowser.helpers.SSL_ISSUED_TO_COMMON_NAME
176 import com.stoutner.privacybrowser.helpers.SSL_ISSUED_TO_ORGANIZATION
177 import com.stoutner.privacybrowser.helpers.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT
178 import com.stoutner.privacybrowser.helpers.SWIPE_TO_REFRESH
179 import com.stoutner.privacybrowser.helpers.SYSTEM_DEFAULT
180 import com.stoutner.privacybrowser.helpers.WEBVIEW_THEME
181 import com.stoutner.privacybrowser.helpers.WIDE_VIEWPORT
182 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper
183 import com.stoutner.privacybrowser.helpers.CheckFilterListHelper
184 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper
185 import com.stoutner.privacybrowser.helpers.ProxyHelper
186 import com.stoutner.privacybrowser.helpers.SanitizeUrlHelper
187 import com.stoutner.privacybrowser.helpers.UrlHelper
188 import com.stoutner.privacybrowser.views.BLOCKED_REQUESTS
189 import com.stoutner.privacybrowser.views.EASYLIST
190 import com.stoutner.privacybrowser.views.EASYPRIVACY
191 import com.stoutner.privacybrowser.views.FANBOYS_ANNOYANCE_LIST
192 import com.stoutner.privacybrowser.views.FANBOYS_SOCIAL_BLOCKING_LIST
193 import com.stoutner.privacybrowser.views.THIRD_PARTY_REQUESTS
194 import com.stoutner.privacybrowser.views.ULTRAPRIVACY
195 import com.stoutner.privacybrowser.views.NestedScrollWebView
197 import kotlinx.coroutines.CoroutineScope
198 import kotlinx.coroutines.Dispatchers
199 import kotlinx.coroutines.launch
200 import kotlinx.coroutines.withContext
202 import java.io.ByteArrayInputStream
203 import java.io.ByteArrayOutputStream
205 import java.io.FileInputStream
206 import java.io.FileOutputStream
207 import java.io.IOException
208 import java.io.UnsupportedEncodingException
210 import java.net.MalformedURLException
212 import java.net.URLDecoder
213 import java.net.URLEncoder
215 import java.text.NumberFormat
217 import java.util.ArrayList
218 import java.util.Date
219 import java.util.concurrent.Executors
220 import kotlin.system.exitProcess
222 // Define the public constants
223 const val CURRENT_URL = "current_url"
224 const val DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0
225 const val DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2
226 const val DOMAINS_CUSTOM_USER_AGENT = 12
227 const val SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1
228 const val SETTINGS_CUSTOM_USER_AGENT = 11
229 const val UNRECOGNIZED_USER_AGENT = -1
231 // Define the private class constants.
232 private const val BOOKMARKS_DRAWER_PINNED = "bookmarks_drawer_pinned"
233 private const val PROXY_MODE = "proxy_mode"
234 private const val SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST = "saved_nested_scroll_webview_state_array_list"
235 private const val SAVED_STATE_ARRAY_LIST = "saved_state_array_list"
236 private const val SAVED_TAB_POSITION = "saved_tab_position"
237 private const val TEMPORARY_MHT_FILE = "temporary_mht_file"
239 class MainWebViewActivity : AppCompatActivity(), CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener, FontSizeDialog.UpdateFontSizeListener,
240 NavigationView.OnNavigationItemSelectedListener, OpenDialog.OpenListener, PinnedMismatchDialog.PinnedMismatchListener, PopulateFilterListsCoroutine.PopulateFilterListsListener, SaveDialog.SaveListener,
241 UrlHistoryDialog.NavigateHistoryListener, WebViewTabFragment.NewTabListener {
244 // Define the public static variables.
245 var currentBookmarksFolderId = 0L
246 val executorService = Executors.newFixedThreadPool(4)!!
247 var orbotStatus = "unknown"
248 val pendingDialogsArrayList = ArrayList<PendingDialogDataClass>()
249 var proxyMode = ProxyHelper.NONE
250 var restartFromBookmarksActivity = false
251 var webViewStateAdapter: WebViewStateAdapter? = null
253 // Declare the public static variables.
254 lateinit var appBarLayout: AppBarLayout
257 // Declare the class variables.
258 private lateinit var appBar: ActionBar
259 private lateinit var checkFilterListHelper: CheckFilterListHelper
260 private lateinit var bookmarksCursorAdapter: CursorAdapter
261 private lateinit var bookmarksListView: ListView
262 private lateinit var bookmarksDrawerPinnedImageView: ImageView
263 private lateinit var bookmarksTitleTextView: TextView
264 private lateinit var coordinatorLayout: CoordinatorLayout
265 private lateinit var cookieManager: CookieManager
266 private lateinit var defaultFontSizeString: String
267 private lateinit var defaultUserAgentName: String
268 private lateinit var defaultWebViewTheme: String
269 private lateinit var domainsSettingsSet: MutableSet<String>
270 private lateinit var drawerLayout: DrawerLayout
271 private lateinit var easyList: ArrayList<List<Array<String>>>
272 private lateinit var easyPrivacy: ArrayList<List<Array<String>>>
273 private lateinit var fanboysAnnoyanceList: ArrayList<List<Array<String>>>
274 private lateinit var fanboysSocialList: ArrayList<List<Array<String>>>
275 private lateinit var fileChooserCallback: ValueCallback<Array<Uri>>
276 private lateinit var finalGrayColorSpan: ForegroundColorSpan
277 private lateinit var findOnPageCountTextView: TextView
278 private lateinit var findOnPageEditText: EditText
279 private lateinit var findOnPageLinearLayout: LinearLayout
280 private lateinit var fullScreenVideoFrameLayout: FrameLayout
281 private lateinit var initialGrayColorSpan: ForegroundColorSpan
282 private lateinit var navigationBackMenuItem: MenuItem
283 private lateinit var navigationForwardMenuItem: MenuItem
284 private lateinit var navigationHistoryMenuItem: MenuItem
285 private lateinit var navigationRequestsMenuItem: MenuItem
286 private lateinit var navigationScrollToBottomMenuItem: MenuItem
287 private lateinit var navigationView: NavigationView
288 private lateinit var optionsAddOrEditDomainMenuItem: MenuItem
289 private lateinit var optionsBlockAllThirdPartyRequestsMenuItem: MenuItem
290 private lateinit var optionsClearCookiesMenuItem: MenuItem
291 private lateinit var optionsClearDataMenuItem: MenuItem
292 private lateinit var optionsClearDomStorageMenuItem: MenuItem
293 private lateinit var optionsClearFormDataMenuItem: MenuItem
294 private lateinit var optionsCookiesMenuItem: MenuItem
295 private lateinit var optionsDarkWebViewMenuItem: MenuItem
296 private lateinit var optionsDisplayImagesMenuItem: MenuItem
297 private lateinit var optionsDomStorageMenuItem: MenuItem
298 private lateinit var optionsEasyListMenuItem: MenuItem
299 private lateinit var optionsEasyPrivacyMenuItem: MenuItem
300 private lateinit var optionsFanboysAnnoyanceListMenuItem: MenuItem
301 private lateinit var optionsFanboysSocialBlockingListMenuItem: MenuItem
302 private lateinit var optionsFilterListsMenuItem: MenuItem
303 private lateinit var optionsFontSizeMenuItem: MenuItem
304 private lateinit var optionsPrivacyMenuItem: MenuItem
305 private lateinit var optionsProxyCustomMenuItem: MenuItem
306 private lateinit var optionsProxyI2pMenuItem: MenuItem
307 private lateinit var optionsProxyMenuItem: MenuItem
308 private lateinit var optionsProxyNoneMenuItem: MenuItem
309 private lateinit var optionsProxyTorMenuItem: MenuItem
310 private lateinit var optionsRefreshMenuItem: MenuItem
311 private lateinit var optionsSaveFormDataMenuItem: MenuItem
312 private lateinit var optionsSwipeToRefreshMenuItem: MenuItem
313 private lateinit var optionsUltraListMenuItem: MenuItem
314 private lateinit var optionsUltraPrivacyMenuItem: MenuItem
315 private lateinit var optionsUserAgentChromeOnAndroidMenuItem: MenuItem
316 private lateinit var optionsUserAgentChromeOnWindowsMenuItem: MenuItem
317 private lateinit var optionsUserAgentChromiumOnLinuxMenuItem: MenuItem
318 private lateinit var optionsUserAgentCustomMenuItem: MenuItem
319 private lateinit var optionsUserAgentEdgeOnWindowsMenuItem: MenuItem
320 private lateinit var optionsUserAgentFirefoxOnAndroidMenuItem: MenuItem
321 private lateinit var optionsUserAgentFirefoxOnLinuxMenuItem: MenuItem
322 private lateinit var optionsUserAgentFirefoxOnWindowsMenuItem: MenuItem
323 private lateinit var optionsUserAgentMenuItem: MenuItem
324 private lateinit var optionsUserAgentPrivacyBrowserMenuItem: MenuItem
325 private lateinit var optionsUserAgentSafariOnIosMenuItem: MenuItem
326 private lateinit var optionsUserAgentSafariOnMacosMenuItem: MenuItem
327 private lateinit var optionsUserAgentWebViewDefaultMenuItem: MenuItem
328 private lateinit var optionsViewSourceMenuItem: MenuItem
329 private lateinit var optionsWideViewportMenuItem: MenuItem
330 private lateinit var proxyHelper: ProxyHelper
331 private lateinit var redColorSpan: ForegroundColorSpan
332 private lateinit var rootFrameLayout: FrameLayout
333 private lateinit var saveUrlString: String
334 private lateinit var searchURL: String
335 private lateinit var sharedPreferences: SharedPreferences
336 private lateinit var swipeRefreshLayout: SwipeRefreshLayout
337 private lateinit var tabLayout: TabLayout
338 private lateinit var tabsLinearLayout: LinearLayout
339 private lateinit var toolbar: Toolbar
340 private lateinit var webViewDefaultUserAgent: String
341 private lateinit var webViewThemeEntryValuesStringArray: Array<String>
342 private lateinit var webViewViewPager2: ViewPager2
343 private lateinit var ultraList: ArrayList<List<Array<String>>>
344 private lateinit var urlEditText: EditText
345 private lateinit var urlRelativeLayout: RelativeLayout
346 private lateinit var userAgentDataArray: Array<String>
347 private lateinit var userAgentNamesArray: Array<String>
348 private lateinit var userAgentDataArrayAdapter: ArrayAdapter<CharSequence>
349 private lateinit var userAgentNamesArrayAdapter: ArrayAdapter<CharSequence>
351 // Define the class variables.
352 private var actionBarDrawerToggle: ActionBarDrawerToggle? = null
353 private var appBarHeight = 0
354 private var bookmarksCursor: Cursor? = null
355 private var bookmarksDatabaseHelper: BookmarksDatabaseHelper? = null
356 private var bookmarksDrawerPinned = false
357 private var bottomAppBar = false
358 private var currentWebView: NestedScrollWebView? = null
359 private var defaultBlockAllThirdPartyRequests = false
360 private var defaultCookies = false
361 private var defaultDisplayWebpageImages = true
362 private var defaultDomStorage = false
363 private var defaultEasyList = true
364 private var defaultEasyPrivacy = true
365 private var defaultFanboysAnnoyanceList = true
366 private var defaultFanboysSocialBlockingList = true
367 private var defaultFormData = false // Form data can be removed once the minimum API >= 26.
368 private var defaultProgressViewEndOffset = 0
369 private var defaultProgressViewStartOffset = 0
370 private var defaultJavaScript = false
371 private var defaultSwipeToRefresh = true
372 private var defaultUltraList = true
373 private var defaultUltraPrivacy = true
374 private var defaultWideViewport = true
375 private var displayAdditionalAppBarIcons = false
376 private var displayingFullScreenVideo = false
377 private var domainsDatabaseHelper: DomainsDatabaseHelper? = null
378 private var downloadWithExternalApp = false
379 private var fullScreenBrowsingModeEnabled = false
380 private var hideAppBar = true
381 private var inFullScreenBrowsingMode = false
382 private var incognitoModeEnabled = false
383 private var loadingNewIntent = false
384 private var navigationDrawerFirstView = true
385 private var objectAnimator = ObjectAnimator()
386 private var optionsMenu: Menu? = null
387 private var orbotStatusBroadcastReceiver: BroadcastReceiver? = null
388 private var reapplyAppSettingsOnRestart = false
389 private var reapplyDomainSettingsOnRestart = false
390 private var sanitizeAmpRedirects = false
391 private var sanitizeTrackingQueries = false
392 private var savedProxyMode: String? = null
393 private var savedNestedScrollWebViewStateArrayList: ArrayList<Bundle>? = null
394 private var savedStateArrayList: ArrayList<Bundle>? = null
395 private var savedTabPosition = 0
396 private var scrollAppBar = false
397 private var ultraPrivacy: ArrayList<List<Array<String>>>? = null
398 private var waitingForProxy = false
400 // Define the save webpage image activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
401 private val browseFileUploadActivityResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { activityResult ->
402 // Pass the file to the WebView.
403 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(activityResult.resultCode, activityResult.data))
406 // Define the save URL activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
407 private val saveUrlActivityResultLauncher = registerForActivityResult<String, Uri>(ActivityResultContracts.CreateDocument("*/*")) { fileUri ->
408 // Only save the URL if the file URI is not null, which happens if the user exited the file picker by pressing back.
409 if (fileUri != null) {
410 // Instantiate the save URL coroutine.
411 val saveUrlCoroutine = SaveUrlCoroutine()
414 saveUrlCoroutine.save(this, this, saveUrlString, fileUri, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
417 // Reset the save URL string.
421 // Define the save webpage archive activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
422 private val saveWebpageArchiveActivityResultLauncher = registerForActivityResult<String, Uri>(ActivityResultContracts.CreateDocument("multipart/related")) { fileUri ->
423 // Only save the webpage archive if the file URI is not null, which happens if the user exited the file picker by pressing back.
424 if (fileUri != null) {
425 // Initialize the file name string from the file URI last path segment.
426 var fileNameString = fileUri.lastPathSegment
428 // Query the exact file name if the API >= 26.
429 if (Build.VERSION.SDK_INT >= 26) {
430 // Get a cursor from the content resolver.
431 val contentResolverCursor = contentResolver.query(fileUri, null, null, null)!!
433 // Move to the fist row.
434 contentResolverCursor.moveToFirst()
436 // Get the file name from the cursor.
437 fileNameString = contentResolverCursor.getString(contentResolverCursor.getColumnIndexOrThrow(OpenableColumns.DISPLAY_NAME))
440 contentResolverCursor.close()
443 // Use a coroutine to save the file.
444 CoroutineScope(Dispatchers.Main).launch {
446 // Create the file on the IO thread.
447 withContext(Dispatchers.IO) {
448 // Create a temporary MHT file.
449 val temporaryMhtFile = File.createTempFile(TEMPORARY_MHT_FILE, ".mht", cacheDir)
451 // The WebView must be accessed from the main thread.
452 withContext(Dispatchers.Main) {
453 currentWebView!!.saveWebArchive(temporaryMhtFile.toString(), false) { callbackValue ->
454 if (callbackValue != null) { // The temporary MHT file was saved successfully.
456 // Create a temporary MHT file input stream.
457 val temporaryMhtFileInputStream = FileInputStream(temporaryMhtFile)
459 // Get an output stream for the save webpage file path.
460 val mhtOutputStream = contentResolver.openOutputStream(fileUri)!!
462 // Create a transfer byte array.
463 val transferByteArray = ByteArray(1024)
465 // Create an integer to track the number of bytes read.
468 // Copy the temporary MHT file input stream to the MHT output stream.
469 while (temporaryMhtFileInputStream.read(transferByteArray).also { bytesRead = it } > 0)
470 mhtOutputStream.write(transferByteArray, 0, bytesRead)
472 // Close the streams.
473 mhtOutputStream.close()
474 temporaryMhtFileInputStream.close()
476 // Display a snackbar.
477 Snackbar.make(currentWebView!!, getString(R.string.saved, fileNameString), Snackbar.LENGTH_SHORT).show()
478 } catch (exception: Exception) {
479 // Display snackbar with the exception.
480 Snackbar.make(currentWebView!!, getString(R.string.error_saving_file, fileNameString, exception), Snackbar.LENGTH_INDEFINITE).show()
482 // Delete the temporary MHT file.
483 temporaryMhtFile.delete()
485 } else { // There was an unspecified error while saving the temporary MHT file.
486 // Display a snackbar.
487 Snackbar.make(currentWebView!!, getString(R.string.error_saving_file, fileNameString, getString(R.string.unknown_error)), Snackbar.LENGTH_INDEFINITE).show()
492 } catch (ioException: IOException) {
493 // Display a snackbar with the IO exception.
494 Snackbar.make(currentWebView!!, getString(R.string.error_saving_file, fileNameString, ioException), Snackbar.LENGTH_INDEFINITE).show()
500 // Define the save webpage image activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
501 private val saveWebpageImageActivityResultLauncher = registerForActivityResult<String, Uri>(ActivityResultContracts.CreateDocument("image/png")) { fileUri ->
502 // Only save the webpage image if the file URI is not null, which happens if the user exited the file picker by pressing back.
503 if (fileUri != null) {
504 // Instantiate the save webpage image coroutine.
505 val saveWebpageImageCoroutine = SaveWebpageImageCoroutine()
507 // Save the webpage image.
508 saveWebpageImageCoroutine.save(this, fileUri, currentWebView!!)
512 override fun onCreate(savedInstanceState: Bundle?) {
513 // Run the default commands.
514 super.onCreate(savedInstanceState)
516 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
517 PreferenceManager.setDefaultValues(this, R.xml.preferences, false)
519 // Get a handle for the shared preferences.
520 sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
522 // Get the preferences.
523 val appTheme = sharedPreferences.getString(getString(R.string.app_theme_key), getString(R.string.app_theme_default_value))
524 val allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false)
525 bottomAppBar = sharedPreferences.getBoolean(getString(R.string.bottom_app_bar_key), false)
526 displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false)
527 val displayUnderCutouts = sharedPreferences.getBoolean(getString(R.string.display_under_cutouts_key), false)
529 // 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.
530 if (displayUnderCutouts) {
531 if (Build.VERSION.SDK_INT >= 30)
532 window.attributes.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS
533 else if (Build.VERSION.SDK_INT >= 28)
534 window.attributes.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
537 // Get the theme entry values string array.
538 val appThemeEntryValuesStringArray = resources.getStringArray(R.array.app_theme_entry_values)
540 // Get the current theme status.
541 val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
543 // 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.
544 if (appTheme == appThemeEntryValuesStringArray[1]) { // The light theme is selected.
545 // Apply the light theme.
546 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
547 } else if (appTheme == appThemeEntryValuesStringArray[2]) { // The dark theme is selected.
548 // Apply the dark theme.
549 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
550 } else { // The system default theme is selected.
551 if (Build.VERSION.SDK_INT >= 28) { // The system default theme is supported.
552 // Follow the system default theme.
553 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
554 } else { // The system default theme is not supported.
555 // Follow the battery saver mode.
556 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY)
560 // Do not continue if the app theme is different than the OS theme. The app always initially starts in the OS theme.
561 // 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.
562 // 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.
563 // See https://redmine.stoutner.com/issues/952.
564 if ((appTheme == appThemeEntryValuesStringArray[0]) || // The system default theme is used.
565 ((appTheme == appThemeEntryValuesStringArray[1]) && (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO)) || // The app is running in day theme as desired.
566 ((appTheme == appThemeEntryValuesStringArray[2]) && (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES))) { // The app is running in night theme as desired.
568 // Disable screenshots if not allowed.
569 if (!allowScreenshots) {
570 window.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
573 // Check to see if the activity has been restarted.
574 if (savedInstanceState != null) {
575 // Store the saved instance state variables. The deprecated `getParcelableArrayList` can be upgraded once the minimum API >= 33.
576 bookmarksDrawerPinned = savedInstanceState.getBoolean(BOOKMARKS_DRAWER_PINNED)
577 @Suppress("DEPRECATION")
578 savedStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_STATE_ARRAY_LIST)
579 @Suppress("DEPRECATION")
580 savedNestedScrollWebViewStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST)
581 savedTabPosition = savedInstanceState.getInt(SAVED_TAB_POSITION)
582 savedProxyMode = savedInstanceState.getString(PROXY_MODE)
585 // 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.
586 WebView.enableSlowWholeDocumentDraw()
588 // Set the content view according to the position of the app bar.
590 setContentView(R.layout.main_framelayout_bottom_appbar)
592 setContentView(R.layout.main_framelayout_top_appbar)
594 // Get handles for the views.
595 rootFrameLayout = findViewById(R.id.root_framelayout)
596 drawerLayout = findViewById(R.id.drawerlayout)
597 coordinatorLayout = findViewById(R.id.coordinatorlayout)
598 appBarLayout = findViewById(R.id.appbar_layout)
599 toolbar = findViewById(R.id.toolbar)
600 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout)
601 findOnPageEditText = findViewById(R.id.find_on_page_edittext)
602 findOnPageCountTextView = findViewById(R.id.find_on_page_count_textview)
603 tabsLinearLayout = findViewById(R.id.tabs_linearlayout)
604 tabLayout = findViewById(R.id.tablayout)
605 swipeRefreshLayout = findViewById(R.id.swiperefreshlayout)
606 webViewViewPager2 = findViewById(R.id.webview_viewpager2)
607 navigationView = findViewById(R.id.navigationview)
608 bookmarksListView = findViewById(R.id.bookmarks_drawer_listview)
609 bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview)
610 bookmarksDrawerPinnedImageView = findViewById(R.id.bookmarks_drawer_pinned_imageview)
611 fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout)
613 // Get a handle for the navigation menu.
614 val navigationMenu = navigationView.menu
616 // Get handles for the navigation menu items.
617 navigationBackMenuItem = navigationMenu.findItem(R.id.back)
618 navigationForwardMenuItem = navigationMenu.findItem(R.id.forward)
619 navigationScrollToBottomMenuItem = navigationMenu.findItem(R.id.scroll_to_bottom)
620 navigationHistoryMenuItem = navigationMenu.findItem(R.id.history)
621 navigationRequestsMenuItem = navigationMenu.findItem(R.id.requests)
623 // Listen for touches on the navigation menu.
624 navigationView.setNavigationItemSelectedListener(this)
626 // Set the support action bar.
627 setSupportActionBar(toolbar)
629 // Get a handle for the app bar.
630 appBar = supportActionBar!!
632 // Set the custom app bar layout, which shows the URL text bar.
633 appBar.setCustomView(R.layout.url_app_bar)
635 // Display the custom app bar layout.
636 appBar.displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM
638 // Get handles for the views in the URL app bar.
639 urlRelativeLayout = findViewById(R.id.url_relativelayout)
640 urlEditText = findViewById(R.id.url_edittext)
642 // Create the hamburger icon at the start of the AppBar.
643 actionBarDrawerToggle = ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer)
645 // Initially disable the sliding drawers. They will be enabled once the filter lists are loaded.
646 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
648 // Initially hide the user interface so that only the filter list loading screen is shown (if reloading).
649 drawerLayout.visibility = View.GONE
651 // Initialize the WebView state adapter.
652 webViewStateAdapter = WebViewStateAdapter(this)
654 // Set the pager adapter on the web view pager.
655 webViewViewPager2.adapter = webViewStateAdapter
657 // Store up to 100 tabs in memory.
658 webViewViewPager2.offscreenPageLimit = 100
660 // Disable swiping between pages in the view pager.
661 webViewViewPager2.isUserInputEnabled = false
663 // Get a handle for the cookie manager.
664 cookieManager = CookieManager.getInstance()
666 // Instantiate the helpers.
667 bookmarksDatabaseHelper = BookmarksDatabaseHelper(this)
668 domainsDatabaseHelper = DomainsDatabaseHelper(this)
669 proxyHelper = ProxyHelper()
671 // Update the bookmarks drawer pinned image view.
672 updateBookmarksDrawerPinnedImageView()
674 // Initialize the app.
677 // Apply the app settings from the shared preferences.
680 // Control what the system back command does.
681 val onBackPressedCallback: OnBackPressedCallback = object : OnBackPressedCallback(true) {
682 override fun handleOnBackPressed() {
683 // Process the different back options.
684 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
685 // Close the navigation drawer.
686 drawerLayout.closeDrawer(GravityCompat.START)
687 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)) { // The bookmarks drawer is open.
688 // close the bookmarks drawer.
689 drawerLayout.closeDrawer(GravityCompat.END)
690 } else if (displayingFullScreenVideo) { // A full screen video is shown.
691 // Exit the full screen video.
692 exitFullScreenVideo()
693 // It shouldn't be possible for the currentWebView to be null, but crash logs indicate it sometimes happens.
694 } else if (currentWebView != null && currentWebView!!.canGoBack()) { // There is at least one item in the current WebView history.
695 // Get the current web back forward list.
696 val webBackForwardList = currentWebView!!.copyBackForwardList()
698 // Get the previous entry data.
699 val previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex - 1).url
700 val previousFavoriteIcon = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex - 1).favicon
702 // Apply the domain settings.
703 applyDomainSettings(currentWebView!!, previousUrl, resetTab = false, reloadWebsite = false, loadUrl = false)
705 // Get the current tab.
706 val tab = tabLayout.getTabAt(tabLayout.selectedTabPosition)!!
708 // Get the custom view from the tab.
709 val tabView = tab.customView!!
711 // Get the favorite icon image view from the tab.
712 val tabFavoriteIconImageView = tabView.findViewById<ImageView>(R.id.favorite_icon_imageview)
714 // Set the previous favorite icon if it isn't null.
715 if (previousFavoriteIcon != null)
716 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(previousFavoriteIcon, 64, 64, true))
719 currentWebView!!.goBack()
721 // Update the URL edit text after a delay.
722 updateUrlEditTextAfterDelay()
723 } else { // Close the current tab.
724 // A view is required because the method is also called by an XML `onClick`.
730 // Register the on back pressed callback.
731 onBackPressedDispatcher.addCallback(this, onBackPressedCallback)
733 // Instantiate the populate filter lists coroutine.
734 val populateFilterListsCoroutine = PopulateFilterListsCoroutine(this)
736 // Populate the filter lists.
737 populateFilterListsCoroutine.populateFilterLists(this)
741 public override fun onPostCreate(savedInstanceState: Bundle?) {
742 // Run the default commands.
743 super.onPostCreate(savedInstanceState)
745 // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished. This creates the navigation drawer icon.
746 // If the app is restarting to change the app theme the action bar drawer toggle will not yet be populated.
747 actionBarDrawerToggle?.syncState()
750 override fun onNewIntent(intent: Intent) {
751 // Run the default commands.
752 super.onNewIntent(intent)
754 // Close the navigation drawer if it is open.
755 if (drawerLayout.isDrawerVisible(GravityCompat.START))
756 drawerLayout.closeDrawer(GravityCompat.START)
758 // Close the bookmarks drawer if it is open.
759 if (drawerLayout.isDrawerVisible(GravityCompat.END))
760 drawerLayout.closeDrawer(GravityCompat.END)
762 // Get the information from the intent.
763 val intentAction = intent.action
764 val intentUriData = intent.data
765 val intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT)
767 // Determine if this is a web search.
768 val isWebSearch = (intentAction != null) && (intentAction == Intent.ACTION_WEB_SEARCH)
770 // Check to see if the app is being restarted from a saved state.
771 if (ultraPrivacy != null) { // The activity is not being restarted from a saved state.
772 // 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.
773 if ((intentUriData != null) || (intentStringExtra != null) || isWebSearch) {
774 // Exit the full screen video if it is displayed.
775 if (displayingFullScreenVideo) {
776 // Exit full screen video mode.
777 exitFullScreenVideo()
779 // Reload the current WebView. Otherwise, it can display entirely black.
780 currentWebView!!.reload()
784 val url = if (isWebSearch) { // The intent is a web search.
785 // Sanitize the search input and convert it to a search.
786 val encodedSearchString = try {
787 URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8")
788 } catch (exception: UnsupportedEncodingException) {
792 // Add the base search URL.
793 searchURL + encodedSearchString
794 } else { // The intent contains a URL in either the data or an extra.
795 intentUriData?.toString() ?: intentStringExtra
798 // Add a new tab if specified in the preferences.
799 if (sharedPreferences.getBoolean(getString(R.string.open_intents_in_new_tab_key), true)) { // Load the URL in a new tab.
800 // Set the loading new intent flag.
801 loadingNewIntent = true
804 addNewPage(url!!, adjacent = false, moveToTab = true)
805 } else { // Load the URL in the current tab.
807 loadUrl(currentWebView!!, url!!)
810 } else { // The app has been restarted.
811 // Replace the intent that started the app with this one. This will load the tab after the others have been restored.
816 public override fun onRestart() {
817 // Run the default commands.
820 // Apply the app settings if returning from the Settings activity.
821 if (reapplyAppSettingsOnRestart) {
822 // Reset the reapply app settings on restart flag.
823 reapplyAppSettingsOnRestart = false
825 // Apply the app settings.
829 // Apply the domain settings if returning from the settings or domains activity.
830 if (reapplyDomainSettingsOnRestart) {
831 // Reset the reapply domain settings on restart flag.
832 reapplyDomainSettingsOnRestart = false
834 // Update the domains settings set.
835 updateDomainsSettingsSet()
837 // Reapply the domain settings for each tab.
838 for (i in 0 until webViewStateAdapter!!.itemCount) {
839 // Get the WebView tab fragment.
840 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
842 // Get the fragment view.
843 val fragmentView = webViewTabFragment.view
845 // Only reload the WebViews if they exist.
846 if (fragmentView != null) {
847 // Get the nested scroll WebView from the tab fragment.
848 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
850 // Reset the current domain name so the domain settings will be reapplied.
851 nestedScrollWebView.currentDomainName = ""
853 // Reapply the domain settings if the URL is not null, which happens for empty tabs when returning from settings.
854 if (nestedScrollWebView.url != null)
855 applyDomainSettings(nestedScrollWebView, nestedScrollWebView.url, resetTab = false, reloadWebsite = true, loadUrl = false)
860 // Update the bookmarks drawer if returning from the Bookmarks activity.
861 if (restartFromBookmarksActivity) {
862 // Reset the restart from bookmarks activity flag.
863 restartFromBookmarksActivity = false
865 // Close the bookmarks drawer.
866 drawerLayout.closeDrawer(GravityCompat.END)
868 // Reload the bookmarks drawer.
869 loadBookmarksFolder()
872 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
873 updatePrivacyIcons(true)
876 // `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.
877 public override fun onStart() {
878 // Run the default commands.
881 // 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.
882 if (webViewStateAdapter != null) {
883 for (i in 0 until webViewStateAdapter!!.itemCount) {
884 // Get the WebView tab fragment.
885 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
887 // Get the fragment view.
888 val fragmentView = webViewTabFragment.view
890 // Only resume the WebViews if they exist (they won't when the app is first created).
891 if (fragmentView != null) {
892 // Get the nested scroll WebView from the tab fragment.
893 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
895 // Resume the nested scroll WebView.
896 nestedScrollWebView.onResume()
901 // Resume the nested scroll WebView JavaScript timers. This is a global command that resumes JavaScript timers on all WebViews.
902 if (currentWebView != null)
903 currentWebView!!.resumeTimers()
905 // Reapply the proxy settings if the system is using a proxy. This redisplays the appropriate alert dialog.
906 if (proxyMode != ProxyHelper.NONE)
909 // Reapply any system UI flags.
910 if (displayingFullScreenVideo || inFullScreenBrowsingMode) { // The system is displaying a website or a video in full screen mode.
911 /* Hide the system bars.
912 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
913 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
914 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
915 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
918 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
919 @Suppress("DEPRECATION")
920 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
923 // Show any pending dialogs.
924 for (i in pendingDialogsArrayList.indices) {
925 // Get the pending dialog from the array list.
926 val (dialogFragment, tag) = pendingDialogsArrayList[i]
928 // Show the pending dialog.
929 dialogFragment.show(supportFragmentManager, tag)
932 // Clear the pending dialogs array list.
933 pendingDialogsArrayList.clear()
936 public override fun onSaveInstanceState(savedInstanceState: Bundle) {
937 // Run the default commands.
938 super.onSaveInstanceState(savedInstanceState)
940 // 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.
941 if (webViewStateAdapter != null) {
942 // Initialize the saved state array lists.
943 savedStateArrayList = ArrayList<Bundle>()
944 savedNestedScrollWebViewStateArrayList = ArrayList<Bundle>()
946 // Get the URLs from each tab.
947 for (i in 0 until webViewStateAdapter!!.itemCount) {
948 // Get the WebView tab fragment.
949 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
951 // Get the fragment view.
952 val fragmentView = webViewTabFragment.view
954 // Save the fragment state if it is not null.
955 if (fragmentView != null) {
956 // Get the nested scroll WebView from the tab fragment.
957 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
959 // Create the saved state bundle.
960 val savedStateBundle = Bundle()
962 // Get the current states.
963 nestedScrollWebView.saveState(savedStateBundle)
964 val savedNestedScrollWebViewStateBundle = nestedScrollWebView.saveNestedScrollWebViewState()
966 // Store the saved states in the array lists.
967 savedStateArrayList!!.add(savedStateBundle)
968 savedNestedScrollWebViewStateArrayList!!.add(savedNestedScrollWebViewStateBundle)
972 // Get the current tab position.
973 val currentTabPosition = tabLayout.selectedTabPosition
975 // Store the saved states in the bundle.
976 savedInstanceState.putBoolean(BOOKMARKS_DRAWER_PINNED, bookmarksDrawerPinned)
977 savedInstanceState.putString(PROXY_MODE, proxyMode)
978 savedInstanceState.putParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST, savedNestedScrollWebViewStateArrayList)
979 savedInstanceState.putParcelableArrayList(SAVED_STATE_ARRAY_LIST, savedStateArrayList)
980 savedInstanceState.putInt(SAVED_TAB_POSITION, currentTabPosition)
984 // `onStop()` runs after `onPause()`. It is used instead of `onPause()` so the commands are not called every time the screen is partially hidden.
985 public override fun onStop() {
986 // Run the default commands.
989 // 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.
990 if (webViewStateAdapter != null) {
991 // Pause each web view.
992 for (i in 0 until webViewStateAdapter!!.itemCount) {
993 // Get the WebView tab fragment.
994 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
996 // Get the fragment view.
997 val fragmentView = webViewTabFragment.view
999 // Only pause the WebViews if they exist (they won't when the app is first created).
1000 if (fragmentView != null) {
1001 // Get the nested scroll WebView from the tab fragment.
1002 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
1004 // Pause the nested scroll WebView.
1005 nestedScrollWebView.onPause()
1010 // Pause the WebView JavaScript timers. This is a global command that pauses JavaScript on all WebViews.
1011 if (currentWebView != null)
1012 currentWebView!!.pauseTimers()
1015 public override fun onDestroy() {
1016 // Unregister the orbot status broadcast receiver if it exists.
1017 if (orbotStatusBroadcastReceiver != null) {
1018 unregisterReceiver(orbotStatusBroadcastReceiver)
1021 // Close the bookmarks cursor if it exists.
1022 bookmarksCursor?.close()
1024 // Close the databases if they exist.
1025 bookmarksDatabaseHelper?.close()
1026 domainsDatabaseHelper?.close()
1028 // Run the default commands.
1032 override fun onConfigurationChanged(newConfig: Configuration) {
1033 // Run the default commands.
1034 super.onConfigurationChanged(newConfig)
1036 // Reset the navigation drawer first view flag.
1037 navigationDrawerFirstView = true
1039 // Get the current page.
1040 val currentPage = webViewViewPager2.currentItem
1042 // Toggle the pages if there is more than one so that the view pager will recalculate their size.
1043 if (currentPage > 0) {
1044 // Switch to the previous page after 25 milliseconds.
1045 webViewViewPager2.postDelayed ({ webViewViewPager2.currentItem = (currentPage - 1) }, 25)
1047 // Switch back to the current page after the view pager has quiesced (which we are deciding should be 25 milliseconds).
1048 webViewViewPager2.postDelayed ({ webViewViewPager2.currentItem = currentPage }, 25)
1051 // Scroll to the current tab position after 25 milliseconds.
1052 tabLayout.postDelayed ({ tabLayout.setScrollPosition(currentPage, 0F, false, false) }, 25)
1055 override fun onCreateOptionsMenu(menu: Menu): Boolean {
1056 // Inflate the menu. This adds items to the app bar if it is present.
1057 menuInflater.inflate(R.menu.webview_options_menu, menu)
1059 // Get handles for the menu items.
1060 optionsPrivacyMenuItem = menu.findItem(R.id.javascript)
1061 optionsRefreshMenuItem = menu.findItem(R.id.refresh)
1062 val optionsBookmarksMenuItem = menu.findItem(R.id.bookmarks)
1063 optionsCookiesMenuItem = menu.findItem(R.id.cookies)
1064 optionsDomStorageMenuItem = menu.findItem(R.id.dom_storage)
1065 optionsSaveFormDataMenuItem = menu.findItem(R.id.save_form_data) // Form data can be removed once the minimum API >= 26.
1066 optionsClearDataMenuItem = menu.findItem(R.id.clear_data)
1067 optionsClearCookiesMenuItem = menu.findItem(R.id.clear_cookies)
1068 optionsClearDomStorageMenuItem = menu.findItem(R.id.clear_dom_storage)
1069 optionsClearFormDataMenuItem = menu.findItem(R.id.clear_form_data) // Form data can be removed once the minimum API >= 26.
1070 optionsEasyListMenuItem = menu.findItem(R.id.easylist)
1071 optionsEasyPrivacyMenuItem = menu.findItem(R.id.easyprivacy)
1072 optionsFanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list)
1073 optionsFanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list)
1074 optionsFilterListsMenuItem = menu.findItem(R.id.filterlists)
1075 optionsUltraListMenuItem = menu.findItem(R.id.ultralist)
1076 optionsUltraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy)
1077 optionsBlockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests)
1078 optionsProxyMenuItem = menu.findItem(R.id.proxy)
1079 optionsProxyNoneMenuItem = menu.findItem(R.id.proxy_none)
1080 optionsProxyTorMenuItem = menu.findItem(R.id.proxy_tor)
1081 optionsProxyI2pMenuItem = menu.findItem(R.id.proxy_i2p)
1082 optionsProxyCustomMenuItem = menu.findItem(R.id.proxy_custom)
1083 optionsUserAgentMenuItem = menu.findItem(R.id.user_agent)
1084 optionsUserAgentPrivacyBrowserMenuItem = menu.findItem(R.id.user_agent_privacy_browser)
1085 optionsUserAgentWebViewDefaultMenuItem = menu.findItem(R.id.user_agent_webview_default)
1086 optionsUserAgentFirefoxOnAndroidMenuItem = menu.findItem(R.id.user_agent_firefox_on_android)
1087 optionsUserAgentChromeOnAndroidMenuItem = menu.findItem(R.id.user_agent_chrome_on_android)
1088 optionsUserAgentSafariOnIosMenuItem = menu.findItem(R.id.user_agent_safari_on_ios)
1089 optionsUserAgentFirefoxOnLinuxMenuItem = menu.findItem(R.id.user_agent_firefox_on_linux)
1090 optionsUserAgentChromiumOnLinuxMenuItem = menu.findItem(R.id.user_agent_chromium_on_linux)
1091 optionsUserAgentFirefoxOnWindowsMenuItem = menu.findItem(R.id.user_agent_firefox_on_windows)
1092 optionsUserAgentChromeOnWindowsMenuItem = menu.findItem(R.id.user_agent_chrome_on_windows)
1093 optionsUserAgentEdgeOnWindowsMenuItem = menu.findItem(R.id.user_agent_edge_on_windows)
1094 optionsUserAgentSafariOnMacosMenuItem = menu.findItem(R.id.user_agent_safari_on_macos)
1095 optionsUserAgentCustomMenuItem = menu.findItem(R.id.user_agent_custom)
1096 optionsSwipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh)
1097 optionsWideViewportMenuItem = menu.findItem(R.id.wide_viewport)
1098 optionsDisplayImagesMenuItem = menu.findItem(R.id.display_images)
1099 optionsDarkWebViewMenuItem = menu.findItem(R.id.dark_webview)
1100 optionsFontSizeMenuItem = menu.findItem(R.id.font_size)
1101 optionsViewSourceMenuItem = menu.findItem(R.id.view_source)
1102 optionsAddOrEditDomainMenuItem = menu.findItem(R.id.add_or_edit_domain)
1104 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1105 updatePrivacyIcons(false)
1107 // Only display the form data menu items if the API < 26.
1108 optionsSaveFormDataMenuItem.isVisible = Build.VERSION.SDK_INT < 26
1109 optionsClearFormDataMenuItem.isVisible = Build.VERSION.SDK_INT < 26
1111 // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
1112 optionsClearFormDataMenuItem.isEnabled = Build.VERSION.SDK_INT < 26
1114 // 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.
1115 if (displayAdditionalAppBarIcons) { // Display the additional icons.
1116 optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
1117 optionsBookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM)
1118 optionsCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM)
1119 } else { //Do not display the additional icons.
1120 optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER)
1121 optionsBookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER)
1122 optionsCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER)
1125 // Replace `Refresh` with `Stop` if a URL is already loading.
1126 if ((currentWebView != null) && (currentWebView!!.progress != 100)) {
1128 optionsRefreshMenuItem.setTitle(R.string.stop)
1130 // 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.
1131 if (displayAdditionalAppBarIcons)
1132 optionsRefreshMenuItem.setIcon(R.drawable.close_blue)
1135 // Store a handle for the options menu.
1142 override fun onPrepareOptionsMenu(menu: Menu): Boolean {
1143 // Initialize the current user agent string and the font size.
1144 var currentUserAgent = getString(R.string.user_agent_privacy_browser)
1147 // 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.
1148 if (currentWebView != null) {
1149 // Set the add or edit domain text.
1150 if (currentWebView!!.domainSettingsApplied)
1151 optionsAddOrEditDomainMenuItem.setTitle(R.string.edit_domain_settings)
1153 optionsAddOrEditDomainMenuItem.setTitle(R.string.add_domain_settings)
1155 // Get the current user agent from the WebView.
1156 currentUserAgent = currentWebView!!.settings.userAgentString
1158 // Get the current font size from the the WebView.
1159 fontSize = currentWebView!!.settings.textZoom
1161 // Set the status of the menu item checkboxes.
1162 optionsDomStorageMenuItem.isChecked = currentWebView!!.settings.domStorageEnabled
1163 @Suppress("DEPRECATION")
1164 optionsSaveFormDataMenuItem.isChecked = currentWebView!!.settings.saveFormData // Form data can be removed once the minimum API >= 26.
1165 optionsEasyListMenuItem.isChecked = currentWebView!!.easyListEnabled
1166 optionsEasyPrivacyMenuItem.isChecked = currentWebView!!.easyPrivacyEnabled
1167 optionsFanboysAnnoyanceListMenuItem.isChecked = currentWebView!!.fanboysAnnoyanceListEnabled
1168 optionsFanboysSocialBlockingListMenuItem.isChecked = currentWebView!!.fanboysSocialBlockingListEnabled
1169 optionsUltraListMenuItem.isChecked = currentWebView!!.ultraListEnabled
1170 optionsUltraPrivacyMenuItem.isChecked = currentWebView!!.ultraPrivacyEnabled
1171 optionsBlockAllThirdPartyRequestsMenuItem.isChecked = currentWebView!!.blockAllThirdPartyRequests
1172 optionsSwipeToRefreshMenuItem.isChecked = currentWebView!!.swipeToRefresh
1173 optionsWideViewportMenuItem.isChecked = currentWebView!!.settings.useWideViewPort
1174 optionsDisplayImagesMenuItem.isChecked = currentWebView!!.settings.loadsImagesAutomatically
1176 // Set the display names for the filter lists with the number of blocked requests.
1177 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + currentWebView!!.getRequestsCount(BLOCKED_REQUESTS)
1178 optionsEasyListMenuItem.title = currentWebView!!.getRequestsCount(EASYLIST).toString() + " - " + getString(R.string.easylist)
1179 optionsEasyPrivacyMenuItem.title = currentWebView!!.getRequestsCount(EASYPRIVACY).toString() + " - " + getString(R.string.easyprivacy)
1180 optionsFanboysAnnoyanceListMenuItem.title = currentWebView!!.getRequestsCount(FANBOYS_ANNOYANCE_LIST).toString() + " - " + getString(R.string.fanboys_annoyance_list)
1181 optionsFanboysSocialBlockingListMenuItem.title = currentWebView!!.getRequestsCount(FANBOYS_SOCIAL_BLOCKING_LIST).toString() + " - " + getString(R.string.fanboys_social_blocking_list)
1182 optionsUltraListMenuItem.title = currentWebView!!.getRequestsCount(com.stoutner.privacybrowser.views.ULTRALIST).toString() + " - " + getString(R.string.ultralist)
1183 optionsUltraPrivacyMenuItem.title = currentWebView!!.getRequestsCount(ULTRAPRIVACY).toString() + " - " + getString(R.string.ultraprivacy)
1184 optionsBlockAllThirdPartyRequestsMenuItem.title = currentWebView!!.getRequestsCount(THIRD_PARTY_REQUESTS).toString() + " - " + getString(R.string.block_all_third_party_requests)
1186 // Enable DOM Storage if JavaScript is enabled.
1187 optionsDomStorageMenuItem.isEnabled = currentWebView!!.settings.javaScriptEnabled
1189 // Get the current theme status.
1190 val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
1192 // Enable dark WebView if night mode is enabled.
1193 optionsDarkWebViewMenuItem.isEnabled = (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES)
1195 // Set the checkbox status for dark WebView if algorithmic darkening is supported.
1196 if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING))
1197 optionsDarkWebViewMenuItem.isChecked = WebSettingsCompat.isAlgorithmicDarkeningAllowed(currentWebView!!.settings)
1199 // Set the view source title according to the current URL.
1200 if (currentWebView!!.currentUrl.startsWith("view-source:"))
1201 optionsViewSourceMenuItem.title = getString(R.string.view_rendered_website)
1203 optionsViewSourceMenuItem.title = getString(R.string.view_source)
1206 // Set the cookies menu item checked status.
1207 optionsCookiesMenuItem.isChecked = cookieManager.acceptCookie()
1209 // Enable Clear Cookies if there are any.
1210 optionsClearCookiesMenuItem.isEnabled = cookieManager.hasCookies()
1212 // 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`.
1213 val privateDataDirectoryString = applicationInfo.dataDir
1215 // Get the storage directories.
1216 val localStorageDirectory = File("$privateDataDirectoryString/app_webview/Local Storage/")
1217 val indexedDBDirectory = File("$privateDataDirectoryString/app_webview/IndexedDB")
1219 // Initialize the number of files counters.
1220 var localStorageDirectoryNumberOfFiles = 0
1221 var indexedDBDirectoryNumberOfFiles = 0
1223 // 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.
1224 if (localStorageDirectory.exists())
1225 localStorageDirectoryNumberOfFiles = (localStorageDirectory.list())?.size ?: 0
1227 // Get a count of the number of files in the IndexedDB directory. The list can be null, in which case a `0` is returned.
1228 if (indexedDBDirectory.exists())
1229 indexedDBDirectoryNumberOfFiles = (indexedDBDirectory.list())?.size ?: 0
1231 // Enable Clear DOM Storage if there is any.
1232 optionsClearDomStorageMenuItem.isEnabled = localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0
1234 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
1235 if (Build.VERSION.SDK_INT < 26) {
1236 // Get the WebView database.
1237 val webViewDatabase = WebViewDatabase.getInstance(this)
1239 // Enable the clear form data menu item if there is anything to clear.
1240 @Suppress("DEPRECATION")
1241 optionsClearFormDataMenuItem.isEnabled = webViewDatabase.hasFormData()
1244 // Enable Clear Data if any of the submenu items are enabled.
1245 optionsClearDataMenuItem.isEnabled = (optionsClearCookiesMenuItem.isEnabled || optionsClearDomStorageMenuItem.isEnabled || optionsClearFormDataMenuItem.isEnabled)
1247 // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
1248 optionsFanboysSocialBlockingListMenuItem.isEnabled = !optionsFanboysAnnoyanceListMenuItem.isChecked
1250 // Set the proxy title and check the applied proxy.
1252 ProxyHelper.NONE -> {
1253 // Set the proxy title.
1254 optionsProxyMenuItem.title = getString(R.string.proxy) + " - " + getString(R.string.proxy_none)
1256 // Check the proxy None radio button.
1257 optionsProxyNoneMenuItem.isChecked = true
1260 ProxyHelper.TOR -> {
1261 // Set the proxy title.
1262 optionsProxyMenuItem.title = getString(R.string.proxy) + " - " + getString(R.string.proxy_tor)
1264 // Check the proxy Tor radio button.
1265 optionsProxyTorMenuItem.isChecked = true
1268 ProxyHelper.I2P -> {
1269 // Set the proxy title.
1270 optionsProxyMenuItem.title = getString(R.string.proxy) + " - " + getString(R.string.proxy_i2p)
1272 // Check the proxy I2P radio button.
1273 optionsProxyI2pMenuItem.isChecked = true
1276 ProxyHelper.CUSTOM -> {
1277 // Set the proxy title.
1278 optionsProxyMenuItem.title = getString(R.string.proxy) + " - " + getString(R.string.proxy_custom)
1280 // Check the proxy Custom radio button.
1281 optionsProxyCustomMenuItem.isChecked = true
1285 // Select the current user agent menu item.
1286 when (currentUserAgent) {
1287 resources.getStringArray(R.array.user_agent_data)[0] -> { // Privacy Browser.
1288 // Update the user agent menu item title.
1289 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_privacy_browser)
1291 // Select the Privacy Browser radio box.
1292 optionsUserAgentPrivacyBrowserMenuItem.isChecked = true
1295 webViewDefaultUserAgent -> { // WebView Default.
1296 // Update the user agent menu item title.
1297 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_webview_default)
1299 // Select the WebView Default radio box.
1300 optionsUserAgentWebViewDefaultMenuItem.isChecked = true
1303 resources.getStringArray(R.array.user_agent_data)[2] -> { // Firefox on Android.
1304 // Update the user agent menu item title.
1305 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_android)
1307 // Select the Firefox on Android radio box.
1308 optionsUserAgentFirefoxOnAndroidMenuItem.isChecked = true
1311 resources.getStringArray(R.array.user_agent_data)[3] -> { // Chrome on Android.
1312 // Update the user agent menu item title.
1313 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_android)
1315 // Select the Chrome on Android radio box.
1316 optionsUserAgentChromeOnAndroidMenuItem.isChecked = true
1319 resources.getStringArray(R.array.user_agent_data)[4] -> { // Safari on iOS.
1320 // Update the user agent menu item title.
1321 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_ios)
1323 // Select the Safari on iOS radio box.
1324 optionsUserAgentSafariOnIosMenuItem.isChecked = true
1327 resources.getStringArray(R.array.user_agent_data)[5] -> { // Firefox on Linux.
1328 // Update the user agent menu item title.
1329 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_linux)
1331 // Select the Firefox on Linux radio box.
1332 optionsUserAgentFirefoxOnLinuxMenuItem.isChecked = true
1335 resources.getStringArray(R.array.user_agent_data)[6] -> { // Chromium on Linux.
1336 // Update the user agent menu item title.
1337 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chromium_on_linux)
1339 // Select the Chromium on Linux radio box.
1340 optionsUserAgentChromiumOnLinuxMenuItem.isChecked = true
1343 resources.getStringArray(R.array.user_agent_data)[7] -> { // Firefox on Windows.
1344 // Update the user agent menu item title.
1345 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_windows)
1347 // Select the Firefox on Windows radio box.
1348 optionsUserAgentFirefoxOnWindowsMenuItem.isChecked = true
1351 resources.getStringArray(R.array.user_agent_data)[8] -> { // Chrome on Windows.
1352 // Update the user agent menu item title.
1353 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_windows)
1355 // Select the Chrome on Windows radio box.
1356 optionsUserAgentChromeOnWindowsMenuItem.isChecked = true
1359 resources.getStringArray(R.array.user_agent_data)[9] -> { // Edge on Windows.
1360 // Update the user agent menu item title.
1361 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_edge_on_windows)
1363 // Select the Edge on Windows radio box.
1364 optionsUserAgentEdgeOnWindowsMenuItem.isChecked = true
1367 resources.getStringArray(R.array.user_agent_data)[10] -> { // Safari on macOS.
1368 // Update the user agent menu item title.
1369 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_macos)
1371 // Select the Safari on macOS radio box.
1372 optionsUserAgentSafariOnMacosMenuItem.isChecked = true
1375 else -> { // Custom user agent.
1376 // Update the user agent menu item title.
1377 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_custom)
1379 // Select the Custom radio box.
1380 optionsUserAgentCustomMenuItem.isChecked = true
1384 // Set the font size title.
1385 optionsFontSizeMenuItem.title = getString(R.string.font_size) + " - " + fontSize + "%"
1387 // Run all the other default commands.
1388 super.onPrepareOptionsMenu(menu)
1390 // Display the menu.
1394 override fun onOptionsItemSelected(menuItem: MenuItem): Boolean {
1395 // Run the commands that correlate to the selected menu item.
1396 return when (menuItem.itemId) {
1397 R.id.javascript -> { // JavaScript.
1398 // Toggle the JavaScript status.
1399 currentWebView!!.settings.javaScriptEnabled = !currentWebView!!.settings.javaScriptEnabled
1401 // Update the privacy icon.
1402 updatePrivacyIcons(true)
1404 // Display a snackbar.
1405 if (currentWebView!!.settings.javaScriptEnabled) // JavaScrip is enabled.
1406 Snackbar.make(webViewViewPager2, R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show()
1407 else if (cookieManager.acceptCookie()) // JavaScript is disabled, but cookies are enabled.
1408 Snackbar.make(webViewViewPager2, R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show()
1409 else // Privacy mode.
1410 Snackbar.make(webViewViewPager2, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show()
1412 // Reload the current WebView.
1413 currentWebView!!.reload()
1415 // Consume the event.
1419 R.id.refresh -> { // Refresh.
1420 // Run the command that correlates to the current status of the menu item.
1421 if (menuItem.title == getString(R.string.refresh)) // The refresh button was pushed.
1422 currentWebView!!.reload()
1423 else // The stop button was pushed.
1424 currentWebView!!.stopLoading()
1426 // Consume the event.
1430 R.id.bookmarks -> { // Bookmarks.
1431 // Open the bookmarks drawer.
1432 drawerLayout.openDrawer(GravityCompat.END)
1434 // Consume the event.
1438 R.id.cookies -> { // Cookies.
1439 // Toggle the cookie status.
1440 cookieManager.setAcceptCookie(!cookieManager.acceptCookie())
1442 // Store the cookie status.
1443 currentWebView!!.acceptCookies = cookieManager.acceptCookie()
1445 // Update the menu checkbox.
1446 menuItem.isChecked = cookieManager.acceptCookie()
1448 // Update the privacy icon.
1449 updatePrivacyIcons(true)
1451 // Display a snackbar.
1452 if (cookieManager.acceptCookie()) // Cookies are enabled.
1453 Snackbar.make(webViewViewPager2, R.string.cookies_enabled, Snackbar.LENGTH_SHORT).show()
1454 else if (currentWebView!!.settings.javaScriptEnabled) // JavaScript is still enabled.
1455 Snackbar.make(webViewViewPager2, R.string.cookies_disabled, Snackbar.LENGTH_SHORT).show()
1456 else // Privacy mode.
1457 Snackbar.make(webViewViewPager2, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show()
1459 // Reload the current WebView.
1460 currentWebView!!.reload()
1462 // Consume the event.
1466 R.id.dom_storage -> { // DOM storage.
1467 // Toggle the DOM storage status.
1468 currentWebView!!.settings.domStorageEnabled = !currentWebView!!.settings.domStorageEnabled
1470 // Update the menu checkbox.
1471 menuItem.isChecked = currentWebView!!.settings.domStorageEnabled
1473 // Update the privacy icon.
1474 updatePrivacyIcons(true)
1476 // Display a snackbar.
1477 if (currentWebView!!.settings.domStorageEnabled)
1478 Snackbar.make(webViewViewPager2, R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show()
1480 Snackbar.make(webViewViewPager2, R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show()
1482 // Reload the current WebView.
1483 currentWebView!!.reload()
1485 // Consume the event.
1489 R.id.save_form_data -> { // Form data. This can be removed once the minimum API >= 26.
1490 // Switch the status of saveFormDataEnabled.
1491 @Suppress("DEPRECATION")
1492 currentWebView!!.settings.saveFormData = !currentWebView!!.settings.saveFormData
1494 // Update the menu checkbox.
1495 @Suppress("DEPRECATION")
1496 menuItem.isChecked = currentWebView!!.settings.saveFormData
1498 // Display a snackbar.
1499 @Suppress("DEPRECATION")
1500 if (currentWebView!!.settings.saveFormData)
1501 Snackbar.make(webViewViewPager2, R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show()
1503 Snackbar.make(webViewViewPager2, R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show()
1505 // Update the privacy icon.
1506 updatePrivacyIcons(true)
1508 // Reload the current WebView.
1509 currentWebView!!.reload()
1511 // Consume the event.
1515 R.id.clear_cookies -> { // Clear cookies.
1516 // Create a snackbar.
1517 Snackbar.make(webViewViewPager2, R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1518 .setAction(R.string.undo) {} // Everything will be handled by `onDismissed()` below.
1519 .addCallback(object : Snackbar.Callback() {
1520 override fun onDismissed(snackbar: Snackbar, event: Int) {
1521 if (event != DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1522 // Delete the cookies.
1523 cookieManager.removeAllCookies(null)
1529 // Consume the event.
1533 R.id.clear_dom_storage -> { // Clear DOM storage.
1534 // Create a snackbar.
1535 Snackbar.make(webViewViewPager2, R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1536 .setAction(R.string.undo) {} // Everything will be handled by `onDismissed()` below.
1537 .addCallback(object : Snackbar.Callback() {
1538 override fun onDismissed(snackbar: Snackbar, event: Int) {
1539 if (event != DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1540 // Get a handle for the web storage.
1541 val webStorage = WebStorage.getInstance()
1543 // Delete the DOM Storage.
1544 webStorage.deleteAllData()
1546 // Initialize a handler to manually delete the DOM storage files and directories.
1547 val deleteDomStorageHandler = Handler(Looper.getMainLooper())
1549 // Setup a runnable to manually delete the DOM storage files and directories.
1550 val deleteDomStorageRunnable = Runnable {
1552 // Get a handle for the runtime.
1553 val runtime = Runtime.getRuntime()
1555 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1556 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1557 val privateDataDirectoryString = applicationInfo.dataDir
1559 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1560 val deleteLocalStorageProcess = runtime.exec(arrayOf("rm", "-rf", "$privateDataDirectoryString/app_webview/Local Storage/"))
1562 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1563 val deleteIndexProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview/IndexedDB")
1564 val deleteQuotaManagerProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/QuotaManager")
1565 val deleteQuotaManagerJournalProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/QuotaManager-journal")
1566 val deleteDatabasesProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview/databases")
1568 // Wait for the processes to finish.
1569 deleteLocalStorageProcess.waitFor()
1570 deleteIndexProcess.waitFor()
1571 deleteQuotaManagerProcess.waitFor()
1572 deleteQuotaManagerJournalProcess.waitFor()
1573 deleteDatabasesProcess.waitFor()
1574 } catch (exception: Exception) {
1575 // Do nothing if an error is thrown.
1579 // Manually delete the DOM storage files after 200 milliseconds.
1580 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200)
1586 // Consume the event.
1590 R.id.clear_form_data -> { // Clear form data. This can be remove once the minimum API >= 26.
1591 // Create a snackbar.
1592 Snackbar.make(webViewViewPager2, R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1593 .setAction(R.string.undo) {} // Everything will be handled by `onDismissed()` below.
1594 .addCallback(object : Snackbar.Callback() {
1595 override fun onDismissed(snackbar: Snackbar, event: Int) {
1596 if (event != DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1597 // Get a handle for the webView database.
1598 val webViewDatabase = WebViewDatabase.getInstance(applicationContext)
1600 // Delete the form data.
1601 @Suppress("DEPRECATION")
1602 webViewDatabase.clearFormData()
1608 // Consume the event.
1612 R.id.easylist -> { // EasyList.
1613 // Toggle the EasyList status.
1614 currentWebView!!.easyListEnabled = !currentWebView!!.easyListEnabled
1616 // Update the menu checkbox.
1617 menuItem.isChecked = currentWebView!!.easyListEnabled
1619 // Reload the current WebView.
1620 currentWebView!!.reload()
1622 // Consume the event.
1626 R.id.easyprivacy -> { // EasyPrivacy.
1627 // Toggle the EasyPrivacy status.
1628 currentWebView!!.easyPrivacyEnabled = !currentWebView!!.easyPrivacyEnabled
1630 // Update the menu checkbox.
1631 menuItem.isChecked = currentWebView!!.easyPrivacyEnabled
1633 // Reload the current WebView.
1634 currentWebView!!.reload()
1636 // Consume the event.
1640 R.id.fanboys_annoyance_list -> { // Fanboy's Annoyance List.
1641 // Toggle Fanboy's Annoyance List status.
1642 currentWebView!!.fanboysAnnoyanceListEnabled = !currentWebView!!.fanboysAnnoyanceListEnabled
1644 // Update the menu checkbox.
1645 menuItem.isChecked = currentWebView!!.fanboysAnnoyanceListEnabled
1647 // Update the status of Fanboy's Social Blocking List.
1648 optionsFanboysSocialBlockingListMenuItem.isEnabled = !currentWebView!!.fanboysAnnoyanceListEnabled
1650 // Reload the current WebView.
1651 currentWebView!!.reload()
1653 // Consume the event.
1657 R.id.fanboys_social_blocking_list -> { // Fanboy's Social Blocking List.
1658 // Toggle Fanboy's Social Blocking List status.
1659 currentWebView!!.fanboysSocialBlockingListEnabled = !currentWebView!!.fanboysSocialBlockingListEnabled
1661 // Update the menu checkbox.
1662 menuItem.isChecked = currentWebView!!.fanboysSocialBlockingListEnabled
1664 // Reload the current WebView.
1665 currentWebView!!.reload()
1667 // Consume the event.
1671 R.id.ultralist -> { // UltraList.
1672 // Toggle the UltraList status.
1673 currentWebView!!.ultraListEnabled = !currentWebView!!.ultraListEnabled
1675 // Update the menu checkbox.
1676 menuItem.isChecked = currentWebView!!.ultraListEnabled
1678 // Reload the current WebView.
1679 currentWebView!!.reload()
1681 // Consume the event.
1685 R.id.ultraprivacy -> { // UltraPrivacy.
1686 // Toggle the UltraPrivacy status.
1687 currentWebView!!.ultraPrivacyEnabled = !currentWebView!!.ultraPrivacyEnabled
1689 // Update the menu checkbox.
1690 menuItem.isChecked = currentWebView!!.ultraPrivacyEnabled
1692 // Reload the current WebView.
1693 currentWebView!!.reload()
1695 // Consume the event.
1699 R.id.block_all_third_party_requests -> { // Block all third-party requests.
1700 //Toggle the third-party requests blocker status.
1701 currentWebView!!.blockAllThirdPartyRequests = !currentWebView!!.blockAllThirdPartyRequests
1703 // Update the menu checkbox.
1704 menuItem.isChecked = currentWebView!!.blockAllThirdPartyRequests
1706 // Reload the current WebView.
1707 currentWebView!!.reload()
1709 // Consume the event.
1713 R.id.proxy_none -> { // Proxy - None.
1714 // Update the proxy mode.
1715 proxyMode = ProxyHelper.NONE
1717 // Apply the proxy mode.
1720 // Consume the event.
1724 R.id.proxy_tor -> { // Proxy - Tor.
1725 // Update the proxy mode.
1726 proxyMode = ProxyHelper.TOR
1728 // Apply the proxy mode.
1731 // Consume the event.
1735 R.id.proxy_i2p -> { // Proxy - I2P.
1736 // Update the proxy mode.
1737 proxyMode = ProxyHelper.I2P
1739 // Apply the proxy mode.
1742 // Consume the event.
1746 R.id.proxy_custom -> { // Proxy - Custom.
1747 // Update the proxy mode.
1748 proxyMode = ProxyHelper.CUSTOM
1750 // Apply the proxy mode.
1753 // Consume the event.
1757 R.id.user_agent_privacy_browser -> { // User Agent - Privacy Browser.
1758 // Update the user agent.
1759 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[0]
1761 // Reload the current WebView.
1762 currentWebView!!.reload()
1764 // Consume the event.
1768 R.id.user_agent_webview_default -> { // User Agent - WebView Default.
1769 // Update the user agent.
1770 currentWebView!!.settings.userAgentString = ""
1772 // Reload the current WebView.
1773 currentWebView!!.reload()
1775 // Consume the event.
1779 R.id.user_agent_firefox_on_android -> { // User Agent - Firefox on Android.
1780 // Update the user agent.
1781 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[2]
1783 // Reload the current WebView.
1784 currentWebView!!.reload()
1786 // Consume the event.
1790 R.id.user_agent_chrome_on_android -> { // User Agent - Chrome on Android.
1791 // Update the user agent.
1792 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[3]
1794 // Reload the current WebView.
1795 currentWebView!!.reload()
1797 // Consume the event.
1801 R.id.user_agent_safari_on_ios -> { // User Agent - Safari on iOS.
1802 // Update the user agent.
1803 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[4]
1805 // Reload the current WebView.
1806 currentWebView!!.reload()
1808 // Consume the event.
1812 R.id.user_agent_firefox_on_linux -> { // User Agent - Firefox on Linux.
1813 // Update the user agent.
1814 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[5]
1816 // Reload the current WebView.
1817 currentWebView!!.reload()
1819 // Consume the event.
1823 R.id.user_agent_chromium_on_linux -> { // User Agent - Chromium on Linux.
1824 // Update the user agent.
1825 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[6]
1827 // Reload the current WebView.
1828 currentWebView!!.reload()
1830 // Consume the event.
1834 R.id.user_agent_firefox_on_windows -> { // User Agent - Firefox on Windows.
1835 // Update the user agent.
1836 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[7]
1838 // Reload the current WebView.
1839 currentWebView!!.reload()
1841 // Consume the event.
1845 R.id.user_agent_chrome_on_windows -> { // User Agent - Chrome on Windows.
1846 // Update the user agent.
1847 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[8]
1849 // Reload the current WebView.
1850 currentWebView!!.reload()
1852 // Consume the event.
1856 R.id.user_agent_edge_on_windows -> { // User Agent - Edge on Windows.
1857 // Update the user agent.
1858 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[9]
1860 // Reload the current WebView.
1861 currentWebView!!.reload()
1863 // Consume the event.
1867 R.id.user_agent_safari_on_macos -> { // User Agent - Safari on macOS.
1868 // Update the user agent.
1869 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[10]
1871 // Reload the current WebView.
1872 currentWebView!!.reload()
1874 // Consume the event.
1878 R.id.user_agent_custom -> { // User Agent - Custom.
1879 // Update the user agent.
1880 currentWebView!!.settings.userAgentString = sharedPreferences.getString(getString(R.string.custom_user_agent_key), getString(R.string.custom_user_agent_default_value))
1882 // Reload the current WebView.
1883 currentWebView!!.reload()
1885 // Consume the event.
1889 R.id.font_size -> { // Font size.
1890 // Instantiate the font size dialog.
1891 val fontSizeDialogFragment: DialogFragment = FontSizeDialog.displayDialog(currentWebView!!.settings.textZoom)
1893 // Show the font size dialog.
1894 fontSizeDialogFragment.show(supportFragmentManager, getString(R.string.font_size))
1896 // Consume the event.
1900 R.id.swipe_to_refresh -> { // Swipe to refresh.
1901 // Toggle the stored status of swipe to refresh.
1902 currentWebView!!.swipeToRefresh = !currentWebView!!.swipeToRefresh
1904 // Update the swipe refresh layout.
1905 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.
1906 swipeRefreshLayout.isEnabled = currentWebView!!.scrollY == 0
1907 else // Swipe to refresh is disabled.
1908 swipeRefreshLayout.isEnabled = false
1910 // Consume the event.
1914 R.id.wide_viewport -> { // Wide viewport.
1915 // Toggle the viewport.
1916 currentWebView!!.settings.useWideViewPort = !currentWebView!!.settings.useWideViewPort
1918 // Consume the event.
1922 R.id.display_images -> { // Display images.
1923 // Toggle the displaying of images.
1924 if (currentWebView!!.settings.loadsImagesAutomatically) { // Images are currently loaded automatically.
1925 // Disable loading of images.
1926 currentWebView!!.settings.loadsImagesAutomatically = false
1928 // Reload the website to remove existing images.
1929 currentWebView!!.reload()
1930 } else { // Images are not currently loaded automatically.
1931 // Enable loading of images. Missing images will be loaded without the need for a reload.
1932 currentWebView!!.settings.loadsImagesAutomatically = true
1935 // Consume the event.
1939 R.id.dark_webview -> { // Dark WebView.
1940 // Toggle dark WebView if supported.
1941 if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING))
1942 WebSettingsCompat.setAlgorithmicDarkeningAllowed(currentWebView!!.settings, !WebSettingsCompat.isAlgorithmicDarkeningAllowed(currentWebView!!.settings)
1945 // Consume the event.
1949 R.id.find_on_page -> { // Find on page.
1950 // Set the minimum height of the find on page linear layout to match the toolbar.
1951 findOnPageLinearLayout.minimumHeight = toolbar.height
1953 // Hide the toolbar.
1954 toolbar.visibility = View.GONE
1956 // Show the find on page linear layout.
1957 findOnPageLinearLayout.visibility = View.VISIBLE
1959 // Display the keyboard. The app must wait 200 ms before running the command to work around a bug in Android.
1960 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1961 findOnPageEditText.postDelayed({
1962 // Set the focus on the find on page edit text.
1963 findOnPageEditText.requestFocus()
1965 // Get a handle for the input method manager.
1966 val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
1968 // Display the keyboard. `0` sets no input flags.
1969 inputMethodManager.showSoftInput(findOnPageEditText, 0)
1972 // Consume the event.
1976 R.id.print -> { // Print.
1977 // Get a print manager instance.
1978 val printManager = (getSystemService(PRINT_SERVICE) as PrintManager)
1980 // Create a print document adapter from the current WebView.
1981 val printDocumentAdapter = currentWebView!!.createPrintDocumentAdapter(getString(R.string.print))
1983 // Print the document.
1984 printManager.print(getString(R.string.privacy_browser_webpage), printDocumentAdapter, null)
1986 // Consume the event.
1990 R.id.save_url -> { // Save URL.
1991 // Check the download preference.
1992 if (downloadWithExternalApp) // Download with an external app.
1993 downloadUrlWithExternalApp(currentWebView!!.currentUrl)
1994 else // Handle the download inside of Privacy Browser. The dialog will be displayed once the file size and the content disposition have been acquired.
1995 PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, currentWebView!!.currentUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
1997 // Consume the event.
2001 R.id.save_archive -> {
2002 // Open the file picker with a default file name built from the current domain name.
2003 saveWebpageArchiveActivityResultLauncher.launch(currentWebView!!.currentDomainName + ".mht")
2005 // Consume the event.
2009 R.id.save_image -> { // Save image.
2010 // Open the file picker with a default file name built from the current domain name.
2011 saveWebpageImageActivityResultLauncher.launch(currentWebView!!.currentDomainName + ".png")
2013 // Consume the event.
2017 R.id.add_to_homescreen -> { // Add to homescreen.
2018 // Instantiate the create home screen shortcut dialog.
2019 val createHomeScreenShortcutDialogFragment: DialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView!!.title!!, currentWebView!!.url!!, currentWebView!!.getFavoriteIcon())
2021 // Show the create home screen shortcut dialog.
2022 createHomeScreenShortcutDialogFragment.show(supportFragmentManager, getString(R.string.create_shortcut))
2024 // Consume the event.
2028 R.id.view_source -> { // View source.
2029 // Open a new tab according to the current URL.
2030 if (currentWebView!!.currentUrl.startsWith("view-source:")) { // The source is currently viewed.
2031 // Open the rendered website in a new tab.
2032 addNewPage(currentWebView!!.currentUrl.substring(12, currentWebView!!.currentUrl.length), true, moveToTab = true)
2033 } else { // The rendered website is currently viewed.
2034 // Open the source in a new tab.
2035 addNewPage("view-source:${currentWebView!!.currentUrl}", adjacent = true, moveToTab = true)
2038 // Consume the event.
2042 R.id.view_headers -> { // View headers.
2043 // Create an intent to launch the view headers activity.
2044 val viewHeadersIntent = Intent(this, ViewHeadersActivity::class.java)
2046 // Add the variables to the intent.
2047 viewHeadersIntent.putExtra(CURRENT_URL, currentWebView!!.url)
2048 viewHeadersIntent.putExtra(USER_AGENT, currentWebView!!.settings.userAgentString)
2051 startActivity(viewHeadersIntent)
2053 // Consume the event.
2057 R.id.share_message -> { // Share a message.
2058 // Prepare the share string.
2059 val shareString = currentWebView!!.title + " – " + currentWebView!!.url
2061 // Create the share intent.
2062 val shareMessageIntent = Intent(Intent.ACTION_SEND)
2064 // Add the share string to the intent.
2065 shareMessageIntent.putExtra(Intent.EXTRA_TEXT, shareString)
2067 // Set the MIME type.
2068 shareMessageIntent.type = "text/plain"
2070 // Set the intent to open in a new task.
2071 shareMessageIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
2074 startActivity(Intent.createChooser(shareMessageIntent, getString(R.string.share_message)))
2076 // Consume the event.
2080 R.id.share_url -> { // Share URL.
2081 // Create the share intent.
2082 val shareUrlIntent = Intent(Intent.ACTION_SEND)
2084 // Add the URL to the intent.
2085 shareUrlIntent.putExtra(Intent.EXTRA_TEXT, currentWebView!!.url)
2087 // Add the title to the intent.
2088 shareUrlIntent.putExtra(Intent.EXTRA_SUBJECT, currentWebView!!.title)
2090 // Set the MIME type.
2091 shareUrlIntent.type = "text/plain"
2093 // Set the intent to open in a new task.
2094 shareUrlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
2097 startActivity(Intent.createChooser(shareUrlIntent, getString(R.string.share_url)))
2099 // Consume the event.
2103 R.id.open_with_app -> { // Open with app.
2104 // Open the URL with an outside app.
2105 openWithApp(currentWebView!!.url!!)
2107 // Consume the event.
2111 R.id.open_with_browser -> { // Open with browser.
2112 // Open the URL with an outside browser.
2113 openWithBrowser(currentWebView!!.url!!)
2115 // Consume the event.
2119 R.id.add_or_edit_domain -> { // Add or edit domain.
2120 // Reapply the domain settings on returning to the main WebView activity.
2121 reapplyDomainSettingsOnRestart = true
2123 // Check if domain settings are currently applied.
2124 if (currentWebView!!.domainSettingsApplied) { // Edit the current domain settings.
2125 // Create an intent to launch the domains activity.
2126 val domainsIntent = Intent(this, DomainsActivity::class.java)
2128 // Add the extra information to the intent.
2129 domainsIntent.putExtra(LOAD_DOMAIN, currentWebView!!.domainSettingsDatabaseId)
2130 domainsIntent.putExtra(CLOSE_ON_BACK, true)
2131 domainsIntent.putExtra(CURRENT_URL, currentWebView!!.url)
2132 domainsIntent.putExtra(CURRENT_IP_ADDRESSES, currentWebView!!.currentIpAddresses)
2134 // Get the current certificate.
2135 val sslCertificate = currentWebView!!.certificate
2137 // Check to see if the SSL certificate is populated.
2138 if (sslCertificate != null) {
2139 // Extract the certificate to strings.
2140 val issuedToCName = sslCertificate.issuedTo.cName
2141 val issuedToOName = sslCertificate.issuedTo.oName
2142 val issuedToUName = sslCertificate.issuedTo.uName
2143 val issuedByCName = sslCertificate.issuedBy.cName
2144 val issuedByOName = sslCertificate.issuedBy.oName
2145 val issuedByUName = sslCertificate.issuedBy.uName
2146 val startDateLong = sslCertificate.validNotBeforeDate.time
2147 val endDateLong = sslCertificate.validNotAfterDate.time
2149 // Add the certificate to the intent.
2150 domainsIntent.putExtra(SSL_ISSUED_TO_CNAME, issuedToCName)
2151 domainsIntent.putExtra(SSL_ISSUED_TO_ONAME, issuedToOName)
2152 domainsIntent.putExtra(SSL_ISSUED_TO_UNAME, issuedToUName)
2153 domainsIntent.putExtra(SSL_ISSUED_BY_CNAME, issuedByCName)
2154 domainsIntent.putExtra(SSL_ISSUED_BY_ONAME, issuedByOName)
2155 domainsIntent.putExtra(SSL_ISSUED_BY_UNAME, issuedByUName)
2156 domainsIntent.putExtra(SSL_START_DATE, startDateLong)
2157 domainsIntent.putExtra(SSL_END_DATE, endDateLong)
2161 startActivity(domainsIntent)
2162 } else { // Add a new domain.
2163 // Get the current URI.
2164 val currentUri = Uri.parse(currentWebView!!.url)
2166 // Get the current domain from the URI. Use an empty string if it is null.
2167 val currentDomain = currentUri.host?: ""
2169 // Get the current settings status.
2170 val javaScriptInt = calculateSettingsInt(currentWebView!!.settings.javaScriptEnabled, sharedPreferences.getBoolean(getString(R.string.javascript_key), false))
2171 val cookiesInt = calculateSettingsInt(currentWebView!!.acceptCookies, sharedPreferences.getBoolean(getString(R.string.cookies_key), false))
2172 val domStorageInt = calculateSettingsInt(currentWebView!!.settings.domStorageEnabled, sharedPreferences.getBoolean(getString(R.string.dom_storage_key), false))
2173 val easyListInt = calculateSettingsInt(currentWebView!!.easyListEnabled, sharedPreferences.getBoolean(getString(R.string.easylist_key), true))
2174 val easyPrivacyInt = calculateSettingsInt(currentWebView!!.easyPrivacyEnabled, sharedPreferences.getBoolean(getString(R.string.easyprivacy_key), true))
2175 val fanboysAnnoyanceListInt = calculateSettingsInt(currentWebView!!.fanboysAnnoyanceListEnabled, sharedPreferences.getBoolean(getString(R.string.fanboys_annoyance_list_key), true))
2176 val fanboysSocialBlockingListInt = calculateSettingsInt(currentWebView!!.fanboysSocialBlockingListEnabled, sharedPreferences.getBoolean(getString(R.string.fanboys_social_blocking_list_key), true))
2177 val ultraListInt = calculateSettingsInt(currentWebView!!.ultraListEnabled, sharedPreferences.getBoolean(getString(R.string.ultralist_key), true))
2178 val ultraPrivacyInt = calculateSettingsInt(currentWebView!!.ultraPrivacyEnabled, sharedPreferences.getBoolean(getString(R.string.ultraprivacy_key), true))
2179 val blockAllThirdPartyRequestsInt = calculateSettingsInt(currentWebView!!.blockAllThirdPartyRequests, sharedPreferences.getBoolean(getString(R.string.block_all_third_party_requests_key), true))
2180 val swipeToRefreshInt = calculateSettingsInt(currentWebView!!.swipeToRefresh, sharedPreferences.getBoolean(getString(R.string.swipe_to_refresh_key), true))
2181 val wideViewportInt = calculateSettingsInt(currentWebView!!.settings.useWideViewPort, sharedPreferences.getBoolean(getString(R.string.wide_viewport_key), true))
2182 val displayImagesInt = calculateSettingsInt(currentWebView!!.settings.loadsImagesAutomatically, sharedPreferences.getBoolean(getString(R.string.display_webpage_images_key), true))
2184 // Initialize the form data int.
2185 var formDataInt = SYSTEM_DEFAULT
2187 // Set the form data int, which can be removed once the minimum API >= 26.
2188 @Suppress("DEPRECATION")
2189 if (Build.VERSION.SDK_INT < 26) {
2190 // Get the form data status.
2191 val formDataEnabled = currentWebView!!.settings.saveFormData
2193 // Calculate the form data Int.
2194 formDataInt = calculateSettingsInt(formDataEnabled, sharedPreferences.getBoolean(getString(R.string.save_form_data_key), false))
2197 // Get the current user agent string.
2198 val currentUserAgentString = currentWebView!!.settings.userAgentString
2200 // Get the user agent string array position.
2201 val userAgentStringArrayPosition = userAgentDataArrayAdapter.getPosition(currentUserAgentString)
2203 // Set the user agent name.
2204 val userAgentName = if ((userAgentStringArrayPosition >= 0) && (defaultUserAgentName == userAgentNamesArray[userAgentStringArrayPosition])) { // The system default user agent is in use.
2205 getString(R.string.system_default_user_agent)
2206 } else { // An on-the-fly user agent is being used (or the WebView default user agent is applied).
2207 when (userAgentStringArrayPosition) {
2208 UNRECOGNIZED_USER_AGENT -> { // The user agent is unrecognized.
2209 if (currentUserAgentString == webViewDefaultUserAgent) { // The WebView default user agent is being used.
2210 if (defaultUserAgentName == getString(R.string.webview_default)) { // The WebView default user agent is the system default.
2211 // Set the user agent name to be the system default.
2212 getString(R.string.system_default_user_agent)
2213 } else { // The WebView default user agent is set as an on-the-fly setting.
2214 // Set the default user agent name.
2215 getString(R.string.webview_default)
2217 } else { // A custom user agent is being used.
2218 if (defaultUserAgentName == getString(R.string.custom_user_agent_non_translatable)) { // The system custom user agent is in use.
2219 // Set the user agent name to be the system default.
2220 getString(R.string.system_default_user_agent)
2221 } else { // An on-the-fly custom user agent is in use.
2222 // Store the user agent as currently applied.
2223 currentUserAgentString
2228 else -> // Store the standard user agent name.
2229 userAgentNamesArray[userAgentStringArrayPosition]
2233 // Get the current text zoom integer.
2234 val textZoomInt = currentWebView!!.settings.textZoom
2236 // Set the font size integer.
2237 val fontSizeInt = if (textZoomInt == defaultFontSizeString.toInt()) // The current system default is used, which is encoded as a zoom of `0`.
2239 else // A custom font size is used.
2242 // Get the current WebView dark theme status.
2243 val webViewDarkThemeCurrentlyEnabled = if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) // Algorithmic darkening is supported.
2244 WebSettingsCompat.isAlgorithmicDarkeningAllowed(currentWebView!!.settings)
2245 else // Algorithmic darkening is not supported.
2248 // Get the default WebView dark theme setting.
2249 val defaultWebViewDarkThemeEnabled = if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) { // Algorithmic darkening is supported.
2250 when (defaultWebViewTheme) {
2251 webViewThemeEntryValuesStringArray[1] -> // The dark theme is disabled by default.
2254 webViewThemeEntryValuesStringArray[2] -> // The dark theme is enabled by default.
2257 else -> { // The system default theme is selected.
2258 // Get the current app theme status.
2259 val currentAppThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
2261 // Check if the current app theme is dark.
2262 currentAppThemeStatus == Configuration.UI_MODE_NIGHT_YES
2265 } else { // Algorithmic darkening is not supported.
2269 // Set the WebView theme int.
2270 val webViewThemeInt = if (webViewDarkThemeCurrentlyEnabled == defaultWebViewDarkThemeEnabled) // The current WebView theme matches the default.
2272 else if (webViewDarkThemeCurrentlyEnabled) // The current WebView theme is dark and that is not the default.
2274 else // The current WebView theme is light and that is not the default.
2277 // Create the domain and store the database ID.
2278 val newDomainDatabaseId = domainsDatabaseHelper!!.addDomain(currentDomain, javaScriptInt, cookiesInt, domStorageInt, formDataInt, userAgentName, easyListInt, easyPrivacyInt,
2279 fanboysAnnoyanceListInt, fanboysSocialBlockingListInt, ultraListInt, ultraPrivacyInt, blockAllThirdPartyRequestsInt, fontSizeInt,
2280 swipeToRefreshInt, webViewThemeInt, wideViewportInt, displayImagesInt)
2282 // Create an intent to launch the domains activity.
2283 val domainsIntent = Intent(this, DomainsActivity::class.java)
2285 // Add the extra information to the intent.
2286 domainsIntent.putExtra(LOAD_DOMAIN, newDomainDatabaseId)
2287 domainsIntent.putExtra(CLOSE_ON_BACK, true)
2288 domainsIntent.putExtra(CURRENT_URL, currentWebView!!.url)
2289 domainsIntent.putExtra(CURRENT_IP_ADDRESSES, currentWebView!!.currentIpAddresses)
2291 // Get the current certificate.
2292 val sslCertificate = currentWebView!!.certificate
2294 // Check to see if the SSL certificate is populated.
2295 if (sslCertificate != null) {
2296 // Extract the certificate to strings.
2297 val issuedToCName = sslCertificate.issuedTo.cName
2298 val issuedToOName = sslCertificate.issuedTo.oName
2299 val issuedToUName = sslCertificate.issuedTo.uName
2300 val issuedByCName = sslCertificate.issuedBy.cName
2301 val issuedByOName = sslCertificate.issuedBy.oName
2302 val issuedByUName = sslCertificate.issuedBy.uName
2303 val startDateLong = sslCertificate.validNotBeforeDate.time
2304 val endDateLong = sslCertificate.validNotAfterDate.time
2306 // Add the certificate to the intent.
2307 domainsIntent.putExtra(SSL_ISSUED_TO_CNAME, issuedToCName)
2308 domainsIntent.putExtra(SSL_ISSUED_TO_ONAME, issuedToOName)
2309 domainsIntent.putExtra(SSL_ISSUED_TO_UNAME, issuedToUName)
2310 domainsIntent.putExtra(SSL_ISSUED_BY_CNAME, issuedByCName)
2311 domainsIntent.putExtra(SSL_ISSUED_BY_ONAME, issuedByOName)
2312 domainsIntent.putExtra(SSL_ISSUED_BY_UNAME, issuedByUName)
2313 domainsIntent.putExtra(SSL_START_DATE, startDateLong)
2314 domainsIntent.putExtra(SSL_END_DATE, endDateLong)
2318 startActivity(domainsIntent)
2321 // Consume the event.
2325 else -> { // There is no match with the options menu. Pass the event up to the parent method.
2326 // Don't consume the event.
2327 super.onOptionsItemSelected(menuItem)
2332 override fun onNavigationItemSelected(menuItem: MenuItem): Boolean {
2333 // Run the commands that correspond to the selected menu item.
2334 when (menuItem.itemId) {
2335 R.id.clear_and_exit -> { // Clear and exit.
2336 // Clear and exit Privacy Browser.
2340 R.id.home -> { // Home.
2341 // Load the homepage.
2342 loadUrl(currentWebView!!, sharedPreferences.getString(getString(R.string.homepage_key), getString(R.string.homepage_default_value))!!)
2345 R.id.back -> { // Back.
2346 // Check if the WebView can go back.
2347 if (currentWebView!!.canGoBack()) {
2348 // Get the current web back forward list.
2349 val webBackForwardList = currentWebView!!.copyBackForwardList()
2351 // Get the previous entry data.
2352 val previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex - 1).url
2353 val previousFavoriteIcon = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex - 1).favicon!!
2355 // Apply the domain settings.
2356 applyDomainSettings(currentWebView!!, previousUrl, resetTab = false, reloadWebsite = false, loadUrl = false)
2358 // Get the current tab.
2359 val tab = tabLayout.getTabAt(tabLayout.selectedTabPosition)!!
2361 // Get the custom view from the tab.
2362 val tabView = tab.customView!!
2364 // Get the favorite icon image view from the tab.
2365 val tabFavoriteIconImageView = tabView.findViewById<ImageView>(R.id.favorite_icon_imageview)
2367 // Set the previous favorite icon.
2368 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(previousFavoriteIcon, 64, 64, true))
2370 // Load the previous website in the history.
2371 currentWebView!!.goBack()
2373 // Update the URL edit text after a delay.
2374 updateUrlEditTextAfterDelay()
2378 R.id.forward -> { // Forward.
2379 // Check if the WebView can go forward.
2380 if (currentWebView!!.canGoForward()) {
2381 // Get the current web back forward list.
2382 val webBackForwardList = currentWebView!!.copyBackForwardList()
2384 // Get the next entry data.
2385 val nextUrl = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex + 1).url
2386 val nextFavoriteIcon = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex + 1).favicon!!
2388 // Apply the domain settings.
2389 applyDomainSettings(currentWebView!!, nextUrl, resetTab = false, reloadWebsite = false, loadUrl = false)
2391 // Get the current tab.
2392 val tab = tabLayout.getTabAt(tabLayout.selectedTabPosition)!!
2394 // Get the custom view from the tab.
2395 val tabView = tab.customView!!
2397 // Get the favorite icon image view from the tab.
2398 val tabFavoriteIconImageView = tabView.findViewById<ImageView>(R.id.favorite_icon_imageview)
2400 // Set the next favorite icon.
2401 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nextFavoriteIcon, 64, 64, true))
2403 // Load the next website in the history.
2404 currentWebView!!.goForward()
2406 // Update the URL edit text after a delay.
2407 updateUrlEditTextAfterDelay()
2411 R.id.scroll_to_bottom -> { // Scroll to Bottom.
2412 // Check if the WebView is scrolled to the top.
2413 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.
2414 currentWebView!!.scrollTo(0, 1_000_000_000)
2415 } else { // The WebView is not at the top; scroll to the top.
2416 currentWebView!!.scrollTo(0, 0)
2420 R.id.history -> { // History.
2421 // Instantiate the URL history dialog.
2422 val urlHistoryDialogFragment: DialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView!!.webViewFragmentId)
2424 // Show the URL history dialog.
2425 urlHistoryDialogFragment.show(supportFragmentManager, getString(R.string.history))
2428 R.id.open -> { // Open.
2429 // Instantiate the open file dialog.
2430 val openDialogFragment: DialogFragment = OpenDialog()
2432 // Show the open file dialog.
2433 openDialogFragment.show(supportFragmentManager, getString(R.string.open))
2436 R.id.requests -> { // Requests.
2437 // Populate the resource requests.
2438 RequestsActivity.resourceRequests = currentWebView!!.getResourceRequests()
2440 // Create an intent to launch the Requests activity.
2441 val requestsIntent = Intent(this, RequestsActivity::class.java)
2443 // Add the block third-party requests status to the intent.
2444 requestsIntent.putExtra(BLOCK_ALL_THIRD_PARTY_REQUESTS, currentWebView!!.blockAllThirdPartyRequests)
2447 startActivity(requestsIntent)
2450 R.id.downloads -> { // Downloads.
2451 // Try the default system download manager.
2453 // Launch the default system Download Manager.
2454 val defaultDownloadManagerIntent = Intent(DownloadManager.ACTION_VIEW_DOWNLOADS)
2456 // Launch as a new task so that the download manager and Privacy Browser show as separate windows in the recent tasks list.
2457 defaultDownloadManagerIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2460 startActivity(defaultDownloadManagerIntent)
2461 } catch (defaultDownloadManagerException: Exception) { // The system download manager is not available.
2462 // Try a generic file manager.
2464 // Create a generic file manager intent.
2465 val genericFileManagerIntent = Intent(Intent.ACTION_VIEW)
2467 // Open the download directory.
2468 genericFileManagerIntent.setDataAndType(Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()), DocumentsContract.Document.MIME_TYPE_DIR)
2470 // Launch as a new task so that the file manager and Privacy Browser show as separate windows in the recent tasks list.
2471 genericFileManagerIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2474 startActivity(genericFileManagerIntent)
2475 } catch (genericFileManagerException: Exception) { // A generic file manager is not available.
2476 // Try an alternate file manager.
2478 // Create an alternate file manager intent.
2479 val alternateFileManagerIntent = Intent(Intent.ACTION_VIEW)
2481 // Open the download directory.
2482 alternateFileManagerIntent.setDataAndType(Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()), "resource/folder")
2484 // Launch as a new task so that the file manager and Privacy Browser show as separate windows in the recent tasks list.
2485 alternateFileManagerIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2487 // Open the alternate file manager.
2488 startActivity(alternateFileManagerIntent)
2489 } catch (alternateFileManagerException: Exception) {
2490 // Display a snackbar.
2491 Snackbar.make(currentWebView!!, R.string.no_file_manager_detected, Snackbar.LENGTH_INDEFINITE).show()
2497 R.id.domains -> { // Domains.
2498 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2499 reapplyDomainSettingsOnRestart = true
2501 // Create a domains activity intent.
2502 val domainsIntent = Intent(this, DomainsActivity::class.java)
2504 // Add the extra information to the intent.
2505 domainsIntent.putExtra(CURRENT_URL, currentWebView!!.url)
2506 domainsIntent.putExtra(CURRENT_IP_ADDRESSES, currentWebView!!.currentIpAddresses)
2508 // Get the current certificate.
2509 val sslCertificate = currentWebView!!.certificate
2511 // Check to see if the SSL certificate is populated.
2512 if (sslCertificate != null) {
2513 // Extract the certificate to strings.
2514 val issuedToCName = sslCertificate.issuedTo.cName
2515 val issuedToOName = sslCertificate.issuedTo.oName
2516 val issuedToUName = sslCertificate.issuedTo.uName
2517 val issuedByCName = sslCertificate.issuedBy.cName
2518 val issuedByOName = sslCertificate.issuedBy.oName
2519 val issuedByUName = sslCertificate.issuedBy.uName
2520 val startDateLong = sslCertificate.validNotBeforeDate.time
2521 val endDateLong = sslCertificate.validNotAfterDate.time
2523 // Add the certificate to the intent.
2524 domainsIntent.putExtra(SSL_ISSUED_TO_CNAME, issuedToCName)
2525 domainsIntent.putExtra(SSL_ISSUED_TO_ONAME, issuedToOName)
2526 domainsIntent.putExtra(SSL_ISSUED_TO_UNAME, issuedToUName)
2527 domainsIntent.putExtra(SSL_ISSUED_BY_CNAME, issuedByCName)
2528 domainsIntent.putExtra(SSL_ISSUED_BY_ONAME, issuedByOName)
2529 domainsIntent.putExtra(SSL_ISSUED_BY_UNAME, issuedByUName)
2530 domainsIntent.putExtra(SSL_START_DATE, startDateLong)
2531 domainsIntent.putExtra(SSL_END_DATE, endDateLong)
2535 startActivity(domainsIntent)
2538 R.id.settings -> { // Settings.
2539 // Set the reapply on restart flags.
2540 reapplyAppSettingsOnRestart = true
2541 reapplyDomainSettingsOnRestart = true
2543 // Create a settings intent.
2544 val settingsIntent = Intent(this, SettingsActivity::class.java)
2547 startActivity(settingsIntent)
2550 R.id.import_export -> { // Import/Export.
2551 // Create an intent to launch the import/export activity.
2552 val importExportIntent = Intent(this, ImportExportActivity::class.java)
2555 startActivity(importExportIntent)
2558 R.id.logcat -> { // Logcat.
2559 // Create an intent to launch the logcat activity.
2560 val logcatIntent = Intent(this, LogcatActivity::class.java)
2563 startActivity(logcatIntent)
2566 R.id.webview_devtools -> { // WebView DevTools.
2567 // Create a WebView DevTools intent.
2568 val webViewDevToolsIntent = Intent("com.android.webview.SHOW_DEV_UI")
2570 // Launch as a new task so that the WebView DevTools and Privacy Browser show as a separate windows in the recent tasks list.
2571 webViewDevToolsIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2574 startActivity(webViewDevToolsIntent)
2577 R.id.guide -> { // Guide.
2578 // Create an intent to launch the guide activity.
2579 val guideIntent = Intent(this, GuideActivity::class.java)
2582 startActivity(guideIntent)
2585 R.id.about -> { // About
2586 // Create an intent to launch the about activity.
2587 val aboutIntent = Intent(this, AboutActivity::class.java)
2589 // Create a string array for the filter list versions.
2590 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])
2592 // Add the filter list versions to the intent.
2593 aboutIntent.putExtra(FILTERLIST_VERSIONS, filterListVersions)
2596 startActivity(aboutIntent)
2600 // Close the navigation drawer.
2601 drawerLayout.closeDrawer(GravityCompat.START)
2607 override fun onCreateContextMenu(contextMenu: ContextMenu, view: View, contextMenuInfo: ContextMenu.ContextMenuInfo?) {
2608 // Get the hit test result.
2609 val hitTestResult = currentWebView!!.hitTestResult
2611 // Define the URL strings.
2612 val imageUrl: String?
2613 val linkUrl: String?
2615 // Get a handle for the clipboard manager.
2616 val clipboardManager = (getSystemService(CLIPBOARD_SERVICE) as ClipboardManager)
2618 // Process the link according to the type.
2619 when (hitTestResult.type) {
2620 // `SRC_ANCHOR_TYPE` is a link.
2621 WebView.HitTestResult.SRC_ANCHOR_TYPE -> {
2622 // Get the target URL.
2623 linkUrl = hitTestResult.extra!!
2625 // Set the target URL as the context menu title.
2626 contextMenu.setHeaderTitle(linkUrl)
2628 // Add an open in new tab entry.
2629 contextMenu.add(R.string.open_in_new_tab).setOnMenuItemClickListener {
2630 // Load the link URL in a new tab and move to it.
2631 addNewPage(linkUrl, adjacent = true, moveToTab = true)
2633 // Consume the event.
2637 // Add an open in background entry.
2638 contextMenu.add(R.string.open_in_background).setOnMenuItemClickListener {
2639 // Load the link URL in a new tab but do not move to it.
2640 addNewPage(linkUrl, adjacent = true, moveToTab = false)
2642 // Consume the event.
2646 // Add an open with app entry.
2647 contextMenu.add(R.string.open_with_app).setOnMenuItemClickListener {
2648 // Open the URL with another app.
2649 openWithApp(linkUrl)
2651 // Consume the event.
2655 // Add an open with browser entry.
2656 contextMenu.add(R.string.open_with_browser).setOnMenuItemClickListener {
2657 // Open the URL with another browser.
2658 openWithBrowser(linkUrl)
2660 // Consume the event.
2664 // Add a copy URL entry.
2665 contextMenu.add(R.string.copy_url).setOnMenuItemClickListener {
2666 // Save the link URL in a clip data.
2667 val srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl)
2669 // Set the clip data as the clipboard's primary clip.
2670 clipboardManager.setPrimaryClip(srcAnchorTypeClipData)
2672 // Consume the event.
2676 // Add a Save URL entry.
2677 contextMenu.add(R.string.save_url).setOnMenuItemClickListener {
2678 // Check the download preference.
2679 if (downloadWithExternalApp) // Download with an external app.
2680 downloadUrlWithExternalApp(linkUrl)
2681 else // Handle the download inside of Privacy Browser. The dialog will be displayed once the file size and the content disposition have been acquired.
2682 PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, linkUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
2684 // Consume the event.
2688 // Add a Share URL entry.
2689 contextMenu.add(R.string.share_url).setOnMenuItemClickListener {
2690 // Create the share intent.
2691 val shareUrlIntent = Intent(Intent.ACTION_SEND)
2693 // Add the URL to the intent.
2694 shareUrlIntent.putExtra(Intent.EXTRA_TEXT, linkUrl)
2696 // Set the MIME type.
2697 shareUrlIntent.type = "text/plain"
2699 // Set the intent to open in a new task.
2700 shareUrlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
2703 startActivity(Intent.createChooser(shareUrlIntent, getString(R.string.share_url)))
2705 // Consume the event.
2709 // Add an empty cancel entry, which by default closes the context menu.
2710 contextMenu.add(R.string.cancel)
2713 // `IMAGE_TYPE` is an image.
2714 WebView.HitTestResult.IMAGE_TYPE -> {
2715 // Get the image URL.
2716 imageUrl = hitTestResult.extra!!
2718 // Set the context menu title.
2719 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.
2720 contextMenu.setHeaderTitle(imageUrl.substring(0, 100))
2721 else // The image URL does not contain the full image data. Set the image URL as the title of the context menu.
2722 contextMenu.setHeaderTitle(imageUrl)
2724 // Add an open in new tab entry.
2725 contextMenu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener {
2726 // Load the image in a new tab.
2727 addNewPage(imageUrl, adjacent = true, moveToTab = true)
2729 // Consume the event.
2733 // Add an open with app entry.
2734 contextMenu.add(R.string.open_with_app).setOnMenuItemClickListener {
2735 // Open the image URL with an external app.
2736 openWithApp(imageUrl)
2738 // Consume the event.
2742 // Add an open with browser entry.
2743 contextMenu.add(R.string.open_with_browser).setOnMenuItemClickListener {
2744 // Open the image URL with an external browser.
2745 openWithBrowser(imageUrl)
2747 // Consume the event.
2751 // Add a view image entry.
2752 contextMenu.add(R.string.view_image).setOnMenuItemClickListener {
2753 // Load the image in the current tab.
2754 loadUrl(currentWebView!!, imageUrl)
2756 // Consume the event.
2760 // Add a save image entry.
2761 contextMenu.add(R.string.save_image).setOnMenuItemClickListener {
2762 // Check the download preference.
2763 if (downloadWithExternalApp) { // Download with an external app.
2764 downloadUrlWithExternalApp(imageUrl)
2765 } else { // Handle the download inside of Privacy Browser. The dialog will be displayed once the file size and the content disposition have been acquired.
2766 PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, imageUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
2769 // Consume the event.
2773 // Add a copy URL entry.
2774 contextMenu.add(R.string.copy_url).setOnMenuItemClickListener {
2775 // Save the image URL in a clip data.
2776 val imageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl)
2778 // Set the clip data as the clipboard's primary clip.
2779 clipboardManager.setPrimaryClip(imageTypeClipData)
2781 // Consume the event.
2785 // Add a Share URL entry.
2786 contextMenu.add(R.string.share_url).setOnMenuItemClickListener {
2787 // Create the share intent.
2788 val shareUrlIntent = Intent(Intent.ACTION_SEND)
2790 // Add the URL to the intent.
2791 shareUrlIntent.putExtra(Intent.EXTRA_TEXT, imageUrl)
2793 // Set the MIME type.
2794 shareUrlIntent.type = "text/plain"
2796 // Set the intent to open in a new task.
2797 shareUrlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
2800 startActivity(Intent.createChooser(shareUrlIntent, getString(R.string.share_url)))
2802 // Consume the event.
2806 // Add an empty cancel entry, which by default closes the context menu.
2807 contextMenu.add(R.string.cancel)
2810 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2811 WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE -> {
2812 // Get the image URL.
2813 imageUrl = hitTestResult.extra!!
2815 // Instantiate a handler.
2816 val handler = Handler(Looper.getMainLooper())
2818 // Get a handle for the handler message.
2819 val message = handler.obtainMessage()
2821 // Request the image details from the last touched node be returned in the message.
2822 currentWebView!!.requestFocusNodeHref(message)
2824 // Get the link URL from the message data.
2825 linkUrl = message.data.getString("url")!!
2827 // Set the link URL as the title of the context menu.
2828 contextMenu.setHeaderTitle(linkUrl)
2830 // Add an open in new tab entry.
2831 contextMenu.add(R.string.open_in_new_tab).setOnMenuItemClickListener {
2832 // Load the link URL in a new tab and move to it.
2833 addNewPage(linkUrl, adjacent = true, moveToTab = true)
2835 // Consume the event.
2839 // Add an open in background entry.
2840 contextMenu.add(R.string.open_in_background).setOnMenuItemClickListener {
2841 // Lod the link URL in a new tab but do not move to it.
2842 addNewPage(linkUrl, adjacent = true, moveToTab = false)
2844 // Consume the event.
2848 // Add an open image in new tab entry.
2849 contextMenu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener {
2850 // Load the image in a new tab and move to it.
2851 addNewPage(imageUrl, adjacent = true, moveToTab = true)
2853 // Consume the event.
2857 // Add an open with app entry.
2858 contextMenu.add(R.string.open_with_app).setOnMenuItemClickListener {
2859 // Open the link URL with an external app.
2860 openWithApp(linkUrl)
2862 // Consume the event.
2866 // Add an open with browser entry.
2867 contextMenu.add(R.string.open_with_browser).setOnMenuItemClickListener {
2868 // Open the link URL with an external browser.
2869 openWithBrowser(linkUrl)
2871 // Consume the event.
2875 // Add a view image entry.
2876 contextMenu.add(R.string.view_image).setOnMenuItemClickListener {
2877 // View the image in the current tab.
2878 loadUrl(currentWebView!!, imageUrl)
2880 // Consume the event.
2884 // Add a Save Image entry.
2885 contextMenu.add(R.string.save_image).setOnMenuItemClickListener {
2886 // Check the download preference.
2887 if (downloadWithExternalApp) // Download with an external app.
2888 downloadUrlWithExternalApp(imageUrl)
2889 else // Handle the download inside of Privacy Browser. The dialog will be displayed once the file size and the content disposition have been acquired.
2890 PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, imageUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
2892 // Consume the event.
2896 // Add a Share Image entry.
2897 contextMenu.add(R.string.share_image).setOnMenuItemClickListener {
2898 // Create the share intent.
2899 val shareUrlIntent = Intent(Intent.ACTION_SEND)
2901 // Add the URL to the intent.
2902 shareUrlIntent.putExtra(Intent.EXTRA_TEXT, imageUrl)
2904 // Set the MIME type.
2905 shareUrlIntent.type = "text/plain"
2907 // Set the intent to open in a new task.
2908 shareUrlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
2911 startActivity(Intent.createChooser(shareUrlIntent, getString(R.string.share_url)))
2913 // Consume the event.
2917 // Add a copy URL entry.
2918 contextMenu.add(R.string.copy_url).setOnMenuItemClickListener {
2919 // Save the link URL in a clip data.
2920 val srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl)
2922 // Set the clip data as the clipboard's primary clip.
2923 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData)
2925 // Consume the event.
2929 // Add a save URL entry.
2930 contextMenu.add(R.string.save_url).setOnMenuItemClickListener {
2931 // Check the download preference.
2932 if (downloadWithExternalApp) // Download with an external app.
2933 downloadUrlWithExternalApp(linkUrl)
2934 else // Handle the download inside of Privacy Browser. The dialog will be displayed once the file size and the content disposition have been acquired.
2935 PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, linkUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
2937 // Consume the event.
2941 // Add a Share URL entry.
2942 contextMenu.add(R.string.share_url).setOnMenuItemClickListener {
2943 // Create the share intent.
2944 val shareUrlIntent = Intent(Intent.ACTION_SEND)
2946 // Add the URL to the intent.
2947 shareUrlIntent.putExtra(Intent.EXTRA_TEXT, linkUrl)
2949 // Set the MIME type.
2950 shareUrlIntent.type = "text/plain"
2952 // Set the intent to open in a new task.
2953 shareUrlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
2956 startActivity(Intent.createChooser(shareUrlIntent, getString(R.string.share_url)))
2958 // Consume the event.
2962 // Add an empty cancel entry, which by default closes the context menu.
2963 contextMenu.add(R.string.cancel)
2966 WebView.HitTestResult.EMAIL_TYPE -> {
2967 // Get the target URL.
2968 linkUrl = hitTestResult.extra
2970 // Set the target URL as the title of the context menu.
2971 contextMenu.setHeaderTitle(linkUrl)
2973 // Add a write email entry.
2974 contextMenu.add(R.string.write_email).setOnMenuItemClickListener {
2975 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2976 val emailIntent = Intent(Intent.ACTION_SENDTO)
2978 // Parse the url and set it as the data for the intent.
2979 emailIntent.data = Uri.parse("mailto:$linkUrl")
2981 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2982 emailIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2986 startActivity(emailIntent)
2987 } catch (exception: ActivityNotFoundException) {
2988 // Display a snackbar.
2989 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
2992 // Consume the event.
2996 // Add a copy email address entry.
2997 contextMenu.add(R.string.copy_email_address).setOnMenuItemClickListener {
2998 // Save the email address in a clip data.
2999 val srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl)
3001 // Set the clip data as the clipboard's primary clip.
3002 clipboardManager.setPrimaryClip(srcEmailTypeClipData)
3004 // Consume the event.
3008 // Add an empty cancel entry, which by default closes the context menu.
3009 contextMenu.add(R.string.cancel)
3014 // The view parameter cannot be removed because it is called from the layout onClick.
3015 fun addTab(@Suppress("UNUSED_PARAMETER")view: View?) {
3016 // Add a new tab with a blank URL.
3017 addNewPage(urlString = "", adjacent = true, moveToTab = true)
3020 private fun addNewPage(urlString: String, adjacent: Boolean, moveToTab: Boolean) {
3021 // Clear the focus from the URL edit text, so that it will be populated with the information from the new tab.
3022 urlEditText.clearFocus()
3024 // Get the new tab position.
3025 val newTabPosition = if (adjacent) // The new tab position is immediately to the right of the current tab position.
3026 tabLayout.selectedTabPosition + 1
3027 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.
3030 // Add the new WebView page.
3031 webViewStateAdapter!!.addPage(newTabPosition, urlString)
3034 addNewTab(newTabPosition, moveToTab)
3037 private fun addNewTab(newTabPosition: Int, moveToTab: Boolean) {
3038 // Check to see if the new page is ready.
3039 if (webViewStateAdapter!!.itemCount >= tabLayout.tabCount) { // The new page is ready.
3040 // Create a new tab.
3041 val newTab = tabLayout.newTab()
3043 // Set a custom view on the new tab.
3044 newTab.setCustomView(R.layout.tab_custom_view)
3047 tabLayout.addTab(newTab, newTabPosition, moveToTab)
3049 // 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.
3050 if (newTabPosition == 0)
3051 tabLayout.selectTab(newTab)
3053 // Scroll to the new tab position if moving to the new tab.
3056 tabLayout.setScrollPosition(newTabPosition, 0F, false, false)
3059 // Show the app bar if it is at the bottom of the screen and the new tab is taking focus.
3060 if (bottomAppBar && moveToTab && appBarLayout.translationY != 0f) {
3061 // Animate the bottom app bar onto the screen.
3062 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0f)
3065 objectAnimator.start()
3067 } else { // The new page is not ready.
3068 // Create a new tab handler.
3069 val newTabHandler = Handler(Looper.getMainLooper())
3071 // Create a new tab runnable.
3072 val newTabRunnable = Runnable {
3073 // Create the new tab.
3074 addNewTab(newTabPosition, moveToTab)
3077 // Try adding the new tab again after 50 milliseconds.
3078 newTabHandler.postDelayed(newTabRunnable, 50)
3082 private fun applyAppSettings() {
3083 // 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.
3084 defaultJavaScript = sharedPreferences.getBoolean(getString(R.string.javascript_key), false)
3085 defaultCookies = sharedPreferences.getBoolean(getString(R.string.cookies_key), false)
3086 defaultDomStorage = sharedPreferences.getBoolean(getString(R.string.dom_storage_key), false)
3087 defaultFormData = sharedPreferences.getBoolean(getString(R.string.save_form_data_key), false) // Form data can be removed once the minimum API >= 26.
3088 defaultEasyList = sharedPreferences.getBoolean(getString(R.string.easylist_key), true)
3089 defaultEasyPrivacy = sharedPreferences.getBoolean(getString(R.string.easyprivacy_key), true)
3090 defaultFanboysAnnoyanceList = sharedPreferences.getBoolean(getString(R.string.fanboys_annoyance_list_key), true)
3091 defaultFanboysSocialBlockingList = sharedPreferences.getBoolean(getString(R.string.fanboys_social_blocking_list_key), true)
3092 defaultUltraList = sharedPreferences.getBoolean(getString(R.string.ultralist_key), true)
3093 defaultUltraPrivacy = sharedPreferences.getBoolean(getString(R.string.ultraprivacy_key), true)
3094 defaultBlockAllThirdPartyRequests = sharedPreferences.getBoolean(getString(R.string.block_all_third_party_requests_key), false)
3095 defaultFontSizeString = sharedPreferences.getString(getString(R.string.font_size_key), getString(R.string.font_size_default_value))!!
3096 defaultUserAgentName = sharedPreferences.getString(getString(R.string.user_agent_key), getString(R.string.user_agent_default_value))!!
3097 defaultSwipeToRefresh = sharedPreferences.getBoolean(getString(R.string.swipe_to_refresh_key), true)
3098 defaultWebViewTheme = sharedPreferences.getString(getString(R.string.webview_theme_key), getString(R.string.webview_theme_default_value))!!
3099 defaultWideViewport = sharedPreferences.getBoolean(getString(R.string.wide_viewport_key), true)
3100 defaultDisplayWebpageImages = sharedPreferences.getBoolean(getString(R.string.display_webpage_images_key), true)
3102 // 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.
3103 webViewThemeEntryValuesStringArray = resources.getStringArray(R.array.webview_theme_entry_values)
3105 // Get the user agent string arrays. These are done here so that expensive resource requests are not made each time a domain is loaded.
3106 userAgentDataArray = resources.getStringArray(R.array.user_agent_data)
3107 userAgentNamesArray = resources.getStringArray(R.array.user_agent_names)
3109 // Get the user agent array adapters. These are done here so that expensive resource requests are not made each time a domain is loaded.
3110 userAgentDataArrayAdapter = ArrayAdapter.createFromResource(this, R.array.user_agent_data, R.layout.spinner_item)
3111 userAgentNamesArrayAdapter = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item)
3113 // Store the values from the shared preferences in variables.
3114 incognitoModeEnabled = sharedPreferences.getBoolean(getString(R.string.incognito_mode_key), false)
3115 sanitizeTrackingQueries = sharedPreferences.getBoolean(getString(R.string.tracking_queries_key), true)
3116 sanitizeAmpRedirects = sharedPreferences.getBoolean(getString(R.string.amp_redirects_key), true)
3117 proxyMode = sharedPreferences.getString(getString(R.string.proxy_key), getString(R.string.proxy_default_value))!!
3118 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean(getString(R.string.full_screen_browsing_mode_key), false)
3119 hideAppBar = sharedPreferences.getBoolean(getString(R.string.hide_app_bar_key), true)
3120 downloadWithExternalApp = sharedPreferences.getBoolean(getString(R.string.download_with_external_app_key), false)
3121 scrollAppBar = sharedPreferences.getBoolean(getString(R.string.scroll_app_bar_key), true)
3123 // Apply the saved proxy mode if the app has been restarted.
3124 if (savedProxyMode != null) {
3125 // Apply the saved proxy mode.
3126 proxyMode = savedProxyMode!!
3128 // Reset the saved proxy mode.
3129 savedProxyMode = null
3132 // Get the search string.
3133 val searchString = sharedPreferences.getString(getString(R.string.search_key), getString(R.string.search_default_value))!!
3135 // Set the search string, using the custom search URL if specified.
3136 searchURL = if (searchString == getString(R.string.custom_url_item))
3137 sharedPreferences.getString(getString(R.string.search_custom_url_key), getString(R.string.search_custom_url_default_value))!!
3144 // Adjust the layout and scrolling parameters according to the position of the app bar.
3145 if (bottomAppBar) { // The app bar is on the bottom.
3147 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) { // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
3148 // Reset the WebView padding to fill the available space.
3149 swipeRefreshLayout.setPadding(0, 0, 0, 0)
3150 } else { // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
3151 // Move the WebView above the app bar layout.
3152 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
3154 // Show the app bar if it is scrolled off the screen.
3155 if (appBarLayout.translationY != 0f) {
3156 // Animate the bottom app bar onto the screen.
3157 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0f)
3160 objectAnimator.start()
3163 } else { // The app bar is on the top.
3164 // Get the current layout parameters. Using coordinator layout parameters allows the `setBehavior()` command and using app bar layout parameters allows the `setScrollFlags()` command.
3165 val swipeRefreshLayoutParams = swipeRefreshLayout.layoutParams as CoordinatorLayout.LayoutParams
3166 val toolbarLayoutParams = toolbar.layoutParams as AppBarLayout.LayoutParams
3167 val findOnPageLayoutParams = findOnPageLinearLayout.layoutParams as AppBarLayout.LayoutParams
3168 val tabsLayoutParams = tabsLinearLayout.layoutParams as AppBarLayout.LayoutParams
3170 // Add the scrolling behavior to the layout parameters.
3172 // Enable scrolling of the app bar.
3173 swipeRefreshLayoutParams.behavior = AppBarLayout.ScrollingViewBehavior()
3174 toolbarLayoutParams.scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS or AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP
3175 findOnPageLayoutParams.scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS or AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP
3176 tabsLayoutParams.scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS or AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP
3178 // Disable scrolling of the app bar.
3179 swipeRefreshLayoutParams.behavior = null
3180 toolbarLayoutParams.scrollFlags = 0
3181 findOnPageLayoutParams.scrollFlags = 0
3182 tabsLayoutParams.scrollFlags = 0
3184 // Expand the app bar if it is currently collapsed.
3185 appBarLayout.setExpanded(true)
3188 // Set the app bar scrolling for each WebView.
3189 for (i in 0 until webViewStateAdapter!!.itemCount) {
3190 // Get the WebView tab fragment.
3191 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
3193 // Get the fragment view.
3194 val fragmentView = webViewTabFragment.view
3196 // Only modify the WebViews if they exist.
3197 if (fragmentView != null) {
3198 // Get the nested scroll WebView from the tab fragment.
3199 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
3201 // Set the app bar scrolling.
3202 nestedScrollWebView.isNestedScrollingEnabled = scrollAppBar
3207 // Update the full screen browsing mode settings.
3208 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
3209 // Update the visibility of the app bar, which might have changed in the settings.
3211 // Hide the tab linear layout.
3212 tabsLinearLayout.visibility = View.GONE
3214 // Hide the app bar.
3217 // Show the tab linear layout.
3218 tabsLinearLayout.visibility = View.VISIBLE
3220 // Show the app bar.
3224 /* Hide the system bars.
3225 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3226 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
3227 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3228 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3231 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
3232 @Suppress("DEPRECATION")
3233 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
3234 } else { // Privacy Browser is not in full screen browsing mode.
3235 // 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.
3236 inFullScreenBrowsingMode = false
3238 // Show the tab linear layout.
3239 tabsLinearLayout.visibility = View.VISIBLE
3241 // Show the app bar.
3244 // Remove the `SYSTEM_UI` flags from the root frame layout. The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
3245 @Suppress("DEPRECATION")
3246 rootFrameLayout.systemUiVisibility = 0
3250 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
3251 @SuppressLint("SetJavaScriptEnabled")
3252 private fun applyDomainSettings(nestedScrollWebView: NestedScrollWebView, url: String?, resetTab: Boolean, reloadWebsite: Boolean, loadUrl: Boolean) {
3253 // Store the current URL.
3254 nestedScrollWebView.currentUrl = url!!
3256 // Parse the URL into a URI.
3257 val uri = Uri.parse(url)
3259 // Extract the domain from the URI.
3260 var newHostName = uri.host
3262 // Strings don't like to be null.
3263 if (newHostName == null)
3266 // 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.
3267 if ((nestedScrollWebView.currentDomainName != newHostName) || (newHostName == "")) { // A new domain is being loaded.
3268 // Set the new host name as the current domain name.
3269 nestedScrollWebView.currentDomainName = newHostName
3271 // Reset the ignoring of pinned domain information.
3272 nestedScrollWebView.ignorePinnedDomainInformation = false
3274 // Clear any pinned SSL certificate or IP addresses.
3275 nestedScrollWebView.clearPinnedSslCertificate()
3276 nestedScrollWebView.pinnedIpAddresses = ""
3278 // Reset the favorite icon if specified.
3280 // Initialize the favorite icon.
3281 nestedScrollWebView.initializeFavoriteIcon()
3283 // Get the current page position.
3284 val currentPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
3286 // Get the corresponding tab.
3287 val tab = tabLayout.getTabAt(currentPagePosition)
3289 // Update the tab if it isn't null, which sometimes happens when restarting from the background.
3291 // Get the tab custom view.
3292 val tabCustomView = tab.customView!!
3294 // Get the tab views.
3295 val tabFavoriteIconImageView = tabCustomView.findViewById<ImageView>(R.id.favorite_icon_imageview)
3296 val tabTitleTextView = tabCustomView.findViewById<TextView>(R.id.title_textview)
3298 // Store the current values in case they need to be restored.
3299 nestedScrollWebView.previousFavoriteIconDrawable = tabFavoriteIconImageView.drawable
3300 nestedScrollWebView.previousWebpageTitle = tabTitleTextView.text.toString()
3302 // Set the default favorite icon as the favorite icon for this tab.
3303 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nestedScrollWebView.getFavoriteIcon(), 64, 64, true))
3305 // Set the loading title text.
3306 tabTitleTextView.setText(R.string.loading)
3310 // Initialize the domain name in database variable.
3311 var domainNameInDatabase: String? = null
3313 // Check the hostname against the domain settings set.
3314 if (domainsSettingsSet.contains(newHostName)) { // The hostname is contained in the domain settings set.
3315 // Record the domain name in the database.
3316 domainNameInDatabase = newHostName
3318 // Set the domain settings applied tracker to true.
3319 nestedScrollWebView.domainSettingsApplied = true
3320 } else { // The hostname is not contained in the domain settings set.
3321 // Set the domain settings applied tracker to false.
3322 nestedScrollWebView.domainSettingsApplied = false
3325 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3326 while (!nestedScrollWebView.domainSettingsApplied && newHostName!!.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the hostname.
3327 if (domainsSettingsSet.contains("*.$newHostName")) { // Check the host name prepended by `*.`.
3328 // Set the domain settings applied tracker to true.
3329 nestedScrollWebView.domainSettingsApplied = true
3331 // Store the applied domain names as it appears in the database.
3332 domainNameInDatabase = "*.$newHostName"
3335 // Strip out the lowest subdomain of of the host name.
3336 newHostName = newHostName.substring(newHostName.indexOf(".") + 1)
3339 // Apply either the domain settings or the default settings.
3340 if (nestedScrollWebView.domainSettingsApplied) { // The url has custom domain settings.
3341 // Get a cursor for the current host.
3342 val currentDomainSettingsCursor = domainsDatabaseHelper!!.getCursorForDomainName(domainNameInDatabase!!)
3344 // Move to the first position.
3345 currentDomainSettingsCursor.moveToFirst()
3347 // Get the settings from the cursor.
3348 nestedScrollWebView.domainSettingsDatabaseId = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ID))
3349 val javaScriptInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_JAVASCRIPT))
3350 val cookiesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(COOKIES))
3351 val domStorageInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_DOM_STORAGE))
3352 val formDataInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_FORM_DATA)) // Form data can be removed once the minimum API >= 26.
3353 val easyListInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_EASYLIST))
3354 val easyPrivacyInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_EASYPRIVACY))
3355 val fanboysAnnoyanceListInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_FANBOYS_ANNOYANCE_LIST))
3356 val fanboysSocialBlockingListInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST))
3357 val ultraListInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.ULTRALIST))
3358 val ultraPrivacyInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_ULTRAPRIVACY))
3359 val blockAllThirdPartyRequestsInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.BLOCK_ALL_THIRD_PARTY_REQUESTS))
3360 val userAgentName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.USER_AGENT))
3361 val fontSize = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(FONT_SIZE))
3362 val swipeToRefreshInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(SWIPE_TO_REFRESH))
3363 val webViewThemeInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(WEBVIEW_THEME))
3364 val wideViewportInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(WIDE_VIEWPORT))
3365 val displayWebpageImagesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DISPLAY_IMAGES))
3366 val pinnedSslCertificate = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(PINNED_SSL_CERTIFICATE)) == 1)
3367 val pinnedSslIssuedToCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_TO_COMMON_NAME))
3368 val pinnedSslIssuedToOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_TO_ORGANIZATION))
3369 val pinnedSslIssuedToUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_TO_ORGANIZATIONAL_UNIT))
3370 val pinnedSslIssuedByCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_BY_COMMON_NAME))
3371 val pinnedSslIssuedByOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_BY_ORGANIZATION))
3372 val pinnedSslIssuedByUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_BY_ORGANIZATIONAL_UNIT))
3373 val pinnedSslStartDate = Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.SSL_START_DATE)))
3374 val pinnedSslEndDate = Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.SSL_END_DATE)))
3375 val pinnedIpAddresses = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(PINNED_IP_ADDRESSES)) == 1)
3376 val pinnedHostIpAddresses = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(IP_ADDRESSES))
3378 // Close the current host domain settings cursor.
3379 currentDomainSettingsCursor.close()
3381 // Set the JavaScript status.
3382 when (javaScriptInt) {
3383 SYSTEM_DEFAULT -> nestedScrollWebView.settings.javaScriptEnabled = defaultJavaScript
3384 ENABLED -> nestedScrollWebView.settings.javaScriptEnabled = true
3385 DISABLED -> nestedScrollWebView.settings.javaScriptEnabled = false
3388 // Store the cookies status.
3390 SYSTEM_DEFAULT -> nestedScrollWebView.acceptCookies = defaultCookies
3391 ENABLED -> nestedScrollWebView.acceptCookies = true
3392 DISABLED -> nestedScrollWebView.acceptCookies = false
3395 // Apply the cookies status.
3396 cookieManager.setAcceptCookie(nestedScrollWebView.acceptCookies)
3398 // Set the DOM storage status.
3399 when (domStorageInt) {
3400 SYSTEM_DEFAULT -> nestedScrollWebView.settings.domStorageEnabled = defaultDomStorage
3401 ENABLED -> nestedScrollWebView.settings.domStorageEnabled = true
3402 DISABLED -> nestedScrollWebView.settings.domStorageEnabled = false
3405 // Apply the form data setting if the API < 26.
3406 @Suppress("DEPRECATION")
3407 if (Build.VERSION.SDK_INT < 26) {
3408 // Set the form data status.
3409 when (formDataInt) {
3410 SYSTEM_DEFAULT -> nestedScrollWebView.settings.saveFormData = defaultFormData
3411 ENABLED -> nestedScrollWebView.settings.saveFormData = true
3412 DISABLED -> nestedScrollWebView.settings.saveFormData = false
3416 // Set the EasyList status.
3417 when (easyListInt) {
3418 SYSTEM_DEFAULT -> nestedScrollWebView.easyListEnabled = defaultEasyList
3419 ENABLED -> nestedScrollWebView.easyListEnabled = true
3420 DISABLED -> nestedScrollWebView.easyListEnabled = false
3423 // Set the EasyPrivacy status.
3424 when (easyPrivacyInt) {
3425 SYSTEM_DEFAULT -> nestedScrollWebView.easyPrivacyEnabled = defaultEasyPrivacy
3426 ENABLED -> nestedScrollWebView.easyPrivacyEnabled = true
3427 DISABLED -> nestedScrollWebView.easyPrivacyEnabled = false
3430 // Set the Fanboy's Annoyance List status.
3431 when (fanboysAnnoyanceListInt) {
3432 SYSTEM_DEFAULT -> nestedScrollWebView.fanboysAnnoyanceListEnabled = defaultFanboysAnnoyanceList
3433 ENABLED -> nestedScrollWebView.fanboysAnnoyanceListEnabled = true
3434 DISABLED -> nestedScrollWebView.fanboysAnnoyanceListEnabled = false
3437 // Set the Fanboy's Social Blocking List status.
3438 when (fanboysSocialBlockingListInt) {
3439 SYSTEM_DEFAULT -> nestedScrollWebView.fanboysSocialBlockingListEnabled = defaultFanboysSocialBlockingList
3440 ENABLED -> nestedScrollWebView.fanboysSocialBlockingListEnabled = true
3441 DISABLED -> nestedScrollWebView.fanboysSocialBlockingListEnabled = false
3444 // Set the UltraList status.
3445 when (ultraListInt) {
3446 SYSTEM_DEFAULT -> nestedScrollWebView.ultraListEnabled = defaultUltraList
3447 ENABLED -> nestedScrollWebView.ultraListEnabled = true
3448 DISABLED -> nestedScrollWebView.ultraListEnabled = false
3451 // Set the UltraPrivacy status.
3452 when (ultraPrivacyInt) {
3453 SYSTEM_DEFAULT -> nestedScrollWebView.ultraPrivacyEnabled = defaultUltraPrivacy
3454 ENABLED -> nestedScrollWebView.ultraPrivacyEnabled = true
3455 DISABLED -> nestedScrollWebView.ultraPrivacyEnabled = false
3458 // Set the block all third-party requests status.
3459 when (blockAllThirdPartyRequestsInt) {
3460 SYSTEM_DEFAULT -> nestedScrollWebView.blockAllThirdPartyRequests = defaultBlockAllThirdPartyRequests
3461 ENABLED -> nestedScrollWebView.blockAllThirdPartyRequests = true
3462 DISABLED -> nestedScrollWebView.blockAllThirdPartyRequests = false
3465 // Set the user agent.
3466 if (userAgentName == getString(R.string.system_default_user_agent)) { // Use the system default user agent.
3467 // Set the user agent according to the system default.
3468 when (val defaultUserAgentArrayPosition = userAgentNamesArrayAdapter.getPosition(defaultUserAgentName)) {
3469 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.
3470 nestedScrollWebView.settings.userAgentString = defaultUserAgentName
3472 SETTINGS_WEBVIEW_DEFAULT_USER_AGENT -> // Set the user agent to `""`, which uses the default value.
3473 nestedScrollWebView.settings.userAgentString = ""
3475 SETTINGS_CUSTOM_USER_AGENT -> // Set the default custom user agent.
3476 nestedScrollWebView.settings.userAgentString = sharedPreferences.getString(getString(R.string.custom_user_agent_key), getString(R.string.custom_user_agent_default_value))
3478 else -> // Get the user agent string from the user agent data array
3479 nestedScrollWebView.settings.userAgentString = userAgentDataArray[defaultUserAgentArrayPosition]
3481 } else { // Set the user agent according to the stored name.
3482 // Set the user agent.
3483 when (val userAgentArrayPosition = userAgentNamesArrayAdapter.getPosition(userAgentName)) {
3484 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3485 UNRECOGNIZED_USER_AGENT ->
3486 nestedScrollWebView.settings.userAgentString = userAgentName
3488 // Set the user agent to `""`, which uses the default value.
3489 SETTINGS_WEBVIEW_DEFAULT_USER_AGENT ->
3490 nestedScrollWebView.settings.userAgentString = ""
3492 // Get the user agent string from the user agent data array.
3494 nestedScrollWebView.settings.userAgentString = userAgentDataArray[userAgentArrayPosition]
3498 // Apply the font size.
3499 try { // Try the specified font size to see if it is valid.
3500 if (fontSize == 0) { // Apply the default font size.
3501 // Set the font size from the value in the app settings.
3502 nestedScrollWebView.settings.textZoom = defaultFontSizeString.toInt()
3503 } else { // Apply the font size from domain settings.
3504 nestedScrollWebView.settings.textZoom = fontSize
3506 } catch (exception: Exception) { // The specified font size is invalid
3507 // Set the font size to be 100%
3508 nestedScrollWebView.settings.textZoom = 100
3511 // Set swipe to refresh.
3512 when (swipeToRefreshInt) {
3514 // Store the swipe to refresh status in the nested scroll WebView.
3515 nestedScrollWebView.swipeToRefresh = defaultSwipeToRefresh
3517 // Update the swipe refresh layout.
3518 if (defaultSwipeToRefresh) { // Swipe to refresh is enabled.
3519 // 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).
3520 if (currentWebView != null) {
3521 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
3522 swipeRefreshLayout.isEnabled = (currentWebView!!.scrollY == 0)
3524 } else { // Swipe to refresh is disabled.
3525 // Disable the swipe refresh layout.
3526 swipeRefreshLayout.isEnabled = false
3531 // Store the swipe to refresh status in the nested scroll WebView.
3532 nestedScrollWebView.swipeToRefresh = true
3534 // 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).
3535 if (currentWebView != null) {
3536 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
3537 swipeRefreshLayout.isEnabled = (currentWebView!!.scrollY == 0)
3542 // Store the swipe to refresh status in the nested scroll WebView.
3543 nestedScrollWebView.swipeToRefresh = false
3545 // Disable swipe to refresh.
3546 swipeRefreshLayout.isEnabled = false
3550 // Set the WebView theme if algorithmic darkening is supported.
3551 if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {
3552 // Set the WebView theme.
3553 when (webViewThemeInt) {
3554 SYSTEM_DEFAULT -> // Set the WebView theme.
3555 when (defaultWebViewTheme) {
3556 webViewThemeEntryValuesStringArray[1] -> // The light theme is selected. Turn off algorithmic darkening.
3557 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
3559 webViewThemeEntryValuesStringArray[2] -> // The dark theme is selected. Turn on algorithmic darkening.
3560 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
3562 else -> { // The system default theme is selected.
3563 // Get the current system theme status.
3564 val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
3566 // Set the algorithmic darkening according to the current system theme status.
3567 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, currentThemeStatus == Configuration.UI_MODE_NIGHT_YES)
3571 LIGHT_THEME -> // Turn off algorithmic darkening.
3572 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
3574 DARK_THEME -> // Turn on algorithmic darkening.
3575 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
3579 // Set the wide viewport status.
3580 when (wideViewportInt) {
3581 SYSTEM_DEFAULT -> nestedScrollWebView.settings.useWideViewPort = defaultWideViewport
3582 ENABLED -> nestedScrollWebView.settings.useWideViewPort = true
3583 DISABLED -> nestedScrollWebView.settings.useWideViewPort = false
3586 // Set the display webpage images status.
3587 when (displayWebpageImagesInt) {
3588 SYSTEM_DEFAULT -> nestedScrollWebView.settings.loadsImagesAutomatically = defaultDisplayWebpageImages
3589 ENABLED -> nestedScrollWebView.settings.loadsImagesAutomatically = true
3590 DISABLED -> nestedScrollWebView.settings.loadsImagesAutomatically = false
3593 // If there is a pinned SSL certificate, store it in the WebView.
3594 if (pinnedSslCertificate)
3595 nestedScrollWebView.setPinnedSslCertificate(pinnedSslIssuedToCName, pinnedSslIssuedToOName, pinnedSslIssuedToUName, pinnedSslIssuedByCName, pinnedSslIssuedByOName, pinnedSslIssuedByUName,
3596 pinnedSslStartDate, pinnedSslEndDate)
3598 // If there is a pinned IP address, store it in the WebView.
3599 if (pinnedIpAddresses)
3600 nestedScrollWebView.pinnedIpAddresses = pinnedHostIpAddresses
3602 // Set a background on the URL relative layout to indicate that custom domain settings are being used.
3603 urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.drawable.domain_settings_url_background)
3604 } else { // The new URL does not have custom domain settings. Load the defaults.
3605 // Store the values from the shared preferences.
3606 nestedScrollWebView.settings.javaScriptEnabled = defaultJavaScript
3607 nestedScrollWebView.acceptCookies = defaultCookies
3608 nestedScrollWebView.settings.domStorageEnabled = defaultDomStorage
3609 nestedScrollWebView.easyListEnabled = defaultEasyList
3610 nestedScrollWebView.easyPrivacyEnabled = defaultEasyPrivacy
3611 nestedScrollWebView.fanboysAnnoyanceListEnabled = defaultFanboysAnnoyanceList
3612 nestedScrollWebView.fanboysSocialBlockingListEnabled = defaultFanboysSocialBlockingList
3613 nestedScrollWebView.ultraListEnabled = defaultUltraList
3614 nestedScrollWebView.ultraPrivacyEnabled = defaultUltraPrivacy
3615 nestedScrollWebView.blockAllThirdPartyRequests = defaultBlockAllThirdPartyRequests
3617 // Apply the default cookie setting.
3618 cookieManager.setAcceptCookie(nestedScrollWebView.acceptCookies)
3620 // Apply the form data setting if the API < 26.
3621 if (Build.VERSION.SDK_INT < 26)
3622 @Suppress("DEPRECATION")
3623 nestedScrollWebView.settings.saveFormData = defaultFormData
3625 // Apply the default font size setting.
3627 // Try to set the font size from the value in the app settings.
3628 nestedScrollWebView.settings.textZoom = defaultFontSizeString.toInt()
3629 } catch (exception: Exception) {
3630 // If the app settings value is invalid, set the font size to 100%.
3631 nestedScrollWebView.settings.textZoom = 100
3634 // Store the swipe to refresh status in the nested scroll WebView.
3635 nestedScrollWebView.swipeToRefresh = defaultSwipeToRefresh
3637 // Update the swipe refresh layout.
3638 if (defaultSwipeToRefresh) { // Swipe to refresh is enabled.
3639 // 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).
3640 if (currentWebView != null) {
3641 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
3642 swipeRefreshLayout.isEnabled = currentWebView!!.scrollY == 0
3644 } else { // Swipe to refresh is disabled.
3645 // Disable the swipe refresh layout.
3646 swipeRefreshLayout.isEnabled = false
3649 // Reset the domain settings database ID.
3650 nestedScrollWebView.domainSettingsDatabaseId = -1
3652 // Set the user agent.
3653 when (val userAgentArrayPosition = userAgentNamesArrayAdapter.getPosition(defaultUserAgentName)) {
3654 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.
3655 nestedScrollWebView.settings.userAgentString = defaultUserAgentName
3657 SETTINGS_WEBVIEW_DEFAULT_USER_AGENT -> // Set the user agent to `""`, which uses the default value.
3658 nestedScrollWebView.settings.userAgentString = ""
3660 SETTINGS_CUSTOM_USER_AGENT -> // Set the default custom user agent.
3661 nestedScrollWebView.settings.userAgentString = sharedPreferences.getString(getString(R.string.custom_user_agent_key), getString(R.string.custom_user_agent_default_value))
3663 else -> // Get the user agent string from the user agent data array
3664 nestedScrollWebView.settings.userAgentString = userAgentDataArray[userAgentArrayPosition]
3667 // Set the WebView theme if algorithmic darkening is supported.
3668 if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {
3669 // Set the WebView theme.
3670 when (defaultWebViewTheme) {
3671 webViewThemeEntryValuesStringArray[1] -> // The light theme is selected. Turn off algorithmic darkening.
3672 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
3674 webViewThemeEntryValuesStringArray[2] -> // The dark theme is selected. Turn on algorithmic darkening.
3675 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
3677 else -> { // The system default theme is selected. Get the current system theme status.
3678 // Get the current theme status.
3679 val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
3681 // Set the algorithmic darkening according to the current system theme status.
3682 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, currentThemeStatus == Configuration.UI_MODE_NIGHT_YES)
3687 // Set the viewport.
3688 nestedScrollWebView.settings.useWideViewPort = defaultWideViewport
3690 // Set the loading of webpage images.
3691 nestedScrollWebView.settings.loadsImagesAutomatically = defaultDisplayWebpageImages
3693 // Set a transparent background on the URL relative layout.
3694 urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.color.transparent)
3697 // Update the privacy icons.
3698 updatePrivacyIcons(true)
3701 // Reload the website if returning from the Domains activity.
3703 nestedScrollWebView.reload()
3705 // Disable the wide viewport if the source is being viewed.
3706 if (url.startsWith("view-source:"))
3707 nestedScrollWebView.settings.useWideViewPort = false
3709 // 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.
3711 nestedScrollWebView.loadUrl(url)
3714 private fun applyProxy(reloadWebViews: Boolean) {
3715 // Set the proxy according to the mode.
3716 proxyHelper.setProxy(applicationContext, appBarLayout, proxyMode)
3718 // Reset the waiting for proxy tracker.
3719 waitingForProxy = false
3723 ProxyHelper.NONE -> {
3724 // Initialize a color background typed value.
3725 val colorBackgroundTypedValue = TypedValue()
3727 // Get the color background from the theme.
3728 theme.resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true)
3730 // Get the color background int from the typed value.
3731 val colorBackgroundInt = colorBackgroundTypedValue.data
3733 // Set the default app bar layout background.
3734 appBarLayout.setBackgroundColor(colorBackgroundInt)
3737 ProxyHelper.TOR -> {
3738 // Set the app bar background to indicate proxying is enabled.
3739 appBarLayout.setBackgroundResource(R.color.blue_background)
3741 // Check to see if Orbot is installed.
3743 // Get the package manager.
3744 val packageManager = packageManager
3746 // 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.
3747 packageManager.getPackageInfo("org.torproject.android", 0)
3749 // Check to see if the proxy is ready.
3750 if (orbotStatus != ProxyHelper.ORBOT_STATUS_ON) { // Orbot is not ready.
3751 // Set the waiting for proxy status.
3752 waitingForProxy = true
3754 // Show the waiting for proxy dialog if it isn't already displayed.
3755 if (supportFragmentManager.findFragmentByTag(getString(R.string.waiting_for_proxy_dialog)) == null) {
3756 // Get a handle for the waiting for proxy alert dialog.
3757 val waitingForProxyDialogFragment = WaitingForProxyDialog()
3759 // Try to show the dialog. Sometimes the window is not yet active if returning from Settings.
3761 // Show the waiting for proxy alert dialog.
3762 waitingForProxyDialogFragment.show(supportFragmentManager, getString(R.string.waiting_for_proxy_dialog))
3763 } catch (waitingForTorException: Exception) {
3764 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
3765 pendingDialogsArrayList.add(PendingDialogDataClass(waitingForProxyDialogFragment, getString(R.string.waiting_for_proxy_dialog)))
3769 } catch (exception: PackageManager.NameNotFoundException) { // Orbot is not installed.
3770 // Show the Orbot not installed dialog if it is not already displayed.
3771 if (supportFragmentManager.findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
3772 // Get a handle for the Orbot not installed alert dialog.
3773 val orbotNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode)
3775 // Try to show the dialog. Sometimes the window is not yet active if returning from Settings.
3777 // Display the Orbot not installed alert dialog.
3778 orbotNotInstalledDialogFragment.show(supportFragmentManager, getString(R.string.proxy_not_installed_dialog))
3779 } catch (orbotNotInstalledException: Exception) {
3780 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
3781 pendingDialogsArrayList.add(PendingDialogDataClass(orbotNotInstalledDialogFragment, getString(R.string.proxy_not_installed_dialog)))
3787 ProxyHelper.I2P -> {
3788 // Set the app bar background to indicate proxying is enabled.
3789 appBarLayout.setBackgroundResource(R.color.blue_background)
3791 // Check to see if I2P is installed.
3793 // 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.
3794 packageManager.getPackageInfo("net.i2p.android.router", 0)
3795 } catch (fdroidException: PackageManager.NameNotFoundException) { // The F-Droid flavor is not installed.
3797 // 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.
3798 packageManager.getPackageInfo("net.i2p.android", 0)
3799 } catch (googlePlayException: PackageManager.NameNotFoundException) { // The Google Play flavor is not installed.
3800 // Sow the I2P not installed dialog if it is not already displayed.
3801 if (supportFragmentManager.findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
3802 // Get a handle for the waiting for proxy alert dialog.
3803 val i2pNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode)
3805 // Try to show the dialog. Sometimes the window is not yet active if returning from Settings.
3807 // Display the I2P not installed alert dialog.
3808 i2pNotInstalledDialogFragment.show(supportFragmentManager, getString(R.string.proxy_not_installed_dialog))
3809 } catch (i2pNotInstalledException: Exception) {
3810 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
3811 pendingDialogsArrayList.add(PendingDialogDataClass(i2pNotInstalledDialogFragment, getString(R.string.proxy_not_installed_dialog)))
3818 ProxyHelper.CUSTOM ->
3819 // Set the app bar background to indicate proxying is enabled.
3820 appBarLayout.setBackgroundResource(R.color.blue_background)
3823 // Reload the WebViews if requested and not waiting for the proxy.
3824 if (reloadWebViews && !waitingForProxy) {
3825 // Reload the WebViews.
3826 for (i in 0 until webViewStateAdapter!!.itemCount) {
3827 // Get the WebView tab fragment.
3828 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
3830 // Get the fragment view.
3831 val fragmentView = webViewTabFragment.view
3833 // Only reload the WebViews if they exist.
3834 if (fragmentView != null) {
3835 // Get the nested scroll WebView from the tab fragment.
3836 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
3838 // Reload the WebView.
3839 nestedScrollWebView.reload()
3845 // The view parameter cannot be removed because it is called from the layout onClick.
3846 fun bookmarksBack(@Suppress("UNUSED_PARAMETER")view: View?) {
3847 if (currentBookmarksFolderId == HOME_FOLDER_ID) { // The home folder is displayed.
3848 // close the bookmarks drawer.
3849 drawerLayout.closeDrawer(GravityCompat.END)
3850 } else { // A subfolder is displayed.
3851 // Set the former parent folder as the current folder.
3852 currentBookmarksFolderId = bookmarksDatabaseHelper!!.getParentFolderId(currentBookmarksFolderId)
3854 // Load the new folder.
3855 loadBookmarksFolder()
3859 private fun calculateSettingsInt(settingCurrentlyEnabled: Boolean, settingEnabledByDefault: Boolean): Int {
3860 return if (settingCurrentlyEnabled == settingEnabledByDefault) // The current system default is used.
3862 else if (settingCurrentlyEnabled) // The setting is enabled, which is different from the system default.
3864 else // The setting is disabled, which is different from the system default.
3868 private fun clearAndExit() {
3869 // Close the bookmarks cursor if it exists.
3870 bookmarksCursor?.close()
3872 // Close the databases helpers if they exist.
3873 bookmarksDatabaseHelper?.close()
3874 domainsDatabaseHelper?.close()
3876 // Get the status of the clear everything preference.
3877 val clearEverything = sharedPreferences.getBoolean(getString(R.string.clear_everything_key), true)
3879 // Get a handle for the runtime.
3880 val runtime = Runtime.getRuntime()
3882 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
3883 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
3884 val privateDataDirectoryString = applicationInfo.dataDir
3887 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_cookies_key), true)) {
3888 // Ass the cookie manager to delete all the cookies.
3889 cookieManager.removeAllCookies(null)
3891 // Ask the cookie manager to flush the cookie database.
3892 cookieManager.flush()
3894 // Manually delete the cookies database, as the cookie manager sometimes will not flush its changes to disk before system exit is run.
3896 // Two commands must be used because `Runtime.exec()` does not like `*`.
3897 val deleteCookiesProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/Cookies")
3898 val deleteCookiesJournalProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/Cookies-journal")
3900 // Wait until the processes have finished.
3901 deleteCookiesProcess.waitFor()
3902 deleteCookiesJournalProcess.waitFor()
3903 } catch (exception: Exception) {
3904 // Do nothing if an error is thrown.
3908 // Clear DOM storage.
3909 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_dom_storage_key), true)) {
3910 // Ask web storage to clear the DOM storage.
3911 WebStorage.getInstance().deleteAllData()
3913 // Manually delete the DOM storage files and directories, as web storage sometimes will not flush its changes to disk before system exit is run.
3915 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
3916 val deleteLocalStorageProcess = runtime.exec(arrayOf("rm", "-rf", "$privateDataDirectoryString/app_webview/Local Storage/"))
3918 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
3919 val deleteIndexProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview/IndexedDB")
3920 val deleteQuotaManagerProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/QuotaManager")
3921 val deleteQuotaManagerJournalProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/QuotaManager-journal")
3922 val deleteDatabaseProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview/databases")
3924 // Wait until the processes have finished.
3925 deleteLocalStorageProcess.waitFor()
3926 deleteIndexProcess.waitFor()
3927 deleteQuotaManagerProcess.waitFor()
3928 deleteQuotaManagerJournalProcess.waitFor()
3929 deleteDatabaseProcess.waitFor()
3930 } catch (exception: Exception) {
3931 // Do nothing if an error is thrown.
3935 // Clear form data if the API < 26.
3936 if (Build.VERSION.SDK_INT < 26 && (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_form_data_key), true))) {
3937 // Ask the WebView database to clear the form data.
3938 @Suppress("DEPRECATION")
3939 WebViewDatabase.getInstance(this).clearFormData()
3941 // Manually delete the form data database, as the WebView database sometimes will not flush its changes to disk before system exit is run.
3943 // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
3944 val deleteWebDataProcess = runtime.exec(arrayOf("rm", "-f", "$privateDataDirectoryString/app_webview/Web Data"))
3945 val deleteWebDataJournalProcess = runtime.exec(arrayOf("rm", "-f", "$privateDataDirectoryString/app_webview/Web Data-journal"))
3947 // Wait until the processes have finished.
3948 deleteWebDataProcess.waitFor()
3949 deleteWebDataJournalProcess.waitFor()
3950 } catch (exception: Exception) {
3951 // Do nothing if an error is thrown.
3955 // Clear the logcat.
3956 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_logcat_key), true)) {
3958 // Clear the logcat. `-c` clears the logcat. `-b all` clears all the buffers (instead of just crash, main, and system).
3959 val process = Runtime.getRuntime().exec("logcat -b all -c")
3961 // Wait for the process to finish.
3963 } catch (exception: IOException) {
3965 } catch (exception: InterruptedException) {
3971 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_cache_key), true)) {
3972 // Clear the cache from each WebView.
3973 for (i in 0 until webViewStateAdapter!!.itemCount) {
3974 // Get the WebView tab fragment.
3975 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
3977 // Get the WebView fragment view.
3978 val webViewFragmentView = webViewTabFragment.view
3980 // Only clear the cache if the WebView exists.
3981 if (webViewFragmentView != null) {
3982 // Get the nested scroll WebView from the tab fragment.
3983 val nestedScrollWebView = webViewFragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
3985 // Clear the cache for this WebView.
3986 nestedScrollWebView.clearCache(true)
3990 // Manually delete the cache directories.
3992 // Delete the main cache directory.
3993 val deleteCacheProcess = runtime.exec("rm -rf $privateDataDirectoryString/cache")
3995 // Delete the secondary `Service Worker` cache directory.
3996 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
3997 val deleteServiceWorkerProcess = runtime.exec(arrayOf("rm", "-rf", "$privateDataDirectoryString/app_webview/Default/Service Worker/"))
3999 // Wait until the processes have finished.
4000 deleteCacheProcess.waitFor()
4001 deleteServiceWorkerProcess.waitFor()
4002 } catch (exception: Exception) {
4003 // Do nothing if an error is thrown.
4007 // Wipe out each WebView.
4008 for (i in 0 until webViewStateAdapter!!.itemCount) {
4009 // Get the WebView tab fragment.
4010 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
4012 // Get the WebView frame layout.
4013 val webViewFrameLayout = webViewTabFragment.view as FrameLayout?
4015 // Only wipe out the WebView if it exists.
4016 if (webViewFrameLayout != null) {
4017 // Get the nested scroll WebView from the tab fragment.
4018 val nestedScrollWebView = webViewFrameLayout.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
4020 // Clear SSL certificate preferences for this WebView.
4021 nestedScrollWebView.clearSslPreferences()
4023 // Clear the back/forward history for this WebView.
4024 nestedScrollWebView.clearHistory()
4026 // Remove all the views from the frame layout.
4027 webViewFrameLayout.removeAllViews()
4029 // Destroy the internal state of the WebView.
4030 nestedScrollWebView.destroy()
4034 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
4035 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
4036 if (clearEverything) {
4038 // Delete the folder.
4039 val deleteAppWebviewProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview")
4041 // Wait until the process has finished.
4042 deleteAppWebviewProcess.waitFor()
4043 } catch (exception: Exception) {
4044 // Do nothing if an error is thrown.
4048 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
4049 finishAndRemoveTask()
4051 // Remove the terminated program from RAM. The status code is `0`.
4055 // The view parameter cannot be removed because it is called from the layout onClick.
4056 fun closeFindOnPage(@Suppress("UNUSED_PARAMETER")view: View?) {
4057 // Delete the contents of the find on page edit text.
4058 findOnPageEditText.text = null
4060 // Clear the highlighted phrases if the WebView is not null.
4061 currentWebView?.clearMatches()
4063 // Hide the find on page linear layout.
4064 findOnPageLinearLayout.visibility = View.GONE
4066 // Show the toolbar.
4067 toolbar.visibility = View.VISIBLE
4069 // Get a handle for the input method manager.
4070 val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
4072 // Hide the keyboard.
4073 inputMethodManager.hideSoftInputFromWindow(toolbar.windowToken, 0)
4076 // The view parameter cannot be removed because it is called from the layout onClick.
4077 fun closeTab(@Suppress("UNUSED_PARAMETER")view: View?) {
4078 // Run the command according to the number of tabs.
4079 if (tabLayout.tabCount > 1) { // There is more than one tab open.
4080 // Get the current tab number.
4081 val currentTabNumber = tabLayout.selectedTabPosition
4083 // Delete the current tab.
4084 tabLayout.removeTabAt(currentTabNumber)
4086 // 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,
4087 // meaning that the current WebView must be reset. Otherwise it will happen automatically as the selected tab number changes.
4088 if (webViewStateAdapter!!.deletePage(currentTabNumber, webViewViewPager2))
4089 setCurrentWebView(currentTabNumber)
4090 } else { // There is only one tab open.
4095 override fun createBookmark(dialogFragment: DialogFragment, favoriteIconBitmap: Bitmap) {
4097 val dialog = dialogFragment.dialog!!
4099 // Get the views from the dialog fragment.
4100 val createBookmarkNameEditText = dialog.findViewById<EditText>(R.id.create_bookmark_name_edittext)
4101 val createBookmarkUrlEditText = dialog.findViewById<EditText>(R.id.create_bookmark_url_edittext)
4103 // Extract the strings from the edit texts.
4104 val bookmarkNameString = createBookmarkNameEditText.text.toString()
4105 val bookmarkUrlString = createBookmarkUrlEditText.text.toString()
4107 // Create a favorite icon byte array output stream.
4108 val favoriteIconByteArrayOutputStream = ByteArrayOutputStream()
4110 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
4111 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream)
4113 // Convert the favorite icon byte array stream to a byte array.
4114 val favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray()
4116 // Display the new bookmark below the current items in the (0 indexed) list.
4117 val newBookmarkDisplayOrder = bookmarksListView.count
4119 // Create the bookmark.
4120 bookmarksDatabaseHelper!!.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolderId, newBookmarkDisplayOrder, favoriteIconByteArray)
4122 // Update the bookmarks cursor with the current contents of this folder.
4123 bookmarksCursor = bookmarksDatabaseHelper!!.getBookmarksByDisplayOrder(currentBookmarksFolderId)
4125 // Update the list view.
4126 bookmarksCursorAdapter.changeCursor(bookmarksCursor)
4128 // Scroll to the new bookmark.
4129 bookmarksListView.setSelection(newBookmarkDisplayOrder)
4132 override fun createBookmarkFolder(dialogFragment: DialogFragment, favoriteIconBitmap: Bitmap) {
4134 val dialog = dialogFragment.dialog!!
4136 // Get handles for the views in the dialog fragment.
4137 val folderNameEditText = dialog.findViewById<EditText>(R.id.folder_name_edittext)
4138 val defaultIconRadioButton = dialog.findViewById<RadioButton>(R.id.default_icon_radiobutton)
4139 val defaultIconImageView = dialog.findViewById<ImageView>(R.id.default_icon_imageview)
4141 // Get new folder name string.
4142 val folderNameString = folderNameEditText.text.toString()
4144 // Set the folder icon bitmap according to the dialog.
4145 val folderIconBitmap: Bitmap = if (defaultIconRadioButton.isChecked) { // Use the default folder icon.
4146 // Get the default folder icon drawable.
4147 val folderIconDrawable = defaultIconImageView.drawable
4149 // Convert the folder icon drawable to a bitmap drawable.
4150 val folderIconBitmapDrawable = folderIconDrawable as BitmapDrawable
4152 // Convert the folder icon bitmap drawable to a bitmap.
4153 folderIconBitmapDrawable.bitmap
4154 } else { // Use the WebView favorite icon.
4155 // Copy the favorite icon bitmap to the folder icon bitmap.
4159 // Create a folder icon byte array output stream.
4160 val folderIconByteArrayOutputStream = ByteArrayOutputStream()
4162 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
4163 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream)
4165 // Convert the folder icon byte array stream to a byte array.
4166 val folderIconByteArray = folderIconByteArrayOutputStream.toByteArray()
4168 // Move all the bookmarks down one in the display order.
4169 for (i in 0 until bookmarksListView.count) {
4170 // Get the bookmark database id.
4171 val databaseId = bookmarksListView.getItemIdAtPosition(i).toInt()
4173 // Move the bookmark down one slot.
4174 bookmarksDatabaseHelper!!.updateDisplayOrder(databaseId, displayOrder = i + 1)
4177 // Create the folder, which will be placed at the top of the list view.
4178 bookmarksDatabaseHelper!!.createFolder(folderNameString, currentBookmarksFolderId, displayOrder = 0, folderIconByteArray)
4180 // Update the bookmarks cursor with the current contents of this folder.
4181 bookmarksCursor = bookmarksDatabaseHelper!!.getBookmarksByDisplayOrder(currentBookmarksFolderId)
4183 // Update the list view.
4184 bookmarksCursorAdapter.changeCursor(bookmarksCursor)
4186 // Scroll to the new folder.
4187 bookmarksListView.setSelection(0)
4190 private fun downloadUrlWithExternalApp(url: String) {
4191 // Create a download intent. Not specifying the action type will display the maximum number of options.
4192 val downloadIntent = Intent()
4194 // Set the URI and the mime type.
4195 downloadIntent.setDataAndType(Uri.parse(url), "text/html")
4197 // Flag the intent to open in a new task.
4198 downloadIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
4200 // Show the chooser.
4201 startActivity(Intent.createChooser(downloadIntent, getString(R.string.download_with_external_app)))
4204 private fun exitFullScreenVideo() {
4205 // Re-enable the screen timeout.
4206 fullScreenVideoFrameLayout.keepScreenOn = false
4208 // Unset the full screen video flag.
4209 displayingFullScreenVideo = false
4211 // Remove all the views from the full screen video frame layout.
4212 fullScreenVideoFrameLayout.removeAllViews()
4214 // Hide the full screen video frame layout.
4215 fullScreenVideoFrameLayout.visibility = View.GONE
4217 // Enable the sliding drawers.
4218 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED)
4220 // Show the coordinator layout.
4221 coordinatorLayout.visibility = View.VISIBLE
4223 // Apply the appropriate full screen mode flags.
4224 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
4225 // Hide the app bar if specified.
4227 // Hide the tab linear layout.
4228 tabsLinearLayout.visibility = View.GONE
4230 // Hide the app bar.
4234 /* Hide the system bars.
4235 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4236 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4237 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4238 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4241 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4242 @Suppress("DEPRECATION")
4243 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
4244 } else { // Switch to normal viewing mode.
4245 // Remove the `SYSTEM_UI` flags from the root frame layout. The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4246 @Suppress("DEPRECATION")
4247 rootFrameLayout.systemUiVisibility = 0
4251 // The view parameter cannot be removed because it is called from the layout onClick.
4252 fun findNextOnPage(@Suppress("UNUSED_PARAMETER")view: View?) {
4253 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
4254 currentWebView!!.findNext(true)
4257 // The view parameter cannot be removed because it is called from the layout onClick.
4258 fun findPreviousOnPage(@Suppress("UNUSED_PARAMETER")view: View?) {
4259 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
4260 currentWebView!!.findNext(false)
4263 override fun finishedPopulatingFilterLists(combinedFilterLists: ArrayList<ArrayList<List<Array<String>>>>) {
4264 // Store the filter lists.
4265 easyList = combinedFilterLists[0]
4266 easyPrivacy = combinedFilterLists[1]
4267 fanboysAnnoyanceList = combinedFilterLists[2]
4268 fanboysSocialList = combinedFilterLists[3]
4269 ultraList = combinedFilterLists[4]
4270 ultraPrivacy = combinedFilterLists[5]
4272 // Check to see if the activity has been restarted with a saved state.
4273 if ((savedStateArrayList == null) || (savedStateArrayList!!.size == 0)) { // The activity has not been restarted or it was restarted on start to change the theme.
4274 // Add the first tab.
4275 addNewPage(urlString = "", adjacent = false, moveToTab = false)
4276 } else { // The activity has been restarted with a saved state.
4277 // Restore each tab.
4278 for (i in savedStateArrayList!!.indices) {
4280 tabLayout.addTab(tabLayout.newTab())
4283 val newTab = tabLayout.getTabAt(i)!!
4285 // Set a custom view on the new tab.
4286 newTab.setCustomView(R.layout.tab_custom_view)
4288 // Add the new page.
4289 webViewStateAdapter!!.restorePage(savedStateArrayList!![i], savedNestedScrollWebViewStateArrayList!![i])
4292 // Reset the saved state variables.
4293 savedStateArrayList = null
4294 savedNestedScrollWebViewStateArrayList = null
4296 // Get the intent that started the app.
4299 // Reset the intent. This prevents a duplicate tab from being created on restart.
4302 // Get the information from the intent.
4303 val intentAction = intent.action
4304 val intentUriData = intent.data
4305 val intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT)
4307 // Determine if this is a web search.
4308 val isWebSearch = (intentAction != null) && (intentAction == Intent.ACTION_WEB_SEARCH)
4310 // 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.
4311 if ((intentUriData != null) || (intentStringExtra != null) || isWebSearch) { // A new tab is being loaded.
4312 // Get the URL string.
4313 val urlString = if (isWebSearch) { // The intent is a web search.
4314 // Sanitize the search input.
4315 val encodedSearchString: String = try {
4316 URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8")
4317 } catch (exception: UnsupportedEncodingException) {
4321 // Add the base search URL.
4322 searchURL + encodedSearchString
4323 } else { // The intent contains a URL formatted as a URI or a URL in the string extra.
4324 // Get the URL string.
4325 intentUriData?.toString() ?: intentStringExtra!!
4328 // Add a new tab if specified in the preferences.
4329 if (sharedPreferences.getBoolean(getString(R.string.open_intents_in_new_tab_key), true)) { // Load the URL in a new tab.
4330 // Set the loading new intent flag.
4331 loadingNewIntent = true
4334 addNewPage(urlString, adjacent = false, moveToTab = true)
4335 } else { // Load the URL in the current tab.
4337 loadUrl(currentWebView!!, urlString)
4339 } else { // A new tab is not being loaded.
4340 // Restore the selected tab position.
4341 if (savedTabPosition == 0) { // The first tab is selected.
4342 // Set the first page as the current WebView.
4343 setCurrentWebView(0)
4344 } else { // The first tab is not selected.
4345 // Select the tab when the layout has finished populating.
4347 // Get a handle for the tab.
4348 val tab = tabLayout.getTabAt(savedTabPosition)!!
4358 // Remove the warning that `OnTouchListener()` needs to override `performClick()`, as the only purpose of setting the `OnTouchListener()` is to make it do nothing.
4359 @SuppressLint("ClickableViewAccessibility")
4360 private fun initializeApp() {
4361 // Get a handle for the input method.
4362 val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
4364 // Initialize the color spans for highlighting the URLs.
4365 initialGrayColorSpan = ForegroundColorSpan(getColor(R.color.gray_500))
4366 finalGrayColorSpan = ForegroundColorSpan(getColor(R.color.gray_500))
4367 redColorSpan = ForegroundColorSpan(getColor(R.color.red_text))
4369 // Remove the formatting from the URL edit text when the user is editing the text.
4370 urlEditText.onFocusChangeListener = View.OnFocusChangeListener { _: View?, hasFocus: Boolean ->
4371 if (hasFocus) { // The user is editing the URL text box.
4372 // Remove the syntax highlighting.
4373 urlEditText.text.removeSpan(redColorSpan)
4374 urlEditText.text.removeSpan(initialGrayColorSpan)
4375 urlEditText.text.removeSpan(finalGrayColorSpan)
4376 } else { // The user has stopped editing the URL text box.
4377 // Move to the beginning of the string.
4378 urlEditText.setSelection(0)
4380 // Reapply the syntax highlighting.
4381 UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
4385 // Set the go button on the keyboard to load the URL in url text box.
4386 urlEditText.setOnKeyListener { _: View?, keyCode: Int, keyEvent: KeyEvent ->
4387 // If the event is a key-down event on the `enter` button, load the URL.
4388 if ((keyEvent.action == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The enter key was pressed.
4390 loadUrlFromTextBox()
4392 // Consume the event.
4393 return@setOnKeyListener true
4394 } else { // Some other key was pressed.
4395 // Do not consume the event.
4396 return@setOnKeyListener false
4400 // Create an Orbot status broadcast receiver.
4401 orbotStatusBroadcastReceiver = object : BroadcastReceiver() {
4402 override fun onReceive(context: Context, intent: Intent) {
4403 // Get the content of the status message.
4404 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS")!!
4406 // If Privacy Browser is waiting on the proxy, load the website now that Orbot is connected.
4407 if ((orbotStatus == ProxyHelper.ORBOT_STATUS_ON) && waitingForProxy) {
4408 // Reset the waiting for proxy status.
4409 waitingForProxy = false
4411 // Get a list of the current fragments.
4412 val fragmentList = supportFragmentManager.fragments
4414 // Check each fragment to see if it is a waiting for proxy dialog. Sometimes more than one is displayed.
4415 for (i in fragmentList.indices) {
4416 // Get the fragment tag.
4417 val fragmentTag = fragmentList[i].tag
4419 // Check to see if it is the waiting for proxy dialog.
4420 if (fragmentTag != null && fragmentTag == getString(R.string.waiting_for_proxy_dialog)) {
4421 // Dismiss the waiting for proxy dialog.
4422 (fragmentList[i] as DialogFragment).dismiss()
4426 // Reload existing URLs and load any URLs that are waiting for the proxy.
4427 for (i in 0 until webViewStateAdapter!!.itemCount) {
4428 // Get the WebView tab fragment.
4429 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
4431 // Get the fragment view.
4432 val fragmentView = webViewTabFragment.view
4434 // Only process the WebViews if they exist.
4435 if (fragmentView != null) {
4436 // Get the nested scroll WebView from the tab fragment.
4437 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
4439 // Get the waiting for proxy URL string.
4440 val waitingForProxyUrlString = nestedScrollWebView.waitingForProxyUrlString
4442 // Load the pending URL if it exists.
4443 if (waitingForProxyUrlString.isNotEmpty()) { // A URL is waiting to be loaded.
4445 loadUrl(nestedScrollWebView, waitingForProxyUrlString)
4447 // Reset the waiting for proxy URL string.
4448 nestedScrollWebView.waitingForProxyUrlString = ""
4449 } else { // No URL is waiting to be loaded.
4450 // Reload the existing URL.
4451 nestedScrollWebView.reload()
4459 // Register the Orbot status broadcast receiver. `ContextCompat` must be used until the minimum API >= 34.
4460 ContextCompat.registerReceiver(this, orbotStatusBroadcastReceiver, IntentFilter("org.torproject.android.intent.action.STATUS"), ContextCompat.RECEIVER_EXPORTED)
4462 // Get handles for views that need to be modified.
4463 val bookmarksHeaderLinearLayout = findViewById<LinearLayout>(R.id.bookmarks_header_linearlayout)
4464 val launchBookmarksActivityFab = findViewById<FloatingActionButton>(R.id.launch_bookmarks_activity_fab)
4465 val createBookmarkFolderFab = findViewById<FloatingActionButton>(R.id.create_bookmark_folder_fab)
4466 val createBookmarkFab = findViewById<FloatingActionButton>(R.id.create_bookmark_fab)
4468 // Handle tab selections.
4469 tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
4470 override fun onTabSelected(tab: TabLayout.Tab) {
4471 // Close the find on page bar if it is open.
4472 closeFindOnPage(null)
4474 // 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.
4475 webViewViewPager2.post {
4476 // Select the same page in the view pager.
4477 webViewViewPager2.currentItem = tab.position
4479 // 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>
4481 setCurrentWebView(tab.position)
4486 override fun onTabUnselected(tab: TabLayout.Tab) {}
4488 override fun onTabReselected(tab: TabLayout.Tab) {
4489 // Only display the view SSL certificate dialog if the current WebView is not null.
4490 // This can happen if the tab is programmatically reselected while the app is being restarted and is not yet populated.
4491 if (currentWebView != null) {
4492 // Instantiate the View SSL Certificate dialog.
4493 val viewSslCertificateDialogFragment: DialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView!!.webViewFragmentId, currentWebView!!.getFavoriteIcon())
4495 // Display the View SSL Certificate dialog.
4496 viewSslCertificateDialogFragment.show(supportFragmentManager, getString(R.string.view_ssl_certificate))
4501 // Set a touch listener on the bookmarks header linear layout so that touches don't pass through to the button underneath.
4502 bookmarksHeaderLinearLayout.setOnTouchListener { _: View?, _: MotionEvent? -> true }
4504 // Set the launch bookmarks activity floating action button to launch the bookmarks activity.
4505 launchBookmarksActivityFab.setOnClickListener {
4506 // Get a copy of the favorite icon bitmap.
4507 val currentFavoriteIconBitmap = currentWebView!!.getFavoriteIcon()
4509 // Create a favorite icon byte array output stream.
4510 val currentFavoriteIconByteArrayOutputStream = ByteArrayOutputStream()
4512 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
4513 currentFavoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, currentFavoriteIconByteArrayOutputStream)
4515 // Convert the favorite icon byte array stream to a byte array.
4516 val currentFavoriteIconByteArray = currentFavoriteIconByteArrayOutputStream.toByteArray()
4518 // Create an intent to launch the bookmarks activity.
4519 val bookmarksIntent = Intent(applicationContext, BookmarksActivity::class.java)
4521 // Add the extra information to the intent.
4522 bookmarksIntent.putExtra(CURRENT_FOLDER_ID, currentBookmarksFolderId)
4523 bookmarksIntent.putExtra(CURRENT_TITLE, currentWebView!!.title)
4524 bookmarksIntent.putExtra(CURRENT_URL, currentWebView!!.url)
4525 bookmarksIntent.putExtra(CURRENT_FAVORITE_ICON_BYTE_ARRAY, currentFavoriteIconByteArray)
4528 startActivity(bookmarksIntent)
4531 // Set the create new bookmark folder floating action button to display an alert dialog.
4532 createBookmarkFolderFab.setOnClickListener {
4533 // Create a create bookmark folder dialog.
4534 val createBookmarkFolderDialog: DialogFragment = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView!!.getFavoriteIcon())
4536 // Show the create bookmark folder dialog.
4537 createBookmarkFolderDialog.show(supportFragmentManager, getString(R.string.create_folder))
4540 // Set the create new bookmark floating action button to display an alert dialog.
4541 createBookmarkFab.setOnClickListener {
4542 // Instantiate the create bookmark dialog.
4543 val createBookmarkDialog: DialogFragment = CreateBookmarkDialog.createBookmark(currentWebView!!.url!!, currentWebView!!.title!!, currentWebView!!.getFavoriteIcon())
4545 // Display the create bookmark dialog.
4546 createBookmarkDialog.show(supportFragmentManager, getString(R.string.create_bookmark))
4549 // Search for the string on the page whenever a character changes in the find on page edit text.
4550 findOnPageEditText.addTextChangedListener(object : TextWatcher {
4551 override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
4553 override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
4555 override fun afterTextChanged(s: Editable) {
4556 // 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.
4557 currentWebView?.findAllAsync(findOnPageEditText.text.toString())
4561 // Set the `check mark` button for the find on page edit text keyboard to close the soft keyboard.
4562 findOnPageEditText.setOnKeyListener { _: View?, keyCode: Int, keyEvent: KeyEvent ->
4563 if ((keyEvent.action == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
4564 // Hide the soft keyboard.
4565 inputMethodManager.hideSoftInputFromWindow(currentWebView!!.windowToken, 0)
4567 // Consume the event.
4568 return@setOnKeyListener true
4569 } else { // A different key was pressed.
4570 // Do not consume the event.
4571 return@setOnKeyListener false
4575 // Implement swipe to refresh.
4576 swipeRefreshLayout.setOnRefreshListener {
4577 // Reload the website.
4578 currentWebView!!.reload()
4581 // Store the default progress view offsets.
4582 defaultProgressViewStartOffset = swipeRefreshLayout.progressViewStartOffset
4583 defaultProgressViewEndOffset = swipeRefreshLayout.progressViewEndOffset
4585 // Set the refresh color scheme according to the theme.
4586 swipeRefreshLayout.setColorSchemeResources(R.color.blue_text)
4588 // Initialize a color background typed value.
4589 val colorBackgroundTypedValue = TypedValue()
4591 // Get the color background from the theme.
4592 theme.resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true)
4594 // Get the color background int from the typed value.
4595 val colorBackgroundInt = colorBackgroundTypedValue.data
4597 // Set the swipe refresh background color.
4598 swipeRefreshLayout.setProgressBackgroundColorSchemeColor(colorBackgroundInt)
4600 // Set the drawer titles, which identify the drawer layouts in accessibility mode.
4601 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer))
4602 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks))
4604 // Load the bookmarks folder.
4605 loadBookmarksFolder()
4607 // Handle clicks on bookmarks.
4608 bookmarksListView.onItemClickListener = AdapterView.OnItemClickListener { _: AdapterView<*>?, _: View?, _: Int, id: Long ->
4609 // Convert the id from long to int to match the format of the bookmarks database.
4610 val databaseId = id.toInt()
4612 // Get the bookmark cursor for this ID.
4613 val bookmarkCursor = bookmarksDatabaseHelper!!.getBookmark(databaseId)
4615 // Move the bookmark cursor to the first row.
4616 bookmarkCursor.moveToFirst()
4618 // Act upon the bookmark according to the type.
4619 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndexOrThrow(IS_FOLDER)) == 1) { // The selected bookmark is a folder.
4620 // Store the folder ID.
4621 currentBookmarksFolderId = bookmarkCursor.getLong(bookmarkCursor.getColumnIndexOrThrow(FOLDER_ID))
4623 // Load the new folder.
4624 loadBookmarksFolder()
4625 } else { // The selected bookmark is not a folder.
4626 // Load the bookmark URL.
4627 loadUrl(currentWebView!!, bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BOOKMARK_URL)))
4629 // Close the bookmarks drawer if it is not pinned.
4630 if (!bookmarksDrawerPinned)
4631 drawerLayout.closeDrawer(GravityCompat.END)
4634 // Close the cursor.
4635 bookmarkCursor.close()
4638 // Handle long-presses on bookmarks.
4639 bookmarksListView.onItemLongClickListener = AdapterView.OnItemLongClickListener { _: AdapterView<*>?, _: View?, _: Int, id: Long ->
4640 // Convert the database ID from `long` to `int`.
4641 val databaseId = id.toInt()
4643 // Run the commands associated with the type.
4644 if (bookmarksDatabaseHelper!!.isFolder(databaseId)) { // The bookmark is a folder.
4645 // Get the folder ID.
4646 val folderId = bookmarksDatabaseHelper!!.getFolderId(databaseId)
4648 // Get a cursor of all the bookmarks in the folder.
4649 val bookmarksCursor = bookmarksDatabaseHelper!!.getFolderBookmarks(folderId)
4651 // Move to the first entry in the cursor.
4652 bookmarksCursor.moveToFirst()
4654 // Open each bookmark
4655 for (i in 0 until bookmarksCursor.count) {
4656 // Load the bookmark in a new tab, moving to the tab for the first bookmark if the drawer is not pinned.
4657 addNewPage(bookmarksCursor.getString(bookmarksCursor.getColumnIndexOrThrow(BOOKMARK_URL)), adjacent = false, moveToTab = !bookmarksDrawerPinned && (i == 0))
4659 // Move to the next bookmark.
4660 bookmarksCursor.moveToNext()
4663 // Close the cursor.
4664 bookmarksCursor.close()
4665 } else { // The bookmark is not a folder.
4666 // Get the bookmark cursor for this ID.
4667 val bookmarkCursor = bookmarksDatabaseHelper!!.getBookmark(databaseId)
4669 // Move the bookmark cursor to the first row.
4670 bookmarkCursor.moveToFirst()
4672 // Load the bookmark in a new tab and move to the tab if the drawer is not pinned.
4673 addNewPage(bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BOOKMARK_URL)), adjacent = true, moveToTab = !bookmarksDrawerPinned)
4675 // Close the cursor.
4676 bookmarkCursor.close()
4679 // Close the bookmarks drawer if it is not pinned.
4680 if (!bookmarksDrawerPinned)
4681 drawerLayout.closeDrawer(GravityCompat.END)
4683 // Consume the event.
4687 // The drawer listener is used to update the navigation menu.
4688 drawerLayout.addDrawerListener(object : DrawerLayout.DrawerListener {
4689 override fun onDrawerSlide(drawerView: View, slideOffset: Float) {}
4691 override fun onDrawerOpened(drawerView: View) {}
4693 override fun onDrawerClosed(drawerView: View) {
4694 // Reset the drawer icon when the drawer is closed. Otherwise, it remains an arrow if the drawer is open when the app is restarted.
4695 actionBarDrawerToggle!!.syncState()
4698 override fun onDrawerStateChanged(newState: Int) {
4699 if (newState == DrawerLayout.STATE_SETTLING || newState == DrawerLayout.STATE_DRAGGING) { // A drawer is opening or closing.
4700 // Update the navigation menu items if the WebView is not null.
4701 if (currentWebView != null) {
4702 // Set the enabled status of the menu items.
4703 navigationBackMenuItem.isEnabled = currentWebView!!.canGoBack()
4704 navigationForwardMenuItem.isEnabled = currentWebView!!.canGoForward()
4705 navigationScrollToBottomMenuItem.isEnabled = (currentWebView!!.canScrollVertically(-1) || currentWebView!!.canScrollVertically(1))
4706 navigationHistoryMenuItem.isEnabled = currentWebView!!.canGoBack() || currentWebView!!.canGoForward()
4708 // Update the scroll menu item.
4709 if (currentWebView!!.scrollY == 0) { // The WebView is scrolled to the top.
4711 navigationScrollToBottomMenuItem.title = getString(R.string.scroll_to_bottom)
4714 navigationScrollToBottomMenuItem.icon = AppCompatResources.getDrawable(applicationContext, R.drawable.move_down_enabled)
4715 } else { // The WebView is not scrolled to the top.
4717 navigationScrollToBottomMenuItem.title = getString(R.string.scroll_to_top)
4720 navigationScrollToBottomMenuItem.icon = AppCompatResources.getDrawable(applicationContext, R.drawable.move_up_enabled)
4723 // Display the number of blocked requests.
4724 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + currentWebView!!.getRequestsCount(BLOCKED_REQUESTS)
4726 // Hide the keyboard (if displayed).
4727 inputMethodManager.hideSoftInputFromWindow(currentWebView!!.windowToken, 0)
4730 // 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.
4731 urlEditText.clearFocus()
4733 // 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.
4734 // Clearing the focus from the WebView removes any text selection markers and context menus, which otherwise draw above the open drawers.
4735 currentWebView?.clearFocus()
4737 if (bottomAppBar && navigationDrawerFirstView) {
4738 // Reset the navigation drawer first view flag.
4739 navigationDrawerFirstView = false
4741 // Get a handle for the navigation recycler view.
4742 val navigationRecyclerView = navigationView.getChildAt(0) as RecyclerView
4744 // Get the navigation linear layout manager.
4745 val navigationLinearLayoutManager = navigationRecyclerView.layoutManager as LinearLayoutManager
4747 // Scroll the navigation drawer to the bottom.
4748 navigationLinearLayoutManager.scrollToPositionWithOffset(13, 0)
4754 // Inflate a bare WebView to get the default user agent. It is not used to render content on the screen.
4755 @SuppressLint("InflateParams") val webViewLayout = layoutInflater.inflate(R.layout.bare_webview, null, false)
4757 // Get a handle for the WebView.
4758 val bareWebView = webViewLayout.findViewById<WebView>(R.id.bare_webview)
4760 // Store the default user agent.
4761 webViewDefaultUserAgent = bareWebView.settings.userAgentString
4763 // Destroy the bare WebView.
4764 bareWebView.destroy()
4766 // Update the domains settings set.
4767 updateDomainsSettingsSet()
4769 // Instantiate the check filter list helper.
4770 checkFilterListHelper = CheckFilterListHelper()
4773 @SuppressLint("ClickableViewAccessibility")
4774 override fun initializeWebView(nestedScrollWebView: NestedScrollWebView, pagePosition: Int, progressBar: ProgressBar, urlString: String, restoringState: Boolean) {
4775 // Get the WebView theme.
4776 val webViewTheme = sharedPreferences.getString(getString(R.string.webview_theme_key), getString(R.string.webview_theme_default_value))
4778 // Get the WebView theme entry values string array.
4779 val webViewThemeEntryValuesStringArray = resources.getStringArray(R.array.webview_theme_entry_values)
4781 // Set the WebView theme if algorithmic darkening is supported.
4782 if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {
4783 // Set the WebView them. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
4784 if (webViewTheme == webViewThemeEntryValuesStringArray[1]) { // The light theme is selected.
4785 // Turn off algorithmic darkening.
4786 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
4788 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
4789 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
4790 nestedScrollWebView.visibility = View.VISIBLE
4791 } else if (webViewTheme == webViewThemeEntryValuesStringArray[2]) { // The dark theme is selected.
4792 // Turn on algorithmic darkening.
4793 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
4794 } else { // The system default theme is selected.
4795 // Get the current theme status.
4796 val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
4798 // Set the algorithmic darkening according to the current system theme status.
4799 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) { // The system is in day mode.
4800 // Turn off algorithmic darkening.
4801 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
4803 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
4804 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
4805 nestedScrollWebView.visibility = View.VISIBLE
4806 } else { // The system is in night mode.
4807 // Turn on algorithmic darkening.
4808 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
4813 // Get a handle for the input method manager.
4814 val inputMethodManager = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
4816 // Set the app bar scrolling.
4817 nestedScrollWebView.isNestedScrollingEnabled = scrollAppBar
4819 // Allow pinch to zoom.
4820 nestedScrollWebView.settings.builtInZoomControls = true
4822 // Hide zoom controls.
4823 nestedScrollWebView.settings.displayZoomControls = false
4825 // Don't allow mixed content (HTTP and HTTPS) on the same website.
4826 nestedScrollWebView.settings.mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW
4828 // Set the WebView to load in overview mode (zoomed out to the maximum width).
4829 nestedScrollWebView.settings.loadWithOverviewMode = true
4831 // Explicitly disable geolocation.
4832 nestedScrollWebView.settings.setGeolocationEnabled(false)
4834 // Allow loading of file:// URLs. This is necessary for opening MHT web archives, which are copied into a temporary cache location.
4835 nestedScrollWebView.settings.allowFileAccess = true
4837 // Create a double-tap gesture detector to toggle full-screen mode.
4838 val doubleTapGestureDetector = GestureDetector(this, object : GestureDetector.SimpleOnGestureListener() {
4839 // Override `onDoubleTap()`. All other events are handled using the default settings.
4840 override fun onDoubleTap(motionEvent: MotionEvent): Boolean {
4841 return if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
4842 // Toggle the full screen browsing mode tracker.
4843 inFullScreenBrowsingMode = !inFullScreenBrowsingMode
4845 // Toggle the full screen browsing mode.
4846 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
4847 // Hide the app bar if specified.
4848 if (hideAppBar) { // App bar hiding is enabled.
4849 // Close the find on page bar if it is visible.
4850 closeFindOnPage(null)
4852 // Hide the tab linear layout.
4853 tabsLinearLayout.visibility = View.GONE
4855 // Hide the app bar.
4858 // Set layout and scrolling parameters according to the position of the app bar.
4859 if (bottomAppBar) { // The app bar is at the bottom.
4860 // Reset the WebView padding to fill the available space.
4861 swipeRefreshLayout.setPadding(0, 0, 0, 0)
4862 } else { // The app bar is at the top.
4863 // Check to see if the app bar is normally scrolled.
4864 if (scrollAppBar) { // The app bar is scrolled when it is displayed.
4865 // Get the swipe refresh layout parameters.
4866 val swipeRefreshLayoutParams = swipeRefreshLayout.layoutParams as CoordinatorLayout.LayoutParams
4868 // Remove the off-screen scrolling layout.
4869 swipeRefreshLayoutParams.behavior = null
4870 } else { // The app bar is not scrolled when it is displayed.
4871 // Remove the padding from the top of the swipe refresh layout.
4872 swipeRefreshLayout.setPadding(0, 0, 0, 0)
4874 // The swipe refresh circle must be moved above the now removed status bar location.
4875 swipeRefreshLayout.setProgressViewOffset(false, -200, defaultProgressViewEndOffset)
4878 } else { // App bar hiding is not enabled.
4879 // Adjust the UI for the bottom app bar.
4881 // Adjust the UI according to the scrolling of the app bar.
4883 // Reset the WebView padding to fill the available space.
4884 swipeRefreshLayout.setPadding(0, 0, 0, 0)
4886 // Move the WebView above the app bar layout.
4887 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
4892 /* Hide the system bars.
4893 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4894 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4895 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4896 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4899 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4900 @Suppress("DEPRECATION")
4901 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
4902 } else { // Switch to normal viewing mode.
4903 // Show the app bar if it was hidden.
4905 // Show the tab linear layout.
4906 tabsLinearLayout.visibility = View.VISIBLE
4908 // Show the app bar.
4912 // Set layout and scrolling parameters according to the position of the app bar.
4913 if (bottomAppBar) { // The app bar is at the bottom.
4916 // Reset the WebView padding to fill the available space.
4917 swipeRefreshLayout.setPadding(0, 0, 0, 0)
4919 // Move the WebView above the app bar layout.
4920 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
4922 } else { // The app bar is at the top.
4923 // Check to see if the app bar is normally scrolled.
4924 if (scrollAppBar) { // The app bar is scrolled when it is displayed.
4925 // Get the swipe refresh layout parameters.
4926 val swipeRefreshLayoutParams = swipeRefreshLayout.layoutParams as CoordinatorLayout.LayoutParams
4928 // Add the off-screen scrolling layout.
4929 swipeRefreshLayoutParams.behavior = AppBarLayout.ScrollingViewBehavior()
4930 } else { // The app bar is not scrolled when it is displayed.
4931 // The swipe refresh layout must be manually moved below the app bar layout.
4932 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0)
4934 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
4935 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight)
4939 // Remove the `SYSTEM_UI` flags from the root frame layout. The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4940 @Suppress("DEPRECATION")
4941 rootFrameLayout.systemUiVisibility = 0
4944 // Consume the double-tap.
4946 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
4952 override fun onFling(motionEvent1: MotionEvent?, motionEvent2: MotionEvent, velocityX: Float, velocityY: Float): Boolean {
4953 // Scroll the bottom app bar if enabled.
4954 if (bottomAppBar && scrollAppBar && !objectAnimator.isRunning && (motionEvent1 != null)) {
4955 // Calculate the Y change.
4956 val motionY = motionEvent2.y - motionEvent1.y
4958 // Scroll the app bar if the change is greater than 50 pixels.
4960 // Animate the bottom app bar onto the screen.
4961 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0f)
4962 } else if (motionY < -50) {
4963 // Animate the bottom app bar off the screen.
4964 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", appBarLayout.height.toFloat())
4968 objectAnimator.start()
4971 // Do not consume the event.
4976 // Pass all touch events on the WebView through the double-tap gesture detector.
4977 nestedScrollWebView.setOnTouchListener { view: View, motionEvent: MotionEvent? ->
4978 // Call `performClick()` on the view, which is required for accessibility.
4981 // Check for double-taps.
4982 doubleTapGestureDetector.onTouchEvent(motionEvent!!)
4985 // Register the WebView for a context menu. This is used to see link targets and download images.
4986 registerForContextMenu(nestedScrollWebView)
4988 // Allow the downloading of files.
4989 nestedScrollWebView.setDownloadListener { downloadUrlString: String?, userAgent: String?, contentDisposition: String?, mimetype: String?, contentLength: Long ->
4990 // Check the download preference.
4991 if (downloadWithExternalApp) { // Download with an external app.
4992 downloadUrlWithExternalApp(downloadUrlString!!)
4993 } else { // Handle the download inside of Privacy Browser.
4994 // Define a formatted file size string.
4996 // Process the content length if it contains data.
4997 val formattedFileSizeString = if (contentLength > 0) { // The content length is greater than 0.
4998 // Format the content length as a string.
4999 NumberFormat.getInstance().format(contentLength) + " " + getString(R.string.bytes)
5000 } else { // The content length is not greater than 0.
5001 // Set the formatted file size string to be `unknown size`.
5002 getString(R.string.unknown_size)
5005 // Get the file name from the content disposition.
5006 val fileNameString = UrlHelper.getFileName(this, contentDisposition, mimetype, downloadUrlString!!)
5008 // Instantiate the save dialog.
5009 val saveDialogFragment = SaveDialog.saveUrl(downloadUrlString, fileNameString, formattedFileSizeString, userAgent!!, nestedScrollWebView.acceptCookies)
5011 // 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.
5013 // Show the save dialog.
5014 saveDialogFragment.show(supportFragmentManager, getString(R.string.save_dialog))
5015 } catch (exception: Exception) { // The dialog could not be shown.
5016 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
5017 pendingDialogsArrayList.add(PendingDialogDataClass(saveDialogFragment, getString(R.string.save_dialog)))
5021 // Get the current page position.
5022 val currentPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
5024 // Get the corresponding tab.
5025 val tab = tabLayout.getTabAt(currentPagePosition)!!
5027 // Get the tab custom view.
5028 val tabCustomView = tab.customView!!
5030 // Get the tab views.
5031 val tabFavoriteIconImageView = tabCustomView.findViewById<ImageView>(R.id.favorite_icon_imageview)
5032 val tabTitleTextView = tabCustomView.findViewById<TextView>(R.id.title_textview)
5034 // Restore the previous webpage favorite icon and title if the title is currently set to `Loading...`.
5035 if (tabTitleTextView.text.toString() == getString(R.string.loading)) {
5036 // Restore the previous webpage title text.
5037 tabTitleTextView.text = nestedScrollWebView.previousWebpageTitle
5039 // Restore the previous webpage favorite icon if it is not null.
5040 if (nestedScrollWebView.previousFavoriteIconDrawable != null)
5041 tabFavoriteIconImageView.setImageDrawable(nestedScrollWebView.previousFavoriteIconDrawable)
5045 // Update the find on page count.
5046 nestedScrollWebView.setFindListener { activeMatchOrdinal, numberOfMatches, isDoneCounting ->
5047 if (isDoneCounting && (numberOfMatches == 0)) { // There are no matches.
5048 // Set the find on page count text view to be `0/0`.
5049 findOnPageCountTextView.setText(R.string.zero_of_zero)
5050 } else if (isDoneCounting) { // There are matches.
5051 // The active match ordinal is zero-based.
5052 val activeMatch = activeMatchOrdinal + 1
5054 // Build the match string.
5055 val matchString = "$activeMatch/$numberOfMatches"
5057 // Update the find on page count text view.
5058 findOnPageCountTextView.text = matchString
5062 // Process scroll changes.
5063 nestedScrollWebView.setOnScrollChangeListener { _: View?, _: Int, _: Int, _: Int, _: Int ->
5064 // Set the swipe to refresh status.
5065 if (nestedScrollWebView.swipeToRefresh) // Only enable swipe to refresh if the WebView is scrolled to the top.
5066 swipeRefreshLayout.isEnabled = nestedScrollWebView.scrollY == 0
5067 else // Disable swipe to refresh.
5068 swipeRefreshLayout.isEnabled = false
5070 // Reinforce the system UI visibility flags if in full screen browsing mode.
5071 // This hides the status and navigation bars, which are displayed if other elements are shown, like dialog boxes, the options menu, or the keyboard.
5072 if (inFullScreenBrowsingMode) {
5073 /* Hide the system bars.
5074 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5075 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5076 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5077 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5080 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
5081 @Suppress("DEPRECATION")
5082 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
5086 // Set the web chrome client.
5087 nestedScrollWebView.webChromeClient = object : WebChromeClient() {
5088 // Update the progress bar when a page is loading.
5089 override fun onProgressChanged(view: WebView, progress: Int) {
5090 // Update the progress bar.
5091 progressBar.progress = progress
5093 // Set the visibility of the progress bar.
5094 if (progress < 100) {
5095 // Show the progress bar.
5096 progressBar.visibility = View.VISIBLE
5098 // Hide the progress bar.
5099 progressBar.visibility = View.GONE
5101 //Stop the swipe to refresh indicator if it is running
5102 swipeRefreshLayout.isRefreshing = false
5104 // 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.
5105 nestedScrollWebView.visibility = View.VISIBLE
5109 // Set the favorite icon when it changes.
5110 override fun onReceivedIcon(view: WebView, icon: Bitmap) {
5111 // 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.
5112 // This prevents low resolution icons from replacing high resolution one.
5113 // The check for the visibility of the progress bar can possibly be removed once https://redmine.stoutner.com/issues/747 is fixed.
5114 if ((progressBar.visibility == View.GONE) && (icon.height > nestedScrollWebView.getFavoriteIconHeight())) {
5115 // Store the new favorite icon.
5116 nestedScrollWebView.setFavoriteIcon(icon)
5118 // Get the current page position.
5119 val currentPosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
5121 // Get the current tab.
5122 val tab = tabLayout.getTabAt(currentPosition)
5124 // Check to see if the tab has been populated.
5126 // Get the custom view from the tab.
5127 val tabView = tab.customView
5129 // Check to see if the custom tab view has been populated.
5130 if (tabView != null) {
5131 // Get the favorite icon image view from the tab.
5132 val tabFavoriteIconImageView = tabView.findViewById<ImageView>(R.id.favorite_icon_imageview)
5134 // Display the favorite icon in the tab.
5135 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true))
5141 // Save a copy of the title when it changes.
5142 override fun onReceivedTitle(view: WebView, title: String) {
5143 // Get the current page position.
5144 val currentPosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
5146 // Get the current tab.
5147 val tab = tabLayout.getTabAt(currentPosition)
5149 // Only populate the title text view if the tab has been fully created.
5151 // Get the custom view from the tab.
5152 val tabView = tab.customView
5154 // Only populate the title text view if the tab view has been fully populated.
5155 if (tabView != null) {
5156 // Get the title text view from the tab.
5157 val tabTitleTextView = tabView.findViewById<TextView>(R.id.title_textview)
5159 // Set the title according to the URL.
5160 if (title == "about:blank") {
5161 // Set the title to indicate a new tab.
5162 tabTitleTextView.setText(R.string.new_tab)
5164 // Set the title as the tab text.
5165 tabTitleTextView.text = title
5171 // Enter full screen video.
5172 override fun onShowCustomView(video: View, callback: CustomViewCallback) {
5173 // Set the full screen video flag.
5174 displayingFullScreenVideo = true
5176 // Hide the keyboard.
5177 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.windowToken, 0)
5179 // Hide the coordinator layout.
5180 coordinatorLayout.visibility = View.GONE
5182 /* Hide the system bars.
5183 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5184 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5185 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5186 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5189 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
5190 @Suppress("DEPRECATION")
5191 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
5193 // Disable the sliding drawers.
5194 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
5196 // Add the video view to the full screen video frame layout.
5197 fullScreenVideoFrameLayout.addView(video)
5199 // Show the full screen video frame layout.
5200 fullScreenVideoFrameLayout.visibility = View.VISIBLE
5202 // Disable the screen timeout while the video is playing. YouTube does this automatically, but not all other videos do.
5203 fullScreenVideoFrameLayout.keepScreenOn = true
5206 // Exit full screen video.
5207 override fun onHideCustomView() {
5208 // Exit the full screen video.
5209 exitFullScreenVideo()
5213 override fun onShowFileChooser(webView: WebView, filePathCallback: ValueCallback<Array<Uri>>, fileChooserParams: FileChooserParams): Boolean {
5214 // Store the file path callback.
5215 fileChooserCallback = filePathCallback
5217 // Create an intent to open a chooser based on the file chooser parameters.
5218 val fileChooserIntent = fileChooserParams.createIntent()
5220 // Check to see if the file chooser intent resolves to an installed package.
5221 if (fileChooserIntent.resolveActivity(packageManager) != null) { // The file chooser intent is fine.
5222 // Launch the file chooser intent.
5223 browseFileUploadActivityResultLauncher.launch(fileChooserIntent)
5224 } else { // The file chooser intent will cause a crash.
5225 // Create a generic intent to open a chooser.
5226 val genericFileChooserIntent = Intent(Intent.ACTION_GET_CONTENT)
5228 // Request an openable file.
5229 genericFileChooserIntent.addCategory(Intent.CATEGORY_OPENABLE)
5231 // Set the file type to everything.
5232 genericFileChooserIntent.type = "*/*"
5234 // Launch the generic file chooser intent.
5235 browseFileUploadActivityResultLauncher.launch(genericFileChooserIntent)
5238 // Handle the event.
5242 nestedScrollWebView.webViewClient = object : WebViewClient() {
5243 // `shouldOverrideUrlLoading` makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
5244 override fun shouldOverrideUrlLoading(view: WebView, webResourceRequest: WebResourceRequest): Boolean {
5245 // Get the URL from the web resource request.
5246 var requestUrlString = webResourceRequest.url.toString()
5248 // Sanitize the url.
5249 requestUrlString = sanitizeUrl(requestUrlString)
5251 // Handle the URL according to the type.
5252 return if (requestUrlString.startsWith("http")) { // Load the URL in Privacy Browser.
5253 // Load the URL. By using `loadUrl()`, instead of `loadUrlFromBase()`, the Referer header will never be sent.
5254 loadUrl(nestedScrollWebView, requestUrlString)
5256 // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
5257 // Custom headers cannot be added if false is returned and the WebView handles the loading of the URL.
5259 } else if (requestUrlString.startsWith("mailto:")) { // Load the email address in an external email program.
5260 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
5261 val emailIntent = Intent(Intent.ACTION_SENDTO)
5263 // Parse the url and set it as the data for the intent.
5264 emailIntent.data = Uri.parse(requestUrlString)
5266 // Open the email program in a new task instead of as part of Privacy Browser.
5267 emailIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
5271 startActivity(emailIntent)
5272 } catch (exception: ActivityNotFoundException) {
5273 // Display a snackbar.
5274 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
5277 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5279 } else if (requestUrlString.startsWith("tel:")) { // Load the phone number in the dialer.
5280 // Create a dial intent.
5281 val dialIntent = Intent(Intent.ACTION_DIAL)
5283 // Add the phone number to the intent.
5284 dialIntent.data = Uri.parse(requestUrlString)
5286 // Open the dialer in a new task instead of as part of Privacy Browser.
5287 dialIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
5291 startActivity(dialIntent)
5292 } catch (exception: ActivityNotFoundException) {
5293 // Display a snackbar.
5294 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
5297 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5299 } else { // Load a system chooser to select an app that can handle the URL.
5300 // Create a generic intent to open an app.
5301 val genericIntent = Intent(Intent.ACTION_VIEW)
5303 // Add the URL to the intent.
5304 genericIntent.data = Uri.parse(requestUrlString)
5306 // List all apps that can handle the URL instead of just opening the first one.
5307 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE)
5309 // Open the app in a new task instead of as part of Privacy Browser.
5310 genericIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
5314 startActivity(genericIntent)
5315 } catch (exception: ActivityNotFoundException) {
5316 // Display a snackbar.
5317 Snackbar.make(nestedScrollWebView, getString(R.string.unrecognized_url, requestUrlString), Snackbar.LENGTH_SHORT).show()
5320 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5325 // Check requests against the block lists.
5326 override fun shouldInterceptRequest(view: WebView, webResourceRequest: WebResourceRequest): WebResourceResponse? {
5328 val requestUrlString = webResourceRequest.url.toString()
5330 // Check to see if the resource request is for the main URL.
5331 if (requestUrlString == nestedScrollWebView.currentUrl) {
5332 // `return null` loads the resource request, which should never be blocked if it is the main URL.
5336 // 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.
5337 while (ultraPrivacy == null) {
5339 // Check to see if the filter lists have been populated after 100 ms.
5341 } catch (exception: InterruptedException) {
5346 // Create an empty web resource response to be used if the resource request is blocked.
5347 val emptyWebResourceResponse = WebResourceResponse("text/plain", "utf8", ByteArrayInputStream("".toByteArray()))
5349 // Initialize the variables.
5350 var allowListResultStringArray: Array<String>? = null
5351 var isThirdPartyRequest = false
5353 // Get the current URL. `.getUrl()` throws an error because operations on the WebView cannot be made from this thread.
5354 var currentBaseDomain = nestedScrollWebView.currentDomainName
5356 // Store a copy of the current domain for use in later requests.
5357 val currentDomain = currentBaseDomain
5359 // Get the request host name.
5360 var requestBaseDomain = webResourceRequest.url.host
5362 // Only check for third-party requests if the current base domain is not empty and the request domain is not null.
5363 if (currentBaseDomain.isNotEmpty() && (requestBaseDomain != null)) {
5364 // Determine the current base domain.
5365 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5366 // Remove the first subdomain.
5367 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1)
5370 // Determine the request base domain.
5371 while (requestBaseDomain!!.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5372 // Remove the first subdomain.
5373 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1)
5376 // Update the third party request tracker.
5377 isThirdPartyRequest = currentBaseDomain != requestBaseDomain
5380 // Get the current WebView page position.
5381 val webViewPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
5383 // Determine if the WebView is currently displayed.
5384 val webViewDisplayed = (webViewPagePosition == tabLayout.selectedTabPosition)
5386 // Block third-party requests if enabled.
5387 if (isThirdPartyRequest && nestedScrollWebView.blockAllThirdPartyRequests) {
5388 // Add the result to the resource requests.
5389 nestedScrollWebView.addResourceRequest(arrayOf(REQUEST_THIRD_PARTY, requestUrlString))
5391 // Increment the blocked requests counters.
5392 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5393 nestedScrollWebView.incrementRequestsCount(THIRD_PARTY_REQUESTS)
5395 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5396 if (webViewDisplayed) {
5397 // Updating the UI must be run from the UI thread.
5399 // Update the menu item titles.
5400 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5402 // Update the options menu if it has been populated.
5403 if (optionsMenu != null) {
5404 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5405 optionsBlockAllThirdPartyRequestsMenuItem.title =
5406 nestedScrollWebView.getRequestsCount(THIRD_PARTY_REQUESTS).toString() + " - " + getString(R.string.block_all_third_party_requests)
5411 // The resource request was blocked. Return an empty web resource response.
5412 return emptyWebResourceResponse
5415 // Check UltraList if it is enabled.
5416 if (nestedScrollWebView.ultraListEnabled) {
5417 // Check the URL against UltraList.
5418 val ultraListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, ultraList)
5420 // Process the UltraList results.
5421 if (ultraListResults[0] == REQUEST_BLOCKED) { // The resource request matched UltraList's block list.
5422 // Add the result to the resource requests.
5423 nestedScrollWebView.addResourceRequest(arrayOf(ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]))
5425 // Increment the blocked requests counters.
5426 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5427 nestedScrollWebView.incrementRequestsCount(com.stoutner.privacybrowser.views.ULTRALIST)
5429 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5430 if (webViewDisplayed) {
5431 // Updating the UI must be run from the UI thread.
5433 // Update the menu item titles.
5434 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5436 // Update the options menu if it has been populated.
5437 if (optionsMenu != null) {
5438 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5439 optionsUltraListMenuItem.title = nestedScrollWebView.getRequestsCount(com.stoutner.privacybrowser.views.ULTRALIST).toString() + " - " + getString(R.string.ultralist)
5444 // The resource request was blocked. Return an empty web resource response.
5445 return emptyWebResourceResponse
5446 } else if (ultraListResults[0] == REQUEST_ALLOWED) { // The resource request matched UltraList's allow list.
5447 // Add an allow list entry to the resource requests array.
5448 nestedScrollWebView.addResourceRequest(arrayOf(ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]))
5450 // The resource request has been allowed by UltraList. `return null` loads the requested resource.
5455 // Check UltraPrivacy if it is enabled.
5456 if (nestedScrollWebView.ultraPrivacyEnabled) {
5457 // Check the URL against UltraPrivacy.
5458 val ultraPrivacyResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, ultraPrivacy!!)
5460 // Process the UltraPrivacy results.
5461 if (ultraPrivacyResults[0] == REQUEST_BLOCKED) { // The resource request matched UltraPrivacy's block list.
5462 // Add the result to the resource requests.
5463 nestedScrollWebView.addResourceRequest(arrayOf(ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5464 ultraPrivacyResults[5]))
5466 // Increment the blocked requests counters.
5467 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5468 nestedScrollWebView.incrementRequestsCount(ULTRAPRIVACY)
5470 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5471 if (webViewDisplayed) {
5472 // Updating the UI must be run from the UI thread.
5474 // Update the menu item titles.
5475 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5477 // Update the options menu if it has been populated.
5478 if (optionsMenu != null) {
5479 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5480 optionsUltraPrivacyMenuItem.title = nestedScrollWebView.getRequestsCount(ULTRAPRIVACY).toString() + " - " + getString(R.string.ultraprivacy)
5485 // The resource request was blocked. Return an empty web resource response.
5486 return emptyWebResourceResponse
5487 } else if (ultraPrivacyResults[0] == REQUEST_ALLOWED) { // The resource request matched UltraPrivacy's allow list.
5488 // Add an allow list entry to the resource requests array.
5489 nestedScrollWebView.addResourceRequest(arrayOf(ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5490 ultraPrivacyResults[5]))
5492 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
5497 // Check EasyList if it is enabled.
5498 if (nestedScrollWebView.easyListEnabled) {
5499 // Check the URL against EasyList.
5500 val easyListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, easyList)
5502 // Process the EasyList results.
5503 if (easyListResults[0] == REQUEST_BLOCKED) { // The resource request matched EasyList's block list.
5504 // Add the result to the resource requests.
5505 nestedScrollWebView.addResourceRequest(arrayOf(easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]))
5507 // Increment the blocked requests counters.
5508 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5509 nestedScrollWebView.incrementRequestsCount(EASYLIST)
5511 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5512 if (webViewDisplayed) {
5513 // Updating the UI must be run from the UI thread.
5515 // Update the menu item titles.
5516 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5518 // Update the options menu if it has been populated.
5519 if (optionsMenu != null) {
5520 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5521 optionsEasyListMenuItem.title = nestedScrollWebView.getRequestsCount(EASYLIST).toString() + " - " + getString(R.string.easylist)
5526 // The resource request was blocked. Return an empty web resource response.
5527 return emptyWebResourceResponse
5528 } else if (easyListResults[0] == REQUEST_ALLOWED) { // The resource request matched EasyList's allow list.
5529 // Update the allow list result string array tracker.
5530 allowListResultStringArray = arrayOf(easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5])
5534 // Check EasyPrivacy if it is enabled.
5535 if (nestedScrollWebView.easyPrivacyEnabled) {
5536 // Check the URL against EasyPrivacy.
5537 val easyPrivacyResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, easyPrivacy)
5539 // Process the EasyPrivacy results.
5540 if (easyPrivacyResults[0] == REQUEST_BLOCKED) { // The resource request matched EasyPrivacy's block list.
5541 // Add the result to the resource requests.
5542 nestedScrollWebView.addResourceRequest(arrayOf(easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5]))
5544 // Increment the blocked requests counters.
5545 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5546 nestedScrollWebView.incrementRequestsCount(EASYPRIVACY)
5548 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5549 if (webViewDisplayed) {
5550 // Updating the UI must be run from the UI thread.
5552 // Update the menu item titles.
5553 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5555 // Update the options menu if it has been populated.
5556 if (optionsMenu != null) {
5557 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5558 optionsEasyPrivacyMenuItem.title = nestedScrollWebView.getRequestsCount(EASYPRIVACY).toString() + " - " + getString(R.string.easyprivacy)
5563 // The resource request was blocked. Return an empty web resource response.
5564 return emptyWebResourceResponse
5565 } else if (easyPrivacyResults[0] == REQUEST_ALLOWED) { // The resource request matched EasyPrivacy's allow list.
5566 // Update the allow list result string array tracker.
5567 allowListResultStringArray = arrayOf(easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5])
5571 // Check Fanboy’s Annoyance List if it is enabled.
5572 if (nestedScrollWebView.fanboysAnnoyanceListEnabled) {
5573 // Check the URL against Fanboy's Annoyance List.
5574 val fanboysAnnoyanceListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, fanboysAnnoyanceList)
5576 // Process the Fanboy's Annoyance List results.
5577 if (fanboysAnnoyanceListResults[0] == REQUEST_BLOCKED) { // The resource request matched Fanboy's Annoyance List's block list.
5578 // Add the result to the resource requests.
5579 nestedScrollWebView.addResourceRequest(arrayOf(fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5580 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]))
5582 // Increment the blocked requests counters.
5583 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5584 nestedScrollWebView.incrementRequestsCount(FANBOYS_ANNOYANCE_LIST)
5586 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5587 if (webViewDisplayed) {
5588 // Updating the UI must be run from the UI thread.
5590 // Update the menu item titles.
5591 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5593 // Update the options menu if it has been populated.
5594 if (optionsMenu != null) {
5595 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5596 optionsFanboysAnnoyanceListMenuItem.title = nestedScrollWebView.getRequestsCount(FANBOYS_ANNOYANCE_LIST).toString() + " - " + getString(R.string.fanboys_annoyance_list)
5601 // The resource request was blocked. Return an empty web resource response.
5602 return emptyWebResourceResponse
5603 } else if (fanboysAnnoyanceListResults[0] == REQUEST_ALLOWED) { // The resource request matched Fanboy's Annoyance List's allow list.
5604 // Update the allow list result string array tracker.
5605 allowListResultStringArray = arrayOf(fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5606 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5])
5608 } else if (nestedScrollWebView.fanboysSocialBlockingListEnabled) { // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
5609 // Check the URL against Fanboy's Annoyance List.
5610 val fanboysSocialListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, fanboysSocialList)
5612 // Process the Fanboy's Social Blocking List results.
5613 if (fanboysSocialListResults[0] == REQUEST_BLOCKED) { // The resource request matched Fanboy's Social Blocking List's block list.
5614 // Add the result to the resource requests.
5615 nestedScrollWebView.addResourceRequest(arrayOf(fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5616 fanboysSocialListResults[4], fanboysSocialListResults[5]))
5618 // Increment the blocked requests counters.
5619 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5620 nestedScrollWebView.incrementRequestsCount(FANBOYS_SOCIAL_BLOCKING_LIST)
5622 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5623 if (webViewDisplayed) {
5624 // Updating the UI must be run from the UI thread.
5626 // Update the menu item titles.
5627 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5629 // Update the options menu if it has been populated.
5630 if (optionsMenu != null) {
5631 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5632 optionsFanboysSocialBlockingListMenuItem.title =
5633 nestedScrollWebView.getRequestsCount(FANBOYS_SOCIAL_BLOCKING_LIST).toString() + " - " + getString(R.string.fanboys_social_blocking_list)
5638 // The resource request was blocked. Return an empty web resource response.
5639 return emptyWebResourceResponse
5640 } else if (fanboysSocialListResults[0] == REQUEST_ALLOWED) { // The resource request matched Fanboy's Social Blocking List's allow list.
5641 // Update the allow list result string array tracker.
5642 allowListResultStringArray = arrayOf(fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3], fanboysSocialListResults[4],
5643 fanboysSocialListResults[5])
5647 // Add the request to the log because it hasn't been processed by any of the previous checks.
5648 if (allowListResultStringArray != null) { // The request was processed by an allow list.
5649 nestedScrollWebView.addResourceRequest(allowListResultStringArray)
5650 } else { // The request didn't match any filter list entry. Log it as a default request.
5651 nestedScrollWebView.addResourceRequest(arrayOf(REQUEST_DEFAULT, requestUrlString))
5654 // The resource request has not been blocked. `return null` loads the requested resource.
5658 // Handle HTTP authentication requests.
5659 override fun onReceivedHttpAuthRequest(view: WebView, handler: HttpAuthHandler, host: String, realm: String) {
5660 // Store the handler.
5661 nestedScrollWebView.httpAuthHandler = handler
5663 // Instantiate an HTTP authentication dialog.
5664 val httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm, nestedScrollWebView.webViewFragmentId)
5666 // Show the HTTP authentication dialog.
5667 httpAuthenticationDialogFragment.show(supportFragmentManager, getString(R.string.http_authentication))
5670 override fun onPageStarted(webView: WebView, url: String, favicon: Bitmap?) {
5671 // Get the app bar layout height. This can't be done in `applyAppSettings()` because the app bar is not yet populated there.
5672 // 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.
5673 if (appBarLayout.height > 0)
5674 appBarHeight = appBarLayout.height
5676 // Set the padding and layout settings according to the position of the app bar.
5677 if (bottomAppBar) { // The app bar is on the bottom.
5679 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) { // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
5680 // Reset the WebView padding to fill the available space.
5681 swipeRefreshLayout.setPadding(0, 0, 0, 0)
5682 } else { // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
5683 // Move the WebView above the app bar layout.
5684 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
5686 } else { // The app bar is on the top.
5687 // 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.
5688 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) { // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
5689 // No padding is needed because it will automatically be placed below the app bar layout due to the scrolling layout behavior.
5690 swipeRefreshLayout.setPadding(0, 0, 0, 0)
5692 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5693 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10, defaultProgressViewEndOffset)
5694 } else { // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
5695 // The swipe refresh layout must be manually moved below the app bar layout.
5696 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0)
5698 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5699 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight)
5703 // Reset the list of resource requests.
5704 nestedScrollWebView.clearResourceRequests()
5706 // Reset the requests counters.
5707 nestedScrollWebView.resetRequestsCounters()
5709 // Get the current page position.
5710 val currentPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
5712 // Update the URL text bar if the page is currently selected and the URL edit text is not currently being edited.
5713 if ((tabLayout.selectedTabPosition == currentPagePosition) && !urlEditText.hasFocus()) {
5714 // Display the formatted URL text. The nested scroll WebView current URL preserves any initial `view-source:`, and opposed to the method URL variable.
5715 urlEditText.setText(nestedScrollWebView.currentUrl)
5717 // Highlight the URL syntax.
5718 UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
5720 // Hide the keyboard.
5721 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.windowToken, 0)
5724 // Reset the list of host IP addresses.
5725 nestedScrollWebView.currentIpAddresses = ""
5727 // Get a URI for the current URL.
5728 val currentUri = Uri.parse(url)
5730 // Get the current domain name.
5731 val currentDomainName = currentUri.host
5733 // Get the IP addresses for the current domain.
5734 if (!currentDomainName.isNullOrEmpty())
5735 GetHostIpAddressesCoroutine.checkPinnedMismatch(currentDomainName, nestedScrollWebView, supportFragmentManager, getString(R.string.pinned_mismatch))
5737 // 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.)
5738 if ((optionsMenu != null) && (webView == currentWebView)) {
5740 optionsRefreshMenuItem.setTitle(R.string.stop)
5742 // Set the icon if it is displayed in the AppBar.
5743 if (displayAdditionalAppBarIcons)
5744 optionsRefreshMenuItem.setIcon(R.drawable.close_blue)
5748 override fun onPageFinished(webView: WebView, url: String) {
5749 // Flush any cookies to persistent storage. The cookie manager has become very lazy about flushing cookies in recent versions.
5750 if (nestedScrollWebView.acceptCookies)
5751 cookieManager.flush()
5753 // Update the Refresh menu item if the options menu has been created and the WebView is currently displayed.
5754 if (optionsMenu != null && (webView == currentWebView)) {
5755 // Reset the Refresh title.
5756 optionsRefreshMenuItem.setTitle(R.string.refresh)
5758 // Reset the icon if it is displayed in the app bar.
5759 if (displayAdditionalAppBarIcons)
5760 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled)
5763 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
5764 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
5765 val privateDataDirectoryString = applicationInfo.dataDir
5767 // Clear the cache, history, and logcat if Incognito Mode is enabled.
5768 if (incognitoModeEnabled) {
5769 // Clear the cache. `true` includes disk files.
5770 nestedScrollWebView.clearCache(true)
5772 // Clear the back/forward history.
5773 nestedScrollWebView.clearHistory()
5775 // Manually delete cache folders.
5777 // Delete the main cache directory.
5778 Runtime.getRuntime().exec("rm -rf $privateDataDirectoryString/cache")
5779 } catch (exception: IOException) {
5780 // Do nothing if an error is thrown.
5783 // Clear the logcat.
5785 // Clear the logcat. `-c` clears the logcat. `-b all` clears all the buffers (instead of just crash, main, and system).
5786 Runtime.getRuntime().exec("logcat -b all -c")
5787 } catch (exception: IOException) {
5792 // Clear the `Service Worker` directory.
5794 // A string array must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
5795 Runtime.getRuntime().exec(arrayOf("rm", "-rf", "$privateDataDirectoryString/app_webview/Default/Service Worker/"))
5796 } catch (exception: IOException) {
5800 // Get the current page position.
5801 val currentPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
5803 // 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.
5804 val currentUrl = nestedScrollWebView.url
5806 // Get the current tab.
5807 val tab = tabLayout.getTabAt(currentPagePosition)
5809 // Update the URL text bar if the page is currently selected and the user is not currently typing in the URL edit text.
5810 // Crash records show that, in some crazy way, it is possible for the current URL to be blank at this point.
5811 // Probably some sort of race condition when Privacy Browser is being resumed.
5812 if ((tabLayout.selectedTabPosition == currentPagePosition) && !urlEditText.hasFocus() && (currentUrl != null)) {
5813 // Check to see if the URL is `about:blank`.
5814 if (currentUrl == "about:blank") { // The WebView is blank.
5815 // Display the hint in the URL edit text.
5816 urlEditText.setText("")
5818 // Request focus for the URL text box.
5819 urlEditText.requestFocus()
5821 // Display the keyboard.
5822 inputMethodManager.showSoftInput(urlEditText, 0)
5824 // Apply the domain settings. This clears any settings from the previous domain.
5825 applyDomainSettings(nestedScrollWebView, "", resetTab = true, reloadWebsite = false, loadUrl = false)
5827 // Only populate the title text view if the tab has been fully created.
5829 // Get the custom view from the tab.
5830 val tabView = tab.customView!!
5832 // Get the title text view from the tab.
5833 val tabTitleTextView = tabView.findViewById<TextView>(R.id.title_textview)
5835 // Set the title as the tab text.
5836 tabTitleTextView.setText(R.string.new_tab)
5838 } else { // The WebView has loaded a webpage.
5839 // Update the URL edit text if it is not currently being edited.
5840 if (!urlEditText.hasFocus()) {
5841 // 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.
5842 val sanitizedUrl = sanitizeUrl(currentUrl)
5844 // Display the final URL. Getting the URL from the WebView instead of using the one provided by `onPageFinished()` makes websites like YouTube function correctly.
5845 urlEditText.setText(sanitizedUrl)
5847 // Highlight the URL syntax.
5848 UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
5851 // Only populate the title text view if the tab has been fully created.
5853 // Get the custom view from the tab.
5854 val tabView = tab.customView!!
5856 // Get the title text view from the tab.
5857 val tabTitleTextView = tabView.findViewById<TextView>(R.id.title_textview)
5859 // Set the title as the tab text. Sometimes `onReceivedTitle()` is not called, especially when navigating history.
5860 tabTitleTextView.text = nestedScrollWebView.title
5866 // Handle SSL Certificate errors. Suppress the lint warning that ignoring the error might be dangerous.
5867 @SuppressLint("WebViewClientOnReceivedSslError")
5868 override fun onReceivedSslError(view: WebView, handler: SslErrorHandler, error: SslError) {
5869 // Get the current website SSL certificate.
5870 val currentWebsiteSslCertificate = error.certificate
5872 // Extract the individual pieces of information from the current website SSL certificate.
5873 val currentWebsiteIssuedToCName = currentWebsiteSslCertificate.issuedTo.cName
5874 val currentWebsiteIssuedToOName = currentWebsiteSslCertificate.issuedTo.oName
5875 val currentWebsiteIssuedToUName = currentWebsiteSslCertificate.issuedTo.uName
5876 val currentWebsiteIssuedByCName = currentWebsiteSslCertificate.issuedBy.cName
5877 val currentWebsiteIssuedByOName = currentWebsiteSslCertificate.issuedBy.oName
5878 val currentWebsiteIssuedByUName = currentWebsiteSslCertificate.issuedBy.uName
5879 val currentWebsiteSslStartDate = currentWebsiteSslCertificate.validNotBeforeDate
5880 val currentWebsiteSslEndDate = currentWebsiteSslCertificate.validNotAfterDate
5882 // Get the pinned SSL certificate.
5883 val (pinnedSslCertificateStringArray, pinnedSslCertificateDateArray) = nestedScrollWebView.getPinnedSslCertificate()
5885 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
5886 if (nestedScrollWebView.hasPinnedSslCertificate() &&
5887 (currentWebsiteIssuedToCName == pinnedSslCertificateStringArray[0]) &&
5888 (currentWebsiteIssuedToOName == pinnedSslCertificateStringArray[1]) &&
5889 (currentWebsiteIssuedToUName == pinnedSslCertificateStringArray[2]) &&
5890 (currentWebsiteIssuedByCName == pinnedSslCertificateStringArray[3]) &&
5891 (currentWebsiteIssuedByOName == pinnedSslCertificateStringArray[4]) &&
5892 (currentWebsiteIssuedByUName == pinnedSslCertificateStringArray[5]) &&
5893 (currentWebsiteSslStartDate == pinnedSslCertificateDateArray[0]) &&
5894 (currentWebsiteSslEndDate == pinnedSslCertificateDateArray[1])) {
5896 // An SSL certificate is pinned and matches the current domain certificate. Proceed to the website without displaying an error.
5898 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
5899 // Store the SSL error handler.
5900 nestedScrollWebView.sslErrorHandler = handler
5902 // Instantiate an SSL certificate error alert dialog.
5903 val sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error, nestedScrollWebView.webViewFragmentId)
5905 // 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.
5907 // Show the SSL certificate error dialog.
5908 sslCertificateErrorDialogFragment.show(supportFragmentManager, getString(R.string.ssl_certificate_error))
5909 } catch (exception: Exception) {
5910 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
5911 pendingDialogsArrayList.add(PendingDialogDataClass(sslCertificateErrorDialogFragment, getString(R.string.ssl_certificate_error)))
5917 // Check to see if the state is being restored.
5918 if (restoringState) { // The state is being restored.
5919 // Resume the nested scroll WebView JavaScript timers.
5920 nestedScrollWebView.resumeTimers()
5921 } else if (pagePosition == 0) { // The first page is being loaded.
5922 // Set this nested scroll WebView as the current WebView.
5923 currentWebView = nestedScrollWebView
5925 // Get the intent that started the app.
5926 val launchingIntent = intent
5928 // Reset the intent. This prevents a duplicate tab from being created on restart.
5931 // Get the information from the intent.
5932 val launchingIntentAction = launchingIntent.action
5933 val launchingIntentUriData = launchingIntent.data
5934 val launchingIntentStringExtra = launchingIntent.getStringExtra(Intent.EXTRA_TEXT)
5936 // Parse the launching intent URL. Suppress the suggestions of using elvis expressions as they make the logic very difficult to follow.
5937 @Suppress("IfThenToElvis") val urlToLoadString = if ((launchingIntentAction != null) && (launchingIntentAction == Intent.ACTION_WEB_SEARCH)) { // The intent contains a search string.
5938 // Sanitize the search input and convert it to a search.
5939 val encodedSearchString = try {
5940 URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8")
5941 } catch (exception: UnsupportedEncodingException) {
5945 // Add the search URL to the encodedSearchString
5946 searchURL + encodedSearchString
5947 } else if (launchingIntentUriData != null) { // The launching intent contains a URL formatted as a URI.
5948 // Get the URL from the URI.
5949 launchingIntentUriData.toString()
5950 } else if (launchingIntentStringExtra != null) { // The launching intent contains text that might be a URL.
5951 // Get the URL from the string extra.
5952 launchingIntentStringExtra
5953 } else if (urlString != "") { // The activity has been restarted.
5954 // Load the saved URL.
5956 } else { // The is no saved URL and there is no URL in the intent.
5957 // Load the homepage.
5958 sharedPreferences.getString("homepage", getString(R.string.homepage_default_value))
5961 // Load the website if not waiting for the proxy.
5962 if (waitingForProxy) { // Store the URL to be loaded in the Nested Scroll WebView.
5963 nestedScrollWebView.waitingForProxyUrlString = urlToLoadString!!
5964 } else { // Load the URL.
5965 loadUrl(nestedScrollWebView, urlToLoadString!!)
5967 } else { // This is not the first tab.
5969 loadUrl(nestedScrollWebView, urlString)
5971 // Set the focus and display the keyboard if the URL is blank.
5972 if (urlString == "") {
5973 // Request focus for the URL text box.
5974 urlEditText.requestFocus()
5976 // Display the keyboard once the tab layout has settled.
5978 inputMethodManager.showSoftInput(urlEditText, 0)
5984 private fun loadBookmarksFolder() {
5985 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
5986 bookmarksCursor = bookmarksDatabaseHelper!!.getBookmarksByDisplayOrder(currentBookmarksFolderId)
5988 // Populate the bookmarks cursor adapter.
5989 bookmarksCursorAdapter = object : CursorAdapter(this, bookmarksCursor, false) {
5990 override fun newView(context: Context, cursor: Cursor, parent: ViewGroup): View {
5991 // Inflate the individual item layout.
5992 return layoutInflater.inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false)
5995 override fun bindView(view: View, context: Context, cursor: Cursor) {
5996 // Get handles for the views.
5997 val bookmarkFavoriteIcon = view.findViewById<ImageView>(R.id.bookmark_favorite_icon)
5998 val bookmarkNameTextView = view.findViewById<TextView>(R.id.bookmark_name)
6000 // Get the favorite icon byte array from the cursor.
6001 val favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndexOrThrow(FAVORITE_ICON))
6003 // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
6004 val favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.size)
6006 // Display the bitmap in the bookmark favorite icon.
6007 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap)
6009 // Display the bookmark name from the cursor in the bookmark name text view.
6010 bookmarkNameTextView.text = cursor.getString(cursor.getColumnIndexOrThrow(BOOKMARK_NAME))
6012 // Make the font bold for folders.
6013 if (cursor.getInt(cursor.getColumnIndexOrThrow(IS_FOLDER)) == 1)
6014 bookmarkNameTextView.typeface = Typeface.DEFAULT_BOLD
6015 else // Reset the font to default for normal bookmarks.
6016 bookmarkNameTextView.typeface = Typeface.DEFAULT
6020 // Populate the list view with the adapter.
6021 bookmarksListView.adapter = bookmarksCursorAdapter
6023 // Set the bookmarks drawer title.
6024 if (currentBookmarksFolderId == HOME_FOLDER_ID) // The current bookmarks folder is the home folder.
6025 bookmarksTitleTextView.setText(R.string.bookmarks)
6027 bookmarksTitleTextView.text = bookmarksDatabaseHelper!!.getFolderName(currentBookmarksFolderId)
6030 private fun loadUrl(nestedScrollWebView: NestedScrollWebView, url: String) {
6031 // Sanitize the URL.
6032 val urlString = sanitizeUrl(url)
6034 // Apply the domain settings and load the URL.
6035 applyDomainSettings(nestedScrollWebView, urlString, resetTab = true, reloadWebsite = false, loadUrl = true)
6038 private fun loadUrlFromTextBox() {
6039 // 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.
6040 var unformattedUrlString = urlEditText.text.toString().trim { it <= ' ' }
6042 // Create the formatted URL string.
6045 // Check to see if the unformatted URL string is a valid URL. Otherwise, convert it into a search.
6046 if (unformattedUrlString.startsWith("content://") || unformattedUrlString.startsWith("view-source:")) { // This is a content or source URL.
6047 // Load the entire content URL.
6048 urlString = unformattedUrlString
6049 } else if (Patterns.WEB_URL.matcher(unformattedUrlString).matches() || unformattedUrlString.startsWith("http://") || unformattedUrlString.startsWith("https://") ||
6050 unformattedUrlString.startsWith("file://")) { // This is a standard URL.
6052 // Add `https://` at the beginning if there is no protocol. Otherwise the app will segfault.
6053 if (!unformattedUrlString.startsWith("http") && !unformattedUrlString.startsWith("file://"))
6054 unformattedUrlString = "https://$unformattedUrlString"
6056 // Initialize the unformatted URL.
6057 var unformattedUrl: URL? = null
6059 // Convert the unformatted URL string to a URL.
6061 unformattedUrl = URL(unformattedUrlString)
6062 } catch (exception: MalformedURLException) {
6063 exception.printStackTrace()
6066 // Get the components of the URL.
6067 val scheme = unformattedUrl?.protocol
6068 val authority = unformattedUrl?.authority
6069 val path = unformattedUrl?.path
6070 val query = unformattedUrl?.query
6071 val fragment = unformattedUrl?.ref
6074 val uri = Uri.Builder()
6076 // Build the URI from the components of the URL.
6077 uri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment)
6079 // Decode the URI as a UTF-8 string in.
6081 urlString = URLDecoder.decode(uri.build().toString(), "UTF-8")
6082 } catch (exception: UnsupportedEncodingException) {
6083 // Do nothing. The formatted URL string will remain blank.
6085 } else if (unformattedUrlString.isNotEmpty()) { // This is not a URL, but rather a search string.
6086 // Sanitize the search input.
6087 val encodedSearchString = try {
6088 URLEncoder.encode(unformattedUrlString, "UTF-8")
6089 } catch (exception: UnsupportedEncodingException) {
6093 // Add the base search URL.
6094 urlString = searchURL + encodedSearchString
6097 // 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.
6098 urlEditText.clearFocus()
6101 loadUrl(currentWebView!!, urlString)
6104 override fun navigateHistory(url: String, steps: Int) {
6105 // Apply the domain settings.
6106 applyDomainSettings(currentWebView!!, url, resetTab = false, reloadWebsite = false, loadUrl = false)
6108 // Load the history entry.
6109 currentWebView!!.goBackOrForward(steps)
6111 // Update the URL edit text after a delay.
6112 updateUrlEditTextAfterDelay()
6115 override fun openFile(dialogFragment: DialogFragment) {
6117 val dialog = dialogFragment.dialog!!
6119 // Get handles for the views.
6120 val fileNameEditText = dialog.findViewById<EditText>(R.id.file_name_edittext)
6121 val mhtCheckBox = dialog.findViewById<CheckBox>(R.id.mht_checkbox)
6123 // Get the file path string.
6124 val openFilePath = fileNameEditText.text.toString()
6126 // Apply the domain settings. This resets the favorite icon and removes any domain settings.
6127 applyDomainSettings(currentWebView!!, openFilePath, resetTab = true, reloadWebsite = false, loadUrl = false)
6129 // Open the file according to the type.
6130 if (mhtCheckBox.isChecked) { // Force opening of an MHT file.
6132 // Get the MHT file input stream.
6133 val mhtFileInputStream = contentResolver.openInputStream(Uri.parse(openFilePath))
6135 // Create a temporary MHT file.
6136 val temporaryMhtFile = File.createTempFile(TEMPORARY_MHT_FILE, ".mht", cacheDir)
6138 // Get a file output stream for the temporary MHT file.
6139 val temporaryMhtFileOutputStream = FileOutputStream(temporaryMhtFile)
6141 // Create a transfer byte array.
6142 val transferByteArray = ByteArray(1024)
6144 // Create an integer to track the number of bytes read.
6147 // Copy the temporary MHT file input stream to the MHT output stream.
6148 while (mhtFileInputStream!!.read(transferByteArray).also { bytesRead = it } > 0)
6149 temporaryMhtFileOutputStream.write(transferByteArray, 0, bytesRead)
6151 // Flush the temporary MHT file output stream.
6152 temporaryMhtFileOutputStream.flush()
6154 // Close the streams.
6155 temporaryMhtFileOutputStream.close()
6156 mhtFileInputStream.close()
6158 // Load the temporary MHT file.
6159 currentWebView!!.loadUrl(temporaryMhtFile.toString())
6160 } catch (exception: Exception) {
6161 // Display a snackbar.
6162 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
6164 } else { // Let the WebView handle opening of the file.
6166 currentWebView!!.loadUrl(openFilePath)
6170 private fun openWithApp(url: String) {
6171 // Create an open with app intent with `ACTION_VIEW`.
6172 val openWithAppIntent = Intent(Intent.ACTION_VIEW)
6174 // Set the URI but not the MIME type. This should open all available apps.
6175 openWithAppIntent.data = Uri.parse(url)
6177 // Flag the intent to open in a new task.
6178 openWithAppIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
6182 // Show the chooser.
6183 startActivity(openWithAppIntent)
6184 } catch (exception: ActivityNotFoundException) { // There are no apps available to open the URL.
6185 // Show a snackbar with the error.
6186 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
6190 private fun openWithBrowser(url: String) {
6192 // Create an open with browser intent with `ACTION_VIEW`.
6193 val openWithBrowserIntent = Intent(Intent.ACTION_VIEW)
6195 // Set the URI and the MIME type. `"text/html"` should load browser options.
6196 openWithBrowserIntent.setDataAndType(Uri.parse(url), "text/html")
6198 // Flag the intent to open in a new task.
6199 openWithBrowserIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
6203 // Show the chooser.
6204 startActivity(openWithBrowserIntent)
6205 } catch (exception: ActivityNotFoundException) { // There are no browsers available to open the URL.
6206 // Show a snackbar with the error.
6207 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
6211 override fun pinnedErrorGoBack() {
6212 // Get the current web back forward list.
6213 val webBackForwardList = currentWebView!!.copyBackForwardList()
6215 // Get the previous entry URL.
6216 val previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex - 1).url
6218 // Apply the domain settings.
6219 applyDomainSettings(currentWebView!!, previousUrl, resetTab = false, reloadWebsite = false, loadUrl = false)
6222 currentWebView!!.goBack()
6224 // Update the URL edit text after a delay.
6225 updateUrlEditTextAfterDelay()
6228 private fun sanitizeUrl(urlString: String): String {
6229 // Initialize a sanitized URL string.
6230 var sanitizedUrlString = urlString
6232 // Sanitize tracking queries.
6233 if (sanitizeTrackingQueries)
6234 sanitizedUrlString = SanitizeUrlHelper.sanitizeTrackingQueries(sanitizedUrlString)
6236 // Sanitize AMP redirects.
6237 if (sanitizeAmpRedirects)
6238 sanitizedUrlString = SanitizeUrlHelper.sanitizeAmpRedirects(sanitizedUrlString)
6240 // Return the sanitized URL string.
6241 return sanitizedUrlString
6244 override fun saveUrl(originalUrlString: String, fileNameString: String, dialogFragment: DialogFragment) {
6245 // Store the URL. This will be used in the save URL activity result launcher.
6246 saveUrlString = if (originalUrlString.startsWith("data:")) {
6247 // Save the original URL.
6251 val dialog = dialogFragment.dialog!!
6253 // Get a handle for the dialog URL edit text.
6254 val dialogUrlEditText = dialog.findViewById<EditText>(R.id.url_edittext)
6256 // Get the URL from the edit text, which may have been modified.
6257 dialogUrlEditText.text.toString()
6260 // Open the file picker.
6261 saveUrlActivityResultLauncher.launch(fileNameString)
6264 private fun setCurrentWebView(pageNumber: Int) {
6265 // Stop the swipe to refresh indicator if it is running
6266 swipeRefreshLayout.isRefreshing = false
6268 // Try to set the current WebView. This will fail if the WebView has not yet been populated.
6270 // Get the WebView tab fragment.
6271 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(pageNumber)
6273 // Get the fragment view.
6274 val webViewFragmentView = webViewTabFragment.view
6276 // Store the current WebView.
6277 currentWebView = webViewFragmentView!!.findViewById(R.id.nestedscroll_webview)
6279 // Update the status of swipe to refresh.
6280 if (currentWebView!!.swipeToRefresh) { // Swipe to refresh is enabled.
6281 // Enable the swipe refresh layout if the WebView is scrolled all the way to the top. It is updated every time the scroll changes.
6282 swipeRefreshLayout.isEnabled = (currentWebView!!.scrollY == 0)
6283 } else { // Swipe to refresh is disabled.
6284 // Disable the swipe refresh layout.
6285 swipeRefreshLayout.isEnabled = false
6288 // Set the cookie status.
6289 cookieManager.setAcceptCookie(currentWebView!!.acceptCookies)
6291 // Update the privacy icons. `true` redraws the icons in the app bar.
6292 updatePrivacyIcons(true)
6294 // Get a handle for the input method manager.
6295 val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
6297 // Get the current URL.
6298 val urlString = currentWebView!!.url
6300 // Update the URL edit text if not loading a new intent. Otherwise, this will be handled by `onPageStarted()` (if called) and `onPageFinished()`.
6301 if (!loadingNewIntent) { // A new intent is not being loaded.
6302 if ((urlString == null) || (urlString == "about:blank")) { // The WebView is blank.
6303 // Display the hint in the URL edit text.
6304 urlEditText.setText("")
6306 // Request focus for the URL text box.
6307 urlEditText.requestFocus()
6309 // Display the keyboard.
6310 inputMethodManager.showSoftInput(urlEditText, 0)
6311 } else { // The WebView has a loaded URL.
6312 // Clear the focus from the URL text box.
6313 urlEditText.clearFocus()
6315 // Hide the soft keyboard.
6316 inputMethodManager.hideSoftInputFromWindow(currentWebView!!.windowToken, 0)
6318 // Display the current URL in the URL text box.
6319 urlEditText.setText(urlString)
6321 // Highlight the URL syntax.
6322 UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
6324 } else { // A new intent is being loaded.
6325 // Reset the loading new intent flag.
6326 loadingNewIntent = false
6329 // Set the background to indicate the domain settings status.
6330 if (currentWebView!!.domainSettingsApplied) {
6331 // Set a background on the URL relative layout to indicate that custom domain settings are being used.
6332 urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.drawable.domain_settings_url_background)
6334 // Remove any background on the URL relative layout.
6335 urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.color.transparent)
6337 } catch (exception: Exception) { // Try again in 10 milliseconds if the WebView has not yet been populated.
6338 // Create a handler to set the current WebView.
6339 val setCurrentWebViewHandler = Handler(Looper.getMainLooper())
6341 // Create a runnable to set the current WebView.
6342 val setCurrentWebWebRunnable = Runnable {
6343 // Set the current WebView.
6344 setCurrentWebView(pageNumber)
6347 // Try setting the current WebView again after 10 milliseconds.
6348 setCurrentWebViewHandler.postDelayed(setCurrentWebWebRunnable, 10)
6352 // The view parameter cannot be removed because it is called from the layout onClick.
6353 fun toggleBookmarksDrawerPinned(@Suppress("UNUSED_PARAMETER")view: View?) {
6354 // Toggle the bookmarks drawer pinned tracker.
6355 bookmarksDrawerPinned = !bookmarksDrawerPinned
6357 // Update the bookmarks drawer pinned image view.
6358 updateBookmarksDrawerPinnedImageView()
6361 private fun updateBookmarksDrawerPinnedImageView() {
6362 // Set the current icon.
6363 if (bookmarksDrawerPinned)
6364 bookmarksDrawerPinnedImageView.setImageResource(R.drawable.pin_selected)
6366 bookmarksDrawerPinnedImageView.setImageResource(R.drawable.pin)
6369 private fun updateDomainsSettingsSet() {
6370 // Reset the domains settings set.
6371 domainsSettingsSet = HashSet()
6373 // Get a domains cursor.
6374 val domainsCursor = domainsDatabaseHelper!!.domainNameCursorOrderedByDomain
6376 // Get the current count of domains.
6377 val domainsCount = domainsCursor.count
6379 // Get the domain name column index.
6380 val domainNameColumnIndex = domainsCursor.getColumnIndexOrThrow(DOMAIN_NAME)
6382 // Populate the domain settings set.
6383 for (i in 0 until domainsCount) {
6384 // Move the domains cursor to the current row.
6385 domainsCursor.moveToPosition(i)
6387 // Store the domain name in the domain settings set.
6388 domainsSettingsSet.add(domainsCursor.getString(domainNameColumnIndex))
6391 // Close the domains cursor.
6392 domainsCursor.close()
6395 override fun updateFontSize(dialogFragment: DialogFragment) {
6397 val dialog = dialogFragment.dialog!!
6399 // Get a handle for the font size edit text.
6400 val fontSizeEditText = dialog.findViewById<EditText>(R.id.font_size_edittext)
6402 // Initialize the new font size variable with the current font size.
6403 var newFontSize = currentWebView!!.settings.textZoom
6405 // Get the font size from the edit text.
6407 newFontSize = fontSizeEditText.text.toString().toInt()
6408 } catch (exception: Exception) {
6409 // If the edit text does not contain a valid font size do nothing.
6412 // Apply the new font size.
6413 currentWebView!!.settings.textZoom = newFontSize
6416 private fun updatePrivacyIcons(runInvalidateOptionsMenu: Boolean) {
6417 // Only update the privacy icons if the options menu and the current WebView have already been populated.
6418 if ((optionsMenu != null) && (currentWebView != null)) {
6419 // Update the privacy icon.
6420 if (currentWebView!!.settings.javaScriptEnabled) // JavaScript is enabled.
6421 optionsPrivacyMenuItem.setIcon(R.drawable.javascript_enabled)
6422 else if (currentWebView!!.acceptCookies) // JavaScript is disabled but cookies are enabled.
6423 optionsPrivacyMenuItem.setIcon(R.drawable.warning)
6424 else // All the dangerous features are disabled.
6425 optionsPrivacyMenuItem.setIcon(R.drawable.privacy_mode)
6427 // Update the cookies icon.
6428 if (currentWebView!!.acceptCookies)
6429 optionsCookiesMenuItem.setIcon(R.drawable.cookies_enabled)
6431 optionsCookiesMenuItem.setIcon(R.drawable.cookies_disabled)
6433 // Update the refresh icon.
6434 if (optionsRefreshMenuItem.title == getString(R.string.refresh)) // The refresh icon is displayed.
6435 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled)
6436 else // The stop icon is displayed.
6437 optionsRefreshMenuItem.setIcon(R.drawable.close_blue)
6439 // `invalidateOptionsMenu()` calls `onPrepareOptionsMenu()` and redraws the icons in the app bar.
6440 if (runInvalidateOptionsMenu)
6441 invalidateOptionsMenu()
6445 fun updateUrlEditTextAfterDelay() {
6446 // Create a handler to update the URL edit box.
6447 val urlEditTextUpdateHandler = Handler(Looper.getMainLooper())
6449 // Create a runnable to update the URL edit box.
6450 val urlEditTextUpdateRunnable = Runnable {
6451 // Update the URL edit text.
6452 urlEditText.setText(currentWebView!!.url)
6454 // Disable the wide viewport if the source is being viewed.
6455 if (currentWebView!!.url!!.startsWith("view-source:"))
6456 currentWebView!!.settings.useWideViewPort = false
6459 // Update the URL edit text after 50 milliseconds, so that the WebView has enough time to navigate to the new URL.
6460 urlEditTextUpdateHandler.postDelayed(urlEditTextUpdateRunnable, 50)