2 * Copyright 2015-2024 Soren Stoutner <soren@stoutner.com>.
4 * Download cookie code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
6 * This file is part of Privacy Browser Android <https://www.stoutner.com/privacy-browser-android>.
8 * Privacy Browser Android is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
13 * Privacy Browser Android is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with Privacy Browser Android. If not, see <http://www.gnu.org/licenses/>.
22 package com.stoutner.privacybrowser.activities
24 import android.animation.ObjectAnimator
25 import android.annotation.SuppressLint
26 import android.app.DownloadManager
27 import android.app.SearchManager
28 import android.content.ActivityNotFoundException
29 import android.content.BroadcastReceiver
30 import android.content.ClipData
31 import android.content.ClipboardManager
32 import android.content.Context
33 import android.content.Intent
34 import android.content.IntentFilter
35 import android.content.SharedPreferences
36 import android.content.pm.PackageManager
37 import android.content.res.Configuration
38 import android.database.Cursor
39 import android.graphics.Bitmap
40 import android.graphics.BitmapFactory
41 import android.graphics.Typeface
42 import android.graphics.drawable.BitmapDrawable
43 import android.net.Uri
44 import android.net.http.SslError
45 import android.os.Build
46 import android.os.Bundle
47 import android.os.Environment
48 import android.os.Handler
49 import android.os.Looper
50 import android.print.PrintManager
51 import android.provider.DocumentsContract
52 import android.provider.OpenableColumns
53 import android.text.Editable
54 import android.text.TextWatcher
55 import android.text.style.ForegroundColorSpan
56 import android.util.Patterns
57 import android.util.TypedValue
58 import android.view.ContextMenu
59 import android.view.GestureDetector
60 import android.view.KeyEvent
61 import android.view.Menu
62 import android.view.MenuItem
63 import android.view.MotionEvent
64 import android.view.View
65 import android.view.ViewGroup
66 import android.view.WindowManager
67 import android.view.inputmethod.InputMethodManager
68 import android.webkit.CookieManager
69 import android.webkit.HttpAuthHandler
70 import android.webkit.ValueCallback
71 import android.webkit.SslErrorHandler
72 import android.webkit.WebChromeClient
73 import android.webkit.WebResourceRequest
74 import android.webkit.WebResourceResponse
75 import android.webkit.WebSettings
76 import android.webkit.WebStorage
77 import android.webkit.WebView
78 import android.webkit.WebViewClient
79 import android.webkit.WebViewDatabase
80 import android.widget.AdapterView
81 import android.widget.ArrayAdapter
82 import android.widget.CheckBox
83 import android.widget.EditText
84 import android.widget.FrameLayout
85 import android.widget.ImageView
86 import android.widget.LinearLayout
87 import android.widget.ListView
88 import android.widget.ProgressBar
89 import android.widget.RadioButton
90 import android.widget.RadioGroup
91 import android.widget.RelativeLayout
92 import android.widget.TextView
94 import androidx.activity.OnBackPressedCallback
95 import androidx.activity.result.contract.ActivityResultContracts
96 import androidx.appcompat.app.ActionBar
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 appBarHeight = 0
353 private var bookmarksCursor: Cursor? = null
354 private var bookmarksDatabaseHelper: BookmarksDatabaseHelper? = null
355 private var bookmarksDrawerPinned = false
356 private var bottomAppBar = false
357 private var currentWebView: NestedScrollWebView? = null
358 private var defaultBlockAllThirdPartyRequests = false
359 private var defaultCookies = false
360 private var defaultDisplayWebpageImages = true
361 private var defaultDomStorage = false
362 private var defaultEasyList = true
363 private var defaultEasyPrivacy = true
364 private var defaultFanboysAnnoyanceList = true
365 private var defaultFanboysSocialBlockingList = true
366 private var defaultFormData = false // Form data can be removed once the minimum API >= 26.
367 private var defaultProgressViewEndOffset = 0
368 private var defaultProgressViewStartOffset = 0
369 private var defaultJavaScript = false
370 private var defaultSwipeToRefresh = true
371 private var defaultUltraList = true
372 private var defaultUltraPrivacy = true
373 private var defaultWideViewport = true
374 private var displayAdditionalAppBarIcons = false
375 private var displayingFullScreenVideo = false
376 private var domainsDatabaseHelper: DomainsDatabaseHelper? = null
377 private var downloadWithExternalApp = false
378 private var fullScreenBrowsingModeEnabled = false
379 private var hideAppBar = true
380 private var inFullScreenBrowsingMode = false
381 private var incognitoModeEnabled = false
382 private var loadingNewIntent = false
383 private var navigationDrawerFirstView = true
384 private var objectAnimator = ObjectAnimator()
385 private var optionsMenu: Menu? = null
386 private var orbotStatusBroadcastReceiver: BroadcastReceiver? = null
387 private var reapplyAppSettingsOnRestart = false
388 private var reapplyDomainSettingsOnRestart = false
389 private var sanitizeAmpRedirects = false
390 private var sanitizeTrackingQueries = false
391 private var savedProxyMode: String? = null
392 private var savedNestedScrollWebViewStateArrayList: ArrayList<Bundle>? = null
393 private var savedStateArrayList: ArrayList<Bundle>? = null
394 private var savedTabPosition = 0
395 private var scrollAppBar = false
396 private var ultraPrivacy: ArrayList<List<Array<String>>>? = null
397 private var waitingForProxy = false
399 // Define the save webpage image activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
400 private val browseFileUploadActivityResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { activityResult ->
401 // Pass the file to the WebView.
402 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(activityResult.resultCode, activityResult.data))
405 // Define the save URL activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
406 private val saveUrlActivityResultLauncher = registerForActivityResult<String, Uri>(ActivityResultContracts.CreateDocument("*/*")) { fileUri ->
407 // Only save the URL if the file URI is not null, which happens if the user exited the file picker by pressing back.
408 if (fileUri != null) {
409 // Instantiate the save URL coroutine.
410 val saveUrlCoroutine = SaveUrlCoroutine()
413 saveUrlCoroutine.save(this, this, saveUrlString, fileUri, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
416 // Reset the save URL string.
420 // Define the save webpage archive activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
421 private val saveWebpageArchiveActivityResultLauncher = registerForActivityResult<String, Uri>(ActivityResultContracts.CreateDocument("multipart/related")) { fileUri ->
422 // Only save the webpage archive if the file URI is not null, which happens if the user exited the file picker by pressing back.
423 if (fileUri != null) {
424 // Initialize the file name string from the file URI last path segment.
425 var fileNameString = fileUri.lastPathSegment
427 // Query the exact file name if the API >= 26.
428 if (Build.VERSION.SDK_INT >= 26) {
429 // Get a cursor from the content resolver.
430 val contentResolverCursor = contentResolver.query(fileUri, null, null, null)!!
432 // Move to the fist row.
433 contentResolverCursor.moveToFirst()
435 // Get the file name from the cursor.
436 fileNameString = contentResolverCursor.getString(contentResolverCursor.getColumnIndexOrThrow(OpenableColumns.DISPLAY_NAME))
439 contentResolverCursor.close()
442 // Use a coroutine to save the file.
443 CoroutineScope(Dispatchers.Main).launch {
445 // Create the file on the IO thread.
446 withContext(Dispatchers.IO) {
447 // Create a temporary MHT file.
448 val temporaryMhtFile = File.createTempFile(TEMPORARY_MHT_FILE, ".mht", cacheDir)
450 // The WebView must be accessed from the main thread.
451 withContext(Dispatchers.Main) {
452 currentWebView!!.saveWebArchive(temporaryMhtFile.toString(), false) { callbackValue ->
453 if (callbackValue != null) { // The temporary MHT file was saved successfully.
455 // Create a temporary MHT file input stream.
456 val temporaryMhtFileInputStream = FileInputStream(temporaryMhtFile)
458 // Get an output stream for the save webpage file path.
459 val mhtOutputStream = contentResolver.openOutputStream(fileUri)!!
461 // Create a transfer byte array.
462 val transferByteArray = ByteArray(1024)
464 // Create an integer to track the number of bytes read.
467 // Copy the temporary MHT file input stream to the MHT output stream.
468 while (temporaryMhtFileInputStream.read(transferByteArray).also { bytesRead = it } > 0)
469 mhtOutputStream.write(transferByteArray, 0, bytesRead)
471 // Close the streams.
472 mhtOutputStream.close()
473 temporaryMhtFileInputStream.close()
475 // Display a snackbar.
476 Snackbar.make(currentWebView!!, getString(R.string.saved, fileNameString), Snackbar.LENGTH_SHORT).show()
477 } catch (exception: Exception) {
478 // Display snackbar with the exception.
479 Snackbar.make(currentWebView!!, getString(R.string.error_saving_file, fileNameString, exception), Snackbar.LENGTH_INDEFINITE).show()
481 // Delete the temporary MHT file.
482 temporaryMhtFile.delete()
484 } else { // There was an unspecified error while saving the temporary MHT file.
485 // Display a snackbar.
486 Snackbar.make(currentWebView!!, getString(R.string.error_saving_file, fileNameString, getString(R.string.unknown_error)), Snackbar.LENGTH_INDEFINITE).show()
491 } catch (ioException: IOException) {
492 // Display a snackbar with the IO exception.
493 Snackbar.make(currentWebView!!, getString(R.string.error_saving_file, fileNameString, ioException), Snackbar.LENGTH_INDEFINITE).show()
499 // Define the save webpage image activity result launcher. It must be defined before `onCreate()` is run or the app will crash.
500 private val saveWebpageImageActivityResultLauncher = registerForActivityResult<String, Uri>(ActivityResultContracts.CreateDocument("image/png")) { fileUri ->
501 // Only save the webpage image if the file URI is not null, which happens if the user exited the file picker by pressing back.
502 if (fileUri != null) {
503 // Instantiate the save webpage image coroutine.
504 val saveWebpageImageCoroutine = SaveWebpageImageCoroutine()
506 // Save the webpage image.
507 saveWebpageImageCoroutine.save(this, fileUri, currentWebView!!)
511 override fun onCreate(savedInstanceState: Bundle?) {
512 // Run the default commands.
513 super.onCreate(savedInstanceState)
515 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
516 PreferenceManager.setDefaultValues(this, R.xml.preferences, false)
518 // Get a handle for the shared preferences.
519 sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
521 // Get the preferences.
522 val appTheme = sharedPreferences.getString(getString(R.string.app_theme_key), getString(R.string.app_theme_default_value))
523 val allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false)
524 bottomAppBar = sharedPreferences.getBoolean(getString(R.string.bottom_app_bar_key), false)
525 displayAdditionalAppBarIcons = sharedPreferences.getBoolean(getString(R.string.display_additional_app_bar_icons_key), false)
526 val displayUnderCutouts = sharedPreferences.getBoolean(getString(R.string.display_under_cutouts_key), false)
528 // 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.
529 if (displayUnderCutouts) {
530 if (Build.VERSION.SDK_INT >= 30)
531 window.attributes.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS
532 else if (Build.VERSION.SDK_INT >= 28)
533 window.attributes.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
536 // Get the entry values string arrays.
537 val appThemeEntryValuesStringArray = resources.getStringArray(R.array.app_theme_entry_values)
539 // Get the current theme status.
540 val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
542 // 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.
543 if (appTheme == appThemeEntryValuesStringArray[1]) { // The light theme is selected.
544 // Apply the light theme.
545 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
546 } else if (appTheme == appThemeEntryValuesStringArray[2]) { // The dark theme is selected.
547 // Apply the dark theme.
548 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
549 } else { // The system default theme is selected.
550 if (Build.VERSION.SDK_INT >= 28) { // The system default theme is supported.
551 // Follow the system default theme.
552 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
553 } else { // The system default theme is not supported.
554 // Follow the battery saver mode.
555 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY)
559 // Do not continue if the app theme is different than the OS theme. The app always initially starts in the OS theme.
560 // 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.
561 // 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.
562 // See https://redmine.stoutner.com/issues/952.
563 if ((appTheme == appThemeEntryValuesStringArray[0]) || // The system default theme is used.
564 ((appTheme == appThemeEntryValuesStringArray[1]) && (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO)) || // The app is running in day theme as desired.
565 ((appTheme == appThemeEntryValuesStringArray[2]) && (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES))) { // The app is running in night theme as desired.
567 // Disable screenshots if not allowed.
568 if (!allowScreenshots) {
569 window.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
572 // Check to see if the activity has been restarted.
573 if (savedInstanceState != null) {
574 // Store the saved instance state variables. The deprecated `getParcelableArrayList` can be upgraded once the minimum API >= 33.
575 bookmarksDrawerPinned = savedInstanceState.getBoolean(BOOKMARKS_DRAWER_PINNED)
576 @Suppress("DEPRECATION")
577 savedStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_STATE_ARRAY_LIST)
578 @Suppress("DEPRECATION")
579 savedNestedScrollWebViewStateArrayList = savedInstanceState.getParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST)
580 savedTabPosition = savedInstanceState.getInt(SAVED_TAB_POSITION)
581 savedProxyMode = savedInstanceState.getString(PROXY_MODE)
584 // 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.
585 WebView.enableSlowWholeDocumentDraw()
587 // Set the content view according to the position of the app bar.
589 setContentView(R.layout.main_framelayout_bottom_appbar)
591 setContentView(R.layout.main_framelayout_top_appbar)
593 // Get handles for the views.
594 rootFrameLayout = findViewById(R.id.root_framelayout)
595 drawerLayout = findViewById(R.id.drawerlayout)
596 coordinatorLayout = findViewById(R.id.coordinatorlayout)
597 appBarLayout = findViewById(R.id.appbar_layout)
598 toolbar = findViewById(R.id.toolbar)
599 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout)
600 findOnPageEditText = findViewById(R.id.find_on_page_edittext)
601 findOnPageCountTextView = findViewById(R.id.find_on_page_count_textview)
602 tabsLinearLayout = findViewById(R.id.tabs_linearlayout)
603 tabLayout = findViewById(R.id.tablayout)
604 swipeRefreshLayout = findViewById(R.id.swiperefreshlayout)
605 webViewViewPager2 = findViewById(R.id.webview_viewpager2)
606 navigationView = findViewById(R.id.navigationview)
607 bookmarksListView = findViewById(R.id.bookmarks_drawer_listview)
608 bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview)
609 bookmarksDrawerPinnedImageView = findViewById(R.id.bookmarks_drawer_pinned_imageview)
610 fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout)
612 // Get a handle for the navigation menu.
613 val navigationMenu = navigationView.menu
615 // Get handles for the navigation menu items.
616 navigationBackMenuItem = navigationMenu.findItem(R.id.back)
617 navigationForwardMenuItem = navigationMenu.findItem(R.id.forward)
618 navigationScrollToBottomMenuItem = navigationMenu.findItem(R.id.scroll_to_bottom)
619 navigationHistoryMenuItem = navigationMenu.findItem(R.id.history)
620 navigationRequestsMenuItem = navigationMenu.findItem(R.id.requests)
622 // Listen for touches on the navigation menu.
623 navigationView.setNavigationItemSelectedListener(this)
625 // Set the support action bar.
626 setSupportActionBar(toolbar)
628 // Get a handle for the app bar.
629 appBar = supportActionBar!!
631 // Set the custom app bar layout, which shows the URL text bar.
632 appBar.setCustomView(R.layout.url_app_bar)
634 // Display the custom app bar layout.
635 appBar.displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM
637 // Get handles for the views in the URL app bar.
638 urlRelativeLayout = findViewById(R.id.url_relativelayout)
639 urlEditText = findViewById(R.id.url_edittext)
641 // Initially disable the sliding drawers. They will be enabled once the filter lists are loaded.
642 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
644 // Initially hide the user interface so that only the filter list loading screen is shown (if reloading).
645 drawerLayout.visibility = View.GONE
647 // Initialize the WebView state adapter.
648 webViewStateAdapter = WebViewStateAdapter(this, bottomAppBar)
650 // Set the WebView pager adapter.
651 webViewViewPager2.adapter = webViewStateAdapter
653 // Store up to 100 tabs in memory.
654 webViewViewPager2.offscreenPageLimit = 100
656 // Disable swiping between pages in the view pager.
657 webViewViewPager2.isUserInputEnabled = false
659 // Get a handle for the cookie manager.
660 cookieManager = CookieManager.getInstance()
662 // Instantiate the helpers.
663 bookmarksDatabaseHelper = BookmarksDatabaseHelper(this)
664 domainsDatabaseHelper = DomainsDatabaseHelper(this)
665 proxyHelper = ProxyHelper()
667 // Update the bookmarks drawer pinned image view.
668 updateBookmarksDrawerPinnedImageView()
670 // Initialize the app.
673 // Apply the app settings from the shared preferences.
676 // Control what the system back command does.
677 val onBackPressedCallback: OnBackPressedCallback = object : OnBackPressedCallback(true) {
678 override fun handleOnBackPressed() {
679 // Process the different back options.
680 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
681 // Close the navigation drawer.
682 drawerLayout.closeDrawer(GravityCompat.START)
683 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)) { // The bookmarks drawer is open.
684 // close the bookmarks drawer.
685 drawerLayout.closeDrawer(GravityCompat.END)
686 } else if (displayingFullScreenVideo) { // A full screen video is shown.
687 // Exit the full screen video.
688 exitFullScreenVideo()
689 // It shouldn't be possible for the currentWebView to be null, but crash logs indicate it sometimes happens.
690 } else if (currentWebView != null && currentWebView!!.canGoBack()) { // There is at least one item in the current WebView history.
691 // Get the current web back forward list.
692 val webBackForwardList = currentWebView!!.copyBackForwardList()
694 // Get the previous entry data.
695 val previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex - 1).url
696 val previousFavoriteIcon = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex - 1).favicon
698 // Apply the domain settings.
699 applyDomainSettings(currentWebView!!, previousUrl, resetTab = false, reloadWebsite = false, loadUrl = false)
701 // Get the current tab.
702 val tab = tabLayout.getTabAt(tabLayout.selectedTabPosition)!!
704 // Get the custom view from the tab.
705 val tabView = tab.customView!!
707 // Get the favorite icon image view from the tab.
708 val tabFavoriteIconImageView = tabView.findViewById<ImageView>(R.id.favorite_icon_imageview)
710 // Set the previous favorite icon if it isn't null.
711 if (previousFavoriteIcon != null)
712 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(previousFavoriteIcon, 64, 64, true))
715 currentWebView!!.goBack()
717 // Update the URL edit text after a delay.
718 updateUrlEditTextAfterDelay()
719 } else { // Close the current tab.
720 // A view is required because the method is also called by an XML `onClick`.
726 // Register the on back pressed callback.
727 onBackPressedDispatcher.addCallback(this, onBackPressedCallback)
729 // Instantiate the populate filter lists coroutine.
730 val populateFilterListsCoroutine = PopulateFilterListsCoroutine(this)
732 // Populate the filter lists.
733 populateFilterListsCoroutine.populateFilterLists(this)
737 override fun onNewIntent(intent: Intent) {
738 // Run the default commands.
739 super.onNewIntent(intent)
741 // Close the navigation drawer if it is open.
742 if (drawerLayout.isDrawerVisible(GravityCompat.START))
743 drawerLayout.closeDrawer(GravityCompat.START)
745 // Close the bookmarks drawer if it is open.
746 if (drawerLayout.isDrawerVisible(GravityCompat.END))
747 drawerLayout.closeDrawer(GravityCompat.END)
749 // Get the information from the intent.
750 val intentAction = intent.action
751 val intentUriData = intent.data
752 val intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT)
754 // Determine if this is a web search.
755 val isWebSearch = (intentAction != null) && (intentAction == Intent.ACTION_WEB_SEARCH)
757 // Check to see if the app is being restarted from a saved state.
758 if (ultraPrivacy != null) { // The activity is not being restarted from a saved state.
759 // 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.
760 if ((intentUriData != null) || (intentStringExtra != null) || isWebSearch) {
761 // Exit the full screen video if it is displayed.
762 if (displayingFullScreenVideo) {
763 // Exit full screen video mode.
764 exitFullScreenVideo()
766 // Reload the current WebView. Otherwise, it can display entirely black.
767 currentWebView!!.reload()
771 val url = if (isWebSearch) { // The intent is a web search.
772 // Sanitize the search input and convert it to a search.
773 val encodedSearchString = try {
774 URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8")
775 } catch (exception: UnsupportedEncodingException) {
779 // Add the base search URL.
780 searchURL + encodedSearchString
781 } else { // The intent contains a URL in either the data or an extra.
782 intentUriData?.toString() ?: intentStringExtra
785 // Add a new tab if specified in the preferences.
786 if (sharedPreferences.getBoolean(getString(R.string.open_intents_in_new_tab_key), true)) { // Load the URL in a new tab.
787 // Set the loading new intent flag.
788 loadingNewIntent = true
791 addNewPage(url!!, adjacent = false, moveToTab = true)
792 } else { // Load the URL in the current tab.
794 loadUrl(currentWebView!!, url!!)
797 } else { // The app has been restarted.
798 // Replace the intent that started the app with this one. This will load the tab after the others have been restored.
803 public override fun onRestart() {
804 // Run the default commands.
807 // Apply the app settings if returning from the Settings activity.
808 if (reapplyAppSettingsOnRestart) {
809 // Reset the reapply app settings on restart flag.
810 reapplyAppSettingsOnRestart = false
812 // Apply the app settings.
816 // Apply the domain settings if returning from the settings or domains activity.
817 if (reapplyDomainSettingsOnRestart) {
818 // Reset the reapply domain settings on restart flag.
819 reapplyDomainSettingsOnRestart = false
821 // Update the domains settings set.
822 updateDomainsSettingsSet()
824 // Reapply the domain settings for each tab.
825 for (i in 0 until webViewStateAdapter!!.itemCount) {
826 // Get the WebView tab fragment.
827 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
829 // Get the fragment view.
830 val fragmentView = webViewTabFragment.view
832 // Only reload the WebViews if they exist.
833 if (fragmentView != null) {
834 // Get the nested scroll WebView from the tab fragment.
835 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
837 // Reset the current domain name so the domain settings will be reapplied.
838 nestedScrollWebView.currentDomainName = ""
840 // Reapply the domain settings if the URL is not null, which happens for empty tabs when returning from settings.
841 if (nestedScrollWebView.url != null)
842 applyDomainSettings(nestedScrollWebView, nestedScrollWebView.url, resetTab = false, reloadWebsite = true, loadUrl = false)
847 // Update the bookmarks drawer if returning from the Bookmarks activity.
848 if (restartFromBookmarksActivity) {
849 // Reset the restart from bookmarks activity flag.
850 restartFromBookmarksActivity = false
852 // Close the bookmarks drawer.
853 drawerLayout.closeDrawer(GravityCompat.END)
855 // Reload the bookmarks drawer.
856 loadBookmarksFolder()
859 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
860 updatePrivacyIcons(true)
863 // `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.
864 public override fun onStart() {
865 // Run the default commands.
868 // 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.
869 if (webViewStateAdapter != null) {
870 for (i in 0 until webViewStateAdapter!!.itemCount) {
871 // Get the WebView tab fragment.
872 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
874 // Get the fragment view.
875 val fragmentView = webViewTabFragment.view
877 // Only resume the WebViews if they exist (they won't when the app is first created).
878 if (fragmentView != null) {
879 // Get the nested scroll WebView from the tab fragment.
880 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
882 // Resume the nested scroll WebView.
883 nestedScrollWebView.onResume()
888 // Resume the nested scroll WebView JavaScript timers. This is a global command that resumes JavaScript timers on all WebViews.
889 if (currentWebView != null)
890 currentWebView!!.resumeTimers()
892 // Reapply the proxy settings if the system is using a proxy. This redisplays the appropriate alert dialog.
893 if (proxyMode != ProxyHelper.NONE)
896 // Reapply any system UI flags.
897 if (displayingFullScreenVideo || inFullScreenBrowsingMode) { // The system is displaying a website or a video in full screen mode.
898 /* Hide the system bars.
899 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
900 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
901 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
902 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
905 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
906 @Suppress("DEPRECATION")
907 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
910 // Show any pending dialogs.
911 for (i in pendingDialogsArrayList.indices) {
912 // Get the pending dialog from the array list.
913 val (dialogFragment, tag) = pendingDialogsArrayList[i]
915 // Show the pending dialog.
916 dialogFragment.show(supportFragmentManager, tag)
919 // Clear the pending dialogs array list.
920 pendingDialogsArrayList.clear()
923 public override fun onSaveInstanceState(savedInstanceState: Bundle) {
924 // Run the default commands.
925 super.onSaveInstanceState(savedInstanceState)
927 // 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.
928 if (webViewStateAdapter != null) {
929 // Initialize the saved state array lists.
930 savedStateArrayList = ArrayList<Bundle>()
931 savedNestedScrollWebViewStateArrayList = ArrayList<Bundle>()
933 // Get the URLs from each tab.
934 for (i in 0 until webViewStateAdapter!!.itemCount) {
935 // Get the WebView tab fragment.
936 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
938 // Get the fragment view.
939 val fragmentView = webViewTabFragment.view
941 // Save the fragment state if it is not null.
942 if (fragmentView != null) {
943 // Get the nested scroll WebView from the tab fragment.
944 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
946 // Create the saved state bundle.
947 val savedStateBundle = Bundle()
949 // Get the current states.
950 nestedScrollWebView.saveState(savedStateBundle)
951 val savedNestedScrollWebViewStateBundle = nestedScrollWebView.saveNestedScrollWebViewState()
953 // Store the saved states in the array lists.
954 savedStateArrayList!!.add(savedStateBundle)
955 savedNestedScrollWebViewStateArrayList!!.add(savedNestedScrollWebViewStateBundle)
959 // Get the current tab position.
960 val currentTabPosition = tabLayout.selectedTabPosition
962 // Store the saved states in the bundle.
963 savedInstanceState.putBoolean(BOOKMARKS_DRAWER_PINNED, bookmarksDrawerPinned)
964 savedInstanceState.putString(PROXY_MODE, proxyMode)
965 savedInstanceState.putParcelableArrayList(SAVED_NESTED_SCROLL_WEBVIEW_STATE_ARRAY_LIST, savedNestedScrollWebViewStateArrayList)
966 savedInstanceState.putParcelableArrayList(SAVED_STATE_ARRAY_LIST, savedStateArrayList)
967 savedInstanceState.putInt(SAVED_TAB_POSITION, currentTabPosition)
971 // `onStop()` runs after `onPause()`. It is used instead of `onPause()` so the commands are not called every time the screen is partially hidden.
972 public override fun onStop() {
973 // Run the default commands.
976 // 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.
977 if (webViewStateAdapter != null) {
978 // Pause each web view.
979 for (i in 0 until webViewStateAdapter!!.itemCount) {
980 // Get the WebView tab fragment.
981 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
983 // Get the fragment view.
984 val fragmentView = webViewTabFragment.view
986 // Only pause the WebViews if they exist (they won't when the app is first created).
987 if (fragmentView != null) {
988 // Get the nested scroll WebView from the tab fragment.
989 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
991 // Pause the nested scroll WebView.
992 nestedScrollWebView.onPause()
997 // Pause the WebView JavaScript timers. This is a global command that pauses JavaScript on all WebViews.
998 if (currentWebView != null)
999 currentWebView!!.pauseTimers()
1002 public override fun onDestroy() {
1003 // Unregister the orbot status broadcast receiver if it exists.
1004 if (orbotStatusBroadcastReceiver != null) {
1005 unregisterReceiver(orbotStatusBroadcastReceiver)
1008 // Close the bookmarks cursor if it exists.
1009 bookmarksCursor?.close()
1011 // Close the databases if they exist.
1012 bookmarksDatabaseHelper?.close()
1013 domainsDatabaseHelper?.close()
1015 // Run the default commands.
1019 override fun onConfigurationChanged(newConfig: Configuration) {
1020 // Run the default commands.
1021 super.onConfigurationChanged(newConfig)
1023 // Reset the navigation drawer first view flag.
1024 navigationDrawerFirstView = true
1026 // Get the current page.
1027 val currentPage = webViewViewPager2.currentItem
1029 // Toggle the pages if there is more than one so that the view pager will recalculate their size.
1030 if (currentPage > 0) {
1031 // Switch to the previous page after 25 milliseconds.
1032 webViewViewPager2.postDelayed ({ webViewViewPager2.currentItem = (currentPage - 1) }, 25)
1034 // Switch back to the current page after the view pager has quiesced (which we are deciding should be 25 milliseconds).
1035 webViewViewPager2.postDelayed ({ webViewViewPager2.currentItem = currentPage }, 25)
1038 // Scroll to the current tab position after 25 milliseconds.
1039 tabLayout.postDelayed ({ tabLayout.setScrollPosition(currentPage, 0F, false, false) }, 25)
1042 override fun onCreateOptionsMenu(menu: Menu): Boolean {
1043 // Inflate the menu. This adds items to the app bar if it is present.
1044 menuInflater.inflate(R.menu.webview_options_menu, menu)
1046 // Get handles for the menu items.
1047 optionsPrivacyMenuItem = menu.findItem(R.id.javascript)
1048 optionsRefreshMenuItem = menu.findItem(R.id.refresh)
1049 val optionsBookmarksMenuItem = menu.findItem(R.id.bookmarks)
1050 optionsCookiesMenuItem = menu.findItem(R.id.cookies)
1051 optionsDomStorageMenuItem = menu.findItem(R.id.dom_storage)
1052 optionsSaveFormDataMenuItem = menu.findItem(R.id.save_form_data) // Form data can be removed once the minimum API >= 26.
1053 optionsClearDataMenuItem = menu.findItem(R.id.clear_data)
1054 optionsClearCookiesMenuItem = menu.findItem(R.id.clear_cookies)
1055 optionsClearDomStorageMenuItem = menu.findItem(R.id.clear_dom_storage)
1056 optionsClearFormDataMenuItem = menu.findItem(R.id.clear_form_data) // Form data can be removed once the minimum API >= 26.
1057 optionsEasyListMenuItem = menu.findItem(R.id.easylist)
1058 optionsEasyPrivacyMenuItem = menu.findItem(R.id.easyprivacy)
1059 optionsFanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list)
1060 optionsFanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list)
1061 optionsFilterListsMenuItem = menu.findItem(R.id.filterlists)
1062 optionsUltraListMenuItem = menu.findItem(R.id.ultralist)
1063 optionsUltraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy)
1064 optionsBlockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests)
1065 optionsProxyMenuItem = menu.findItem(R.id.proxy)
1066 optionsProxyNoneMenuItem = menu.findItem(R.id.proxy_none)
1067 optionsProxyTorMenuItem = menu.findItem(R.id.proxy_tor)
1068 optionsProxyI2pMenuItem = menu.findItem(R.id.proxy_i2p)
1069 optionsProxyCustomMenuItem = menu.findItem(R.id.proxy_custom)
1070 optionsUserAgentMenuItem = menu.findItem(R.id.user_agent)
1071 optionsUserAgentPrivacyBrowserMenuItem = menu.findItem(R.id.user_agent_privacy_browser)
1072 optionsUserAgentWebViewDefaultMenuItem = menu.findItem(R.id.user_agent_webview_default)
1073 optionsUserAgentFirefoxOnAndroidMenuItem = menu.findItem(R.id.user_agent_firefox_on_android)
1074 optionsUserAgentChromeOnAndroidMenuItem = menu.findItem(R.id.user_agent_chrome_on_android)
1075 optionsUserAgentSafariOnIosMenuItem = menu.findItem(R.id.user_agent_safari_on_ios)
1076 optionsUserAgentFirefoxOnLinuxMenuItem = menu.findItem(R.id.user_agent_firefox_on_linux)
1077 optionsUserAgentChromiumOnLinuxMenuItem = menu.findItem(R.id.user_agent_chromium_on_linux)
1078 optionsUserAgentFirefoxOnWindowsMenuItem = menu.findItem(R.id.user_agent_firefox_on_windows)
1079 optionsUserAgentChromeOnWindowsMenuItem = menu.findItem(R.id.user_agent_chrome_on_windows)
1080 optionsUserAgentEdgeOnWindowsMenuItem = menu.findItem(R.id.user_agent_edge_on_windows)
1081 optionsUserAgentSafariOnMacosMenuItem = menu.findItem(R.id.user_agent_safari_on_macos)
1082 optionsUserAgentCustomMenuItem = menu.findItem(R.id.user_agent_custom)
1083 optionsSwipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh)
1084 optionsWideViewportMenuItem = menu.findItem(R.id.wide_viewport)
1085 optionsDisplayImagesMenuItem = menu.findItem(R.id.display_images)
1086 optionsDarkWebViewMenuItem = menu.findItem(R.id.dark_webview)
1087 optionsFontSizeMenuItem = menu.findItem(R.id.font_size)
1088 optionsViewSourceMenuItem = menu.findItem(R.id.view_source)
1089 optionsAddOrEditDomainMenuItem = menu.findItem(R.id.add_or_edit_domain)
1091 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1092 updatePrivacyIcons(false)
1094 // Only display the form data menu items if the API < 26.
1095 optionsSaveFormDataMenuItem.isVisible = Build.VERSION.SDK_INT < 26
1096 optionsClearFormDataMenuItem.isVisible = Build.VERSION.SDK_INT < 26
1098 // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
1099 optionsClearFormDataMenuItem.isEnabled = Build.VERSION.SDK_INT < 26
1101 // 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.
1102 if (displayAdditionalAppBarIcons) { // Display the additional icons.
1103 optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
1104 optionsBookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM)
1105 optionsCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM)
1106 } else { //Do not display the additional icons.
1107 optionsRefreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER)
1108 optionsBookmarksMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER)
1109 optionsCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER)
1112 // Replace `Refresh` with `Stop` if a URL is already loading.
1113 if ((currentWebView != null) && (currentWebView!!.progress != 100)) {
1115 optionsRefreshMenuItem.setTitle(R.string.stop)
1117 // 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.
1118 if (displayAdditionalAppBarIcons)
1119 optionsRefreshMenuItem.setIcon(R.drawable.close_blue)
1122 // Store a handle for the options menu.
1129 override fun onPrepareOptionsMenu(menu: Menu): Boolean {
1130 // Initialize the current user agent string and the font size.
1131 var currentUserAgent = getString(R.string.user_agent_privacy_browser)
1134 // 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.
1135 if (currentWebView != null) {
1136 // Set the add or edit domain text.
1137 if (currentWebView!!.domainSettingsApplied)
1138 optionsAddOrEditDomainMenuItem.setTitle(R.string.edit_domain_settings)
1140 optionsAddOrEditDomainMenuItem.setTitle(R.string.add_domain_settings)
1142 // Get the current user agent from the WebView.
1143 currentUserAgent = currentWebView!!.settings.userAgentString
1145 // Get the current font size from the the WebView.
1146 fontSize = currentWebView!!.settings.textZoom
1148 // Set the status of the menu item checkboxes.
1149 optionsDomStorageMenuItem.isChecked = currentWebView!!.settings.domStorageEnabled
1150 @Suppress("DEPRECATION")
1151 optionsSaveFormDataMenuItem.isChecked = currentWebView!!.settings.saveFormData // Form data can be removed once the minimum API >= 26.
1152 optionsEasyListMenuItem.isChecked = currentWebView!!.easyListEnabled
1153 optionsEasyPrivacyMenuItem.isChecked = currentWebView!!.easyPrivacyEnabled
1154 optionsFanboysAnnoyanceListMenuItem.isChecked = currentWebView!!.fanboysAnnoyanceListEnabled
1155 optionsFanboysSocialBlockingListMenuItem.isChecked = currentWebView!!.fanboysSocialBlockingListEnabled
1156 optionsUltraListMenuItem.isChecked = currentWebView!!.ultraListEnabled
1157 optionsUltraPrivacyMenuItem.isChecked = currentWebView!!.ultraPrivacyEnabled
1158 optionsBlockAllThirdPartyRequestsMenuItem.isChecked = currentWebView!!.blockAllThirdPartyRequests
1159 optionsSwipeToRefreshMenuItem.isChecked = currentWebView!!.swipeToRefresh
1160 optionsWideViewportMenuItem.isChecked = currentWebView!!.settings.useWideViewPort
1161 optionsDisplayImagesMenuItem.isChecked = currentWebView!!.settings.loadsImagesAutomatically
1163 // Set the display names for the filter lists with the number of blocked requests.
1164 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + currentWebView!!.getRequestsCount(BLOCKED_REQUESTS)
1165 optionsEasyListMenuItem.title = currentWebView!!.getRequestsCount(EASYLIST).toString() + " - " + getString(R.string.easylist)
1166 optionsEasyPrivacyMenuItem.title = currentWebView!!.getRequestsCount(EASYPRIVACY).toString() + " - " + getString(R.string.easyprivacy)
1167 optionsFanboysAnnoyanceListMenuItem.title = currentWebView!!.getRequestsCount(FANBOYS_ANNOYANCE_LIST).toString() + " - " + getString(R.string.fanboys_annoyance_list)
1168 optionsFanboysSocialBlockingListMenuItem.title = currentWebView!!.getRequestsCount(FANBOYS_SOCIAL_BLOCKING_LIST).toString() + " - " + getString(R.string.fanboys_social_blocking_list)
1169 optionsUltraListMenuItem.title = currentWebView!!.getRequestsCount(com.stoutner.privacybrowser.views.ULTRALIST).toString() + " - " + getString(R.string.ultralist)
1170 optionsUltraPrivacyMenuItem.title = currentWebView!!.getRequestsCount(ULTRAPRIVACY).toString() + " - " + getString(R.string.ultraprivacy)
1171 optionsBlockAllThirdPartyRequestsMenuItem.title = currentWebView!!.getRequestsCount(THIRD_PARTY_REQUESTS).toString() + " - " + getString(R.string.block_all_third_party_requests)
1173 // Enable DOM Storage if JavaScript is enabled.
1174 optionsDomStorageMenuItem.isEnabled = currentWebView!!.settings.javaScriptEnabled
1176 // Get the current theme status.
1177 val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
1179 // Enable dark WebView if night mode is enabled.
1180 optionsDarkWebViewMenuItem.isEnabled = (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES)
1182 // Set the checkbox status for dark WebView if algorithmic darkening is supported.
1183 if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING))
1184 optionsDarkWebViewMenuItem.isChecked = WebSettingsCompat.isAlgorithmicDarkeningAllowed(currentWebView!!.settings)
1186 // Set the view source title according to the current URL.
1187 if (currentWebView!!.currentUrl.startsWith("view-source:"))
1188 optionsViewSourceMenuItem.title = getString(R.string.view_rendered_website)
1190 optionsViewSourceMenuItem.title = getString(R.string.view_source)
1193 // Set the cookies menu item checked status.
1194 optionsCookiesMenuItem.isChecked = cookieManager.acceptCookie()
1196 // Enable Clear Cookies if there are any.
1197 optionsClearCookiesMenuItem.isEnabled = cookieManager.hasCookies()
1199 // 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`.
1200 val privateDataDirectoryString = applicationInfo.dataDir
1202 // Get the storage directories.
1203 val localStorageDirectory = File("$privateDataDirectoryString/app_webview/Local Storage/")
1204 val indexedDBDirectory = File("$privateDataDirectoryString/app_webview/IndexedDB")
1206 // Initialize the number of files counters.
1207 var localStorageDirectoryNumberOfFiles = 0
1208 var indexedDBDirectoryNumberOfFiles = 0
1210 // 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.
1211 if (localStorageDirectory.exists())
1212 localStorageDirectoryNumberOfFiles = (localStorageDirectory.list())?.size ?: 0
1214 // Get a count of the number of files in the IndexedDB directory. The list can be null, in which case a `0` is returned.
1215 if (indexedDBDirectory.exists())
1216 indexedDBDirectoryNumberOfFiles = (indexedDBDirectory.list())?.size ?: 0
1218 // Enable Clear DOM Storage if there is any.
1219 optionsClearDomStorageMenuItem.isEnabled = localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0
1221 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
1222 if (Build.VERSION.SDK_INT < 26) {
1223 // Get the WebView database.
1224 val webViewDatabase = WebViewDatabase.getInstance(this)
1226 // Enable the clear form data menu item if there is anything to clear.
1227 @Suppress("DEPRECATION")
1228 optionsClearFormDataMenuItem.isEnabled = webViewDatabase.hasFormData()
1231 // Enable Clear Data if any of the submenu items are enabled.
1232 optionsClearDataMenuItem.isEnabled = (optionsClearCookiesMenuItem.isEnabled || optionsClearDomStorageMenuItem.isEnabled || optionsClearFormDataMenuItem.isEnabled)
1234 // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
1235 optionsFanboysSocialBlockingListMenuItem.isEnabled = !optionsFanboysAnnoyanceListMenuItem.isChecked
1237 // Set the proxy title and check the applied proxy.
1239 ProxyHelper.NONE -> {
1240 // Set the proxy title.
1241 optionsProxyMenuItem.title = getString(R.string.proxy) + " - " + getString(R.string.proxy_none)
1243 // Check the proxy None radio button.
1244 optionsProxyNoneMenuItem.isChecked = true
1247 ProxyHelper.TOR -> {
1248 // Set the proxy title.
1249 optionsProxyMenuItem.title = getString(R.string.proxy) + " - " + getString(R.string.proxy_tor)
1251 // Check the proxy Tor radio button.
1252 optionsProxyTorMenuItem.isChecked = true
1255 ProxyHelper.I2P -> {
1256 // Set the proxy title.
1257 optionsProxyMenuItem.title = getString(R.string.proxy) + " - " + getString(R.string.proxy_i2p)
1259 // Check the proxy I2P radio button.
1260 optionsProxyI2pMenuItem.isChecked = true
1263 ProxyHelper.CUSTOM -> {
1264 // Set the proxy title.
1265 optionsProxyMenuItem.title = getString(R.string.proxy) + " - " + getString(R.string.proxy_custom)
1267 // Check the proxy Custom radio button.
1268 optionsProxyCustomMenuItem.isChecked = true
1272 // Select the current user agent menu item.
1273 when (currentUserAgent) {
1274 resources.getStringArray(R.array.user_agent_data)[0] -> { // Privacy Browser.
1275 // Update the user agent menu item title.
1276 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_privacy_browser)
1278 // Select the Privacy Browser radio box.
1279 optionsUserAgentPrivacyBrowserMenuItem.isChecked = true
1282 webViewDefaultUserAgent -> { // WebView Default.
1283 // Update the user agent menu item title.
1284 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_webview_default)
1286 // Select the WebView Default radio box.
1287 optionsUserAgentWebViewDefaultMenuItem.isChecked = true
1290 resources.getStringArray(R.array.user_agent_data)[2] -> { // Firefox on Android.
1291 // Update the user agent menu item title.
1292 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_android)
1294 // Select the Firefox on Android radio box.
1295 optionsUserAgentFirefoxOnAndroidMenuItem.isChecked = true
1298 resources.getStringArray(R.array.user_agent_data)[3] -> { // Chrome on Android.
1299 // Update the user agent menu item title.
1300 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_android)
1302 // Select the Chrome on Android radio box.
1303 optionsUserAgentChromeOnAndroidMenuItem.isChecked = true
1306 resources.getStringArray(R.array.user_agent_data)[4] -> { // Safari on iOS.
1307 // Update the user agent menu item title.
1308 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_ios)
1310 // Select the Safari on iOS radio box.
1311 optionsUserAgentSafariOnIosMenuItem.isChecked = true
1314 resources.getStringArray(R.array.user_agent_data)[5] -> { // Firefox on Linux.
1315 // Update the user agent menu item title.
1316 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_linux)
1318 // Select the Firefox on Linux radio box.
1319 optionsUserAgentFirefoxOnLinuxMenuItem.isChecked = true
1322 resources.getStringArray(R.array.user_agent_data)[6] -> { // Chromium on Linux.
1323 // Update the user agent menu item title.
1324 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chromium_on_linux)
1326 // Select the Chromium on Linux radio box.
1327 optionsUserAgentChromiumOnLinuxMenuItem.isChecked = true
1330 resources.getStringArray(R.array.user_agent_data)[7] -> { // Firefox on Windows.
1331 // Update the user agent menu item title.
1332 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_windows)
1334 // Select the Firefox on Windows radio box.
1335 optionsUserAgentFirefoxOnWindowsMenuItem.isChecked = true
1338 resources.getStringArray(R.array.user_agent_data)[8] -> { // Chrome on Windows.
1339 // Update the user agent menu item title.
1340 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_windows)
1342 // Select the Chrome on Windows radio box.
1343 optionsUserAgentChromeOnWindowsMenuItem.isChecked = true
1346 resources.getStringArray(R.array.user_agent_data)[9] -> { // Edge on Windows.
1347 // Update the user agent menu item title.
1348 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_edge_on_windows)
1350 // Select the Edge on Windows radio box.
1351 optionsUserAgentEdgeOnWindowsMenuItem.isChecked = true
1354 resources.getStringArray(R.array.user_agent_data)[10] -> { // Safari on macOS.
1355 // Update the user agent menu item title.
1356 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_macos)
1358 // Select the Safari on macOS radio box.
1359 optionsUserAgentSafariOnMacosMenuItem.isChecked = true
1362 else -> { // Custom user agent.
1363 // Update the user agent menu item title.
1364 optionsUserAgentMenuItem.title = getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_custom)
1366 // Select the Custom radio box.
1367 optionsUserAgentCustomMenuItem.isChecked = true
1371 // Set the font size title.
1372 optionsFontSizeMenuItem.title = getString(R.string.font_size) + " - " + fontSize + "%"
1374 // Run all the other default commands.
1375 super.onPrepareOptionsMenu(menu)
1377 // Display the menu.
1381 override fun onOptionsItemSelected(menuItem: MenuItem): Boolean {
1382 // Run the commands that correlate to the selected menu item.
1383 return when (menuItem.itemId) {
1384 R.id.javascript -> { // JavaScript.
1385 // Toggle the JavaScript status.
1386 currentWebView!!.settings.javaScriptEnabled = !currentWebView!!.settings.javaScriptEnabled
1388 // Update the privacy icon.
1389 updatePrivacyIcons(true)
1391 // Display a snackbar.
1392 if (currentWebView!!.settings.javaScriptEnabled) // JavaScrip is enabled.
1393 Snackbar.make(webViewViewPager2, R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show()
1394 else if (cookieManager.acceptCookie()) // JavaScript is disabled, but cookies are enabled.
1395 Snackbar.make(webViewViewPager2, R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show()
1396 else // Privacy mode.
1397 Snackbar.make(webViewViewPager2, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show()
1399 // Reload the current WebView.
1400 currentWebView!!.reload()
1402 // Consume the event.
1406 R.id.refresh -> { // Refresh.
1407 // Run the command that correlates to the current status of the menu item.
1408 if (menuItem.title == getString(R.string.refresh)) // The refresh button was pushed.
1409 currentWebView!!.reload()
1410 else // The stop button was pushed.
1411 currentWebView!!.stopLoading()
1413 // Consume the event.
1417 R.id.bookmarks -> { // Bookmarks.
1418 // Open the bookmarks drawer.
1419 drawerLayout.openDrawer(GravityCompat.END)
1421 // Consume the event.
1425 R.id.cookies -> { // Cookies.
1426 // Toggle the cookie status.
1427 cookieManager.setAcceptCookie(!cookieManager.acceptCookie())
1429 // Store the cookie status.
1430 currentWebView!!.acceptCookies = cookieManager.acceptCookie()
1432 // Update the menu checkbox.
1433 menuItem.isChecked = cookieManager.acceptCookie()
1435 // Update the privacy icon.
1436 updatePrivacyIcons(true)
1438 // Display a snackbar.
1439 if (cookieManager.acceptCookie()) // Cookies are enabled.
1440 Snackbar.make(webViewViewPager2, R.string.cookies_enabled, Snackbar.LENGTH_SHORT).show()
1441 else if (currentWebView!!.settings.javaScriptEnabled) // JavaScript is still enabled.
1442 Snackbar.make(webViewViewPager2, R.string.cookies_disabled, Snackbar.LENGTH_SHORT).show()
1443 else // Privacy mode.
1444 Snackbar.make(webViewViewPager2, R.string.privacy_mode, Snackbar.LENGTH_SHORT).show()
1446 // Reload the current WebView.
1447 currentWebView!!.reload()
1449 // Consume the event.
1453 R.id.dom_storage -> { // DOM storage.
1454 // Toggle the DOM storage status.
1455 currentWebView!!.settings.domStorageEnabled = !currentWebView!!.settings.domStorageEnabled
1457 // Update the menu checkbox.
1458 menuItem.isChecked = currentWebView!!.settings.domStorageEnabled
1460 // Update the privacy icon.
1461 updatePrivacyIcons(true)
1463 // Display a snackbar.
1464 if (currentWebView!!.settings.domStorageEnabled)
1465 Snackbar.make(webViewViewPager2, R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show()
1467 Snackbar.make(webViewViewPager2, R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show()
1469 // Reload the current WebView.
1470 currentWebView!!.reload()
1472 // Consume the event.
1476 R.id.save_form_data -> { // Form data. This can be removed once the minimum API >= 26.
1477 // Switch the status of saveFormDataEnabled.
1478 @Suppress("DEPRECATION")
1479 currentWebView!!.settings.saveFormData = !currentWebView!!.settings.saveFormData
1481 // Update the menu checkbox.
1482 @Suppress("DEPRECATION")
1483 menuItem.isChecked = currentWebView!!.settings.saveFormData
1485 // Display a snackbar.
1486 @Suppress("DEPRECATION")
1487 if (currentWebView!!.settings.saveFormData)
1488 Snackbar.make(webViewViewPager2, R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show()
1490 Snackbar.make(webViewViewPager2, R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show()
1492 // Update the privacy icon.
1493 updatePrivacyIcons(true)
1495 // Reload the current WebView.
1496 currentWebView!!.reload()
1498 // Consume the event.
1502 R.id.clear_cookies -> { // Clear cookies.
1503 // Create a snackbar.
1504 Snackbar.make(webViewViewPager2, R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1505 .setAction(R.string.undo) {} // Everything will be handled by `onDismissed()` below.
1506 .addCallback(object : Snackbar.Callback() {
1507 override fun onDismissed(snackbar: Snackbar, event: Int) {
1508 if (event != DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1509 // Delete the cookies.
1510 cookieManager.removeAllCookies(null)
1516 // Consume the event.
1520 R.id.clear_dom_storage -> { // Clear DOM storage.
1521 // Create a snackbar.
1522 Snackbar.make(webViewViewPager2, R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1523 .setAction(R.string.undo) {} // Everything will be handled by `onDismissed()` below.
1524 .addCallback(object : Snackbar.Callback() {
1525 override fun onDismissed(snackbar: Snackbar, event: Int) {
1526 if (event != DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1527 // Get a handle for the web storage.
1528 val webStorage = WebStorage.getInstance()
1530 // Delete the DOM Storage.
1531 webStorage.deleteAllData()
1533 // Initialize a handler to manually delete the DOM storage files and directories.
1534 val deleteDomStorageHandler = Handler(Looper.getMainLooper())
1536 // Setup a runnable to manually delete the DOM storage files and directories.
1537 val deleteDomStorageRunnable = Runnable {
1539 // Get a handle for the runtime.
1540 val runtime = Runtime.getRuntime()
1542 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1543 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1544 val privateDataDirectoryString = applicationInfo.dataDir
1546 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1547 val deleteLocalStorageProcess = runtime.exec(arrayOf("rm", "-rf", "$privateDataDirectoryString/app_webview/Local Storage/"))
1549 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1550 val deleteIndexProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview/IndexedDB")
1551 val deleteQuotaManagerProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/QuotaManager")
1552 val deleteQuotaManagerJournalProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/QuotaManager-journal")
1553 val deleteDatabasesProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview/databases")
1555 // Wait for the processes to finish.
1556 deleteLocalStorageProcess.waitFor()
1557 deleteIndexProcess.waitFor()
1558 deleteQuotaManagerProcess.waitFor()
1559 deleteQuotaManagerJournalProcess.waitFor()
1560 deleteDatabasesProcess.waitFor()
1561 } catch (exception: Exception) {
1562 // Do nothing if an error is thrown.
1566 // Manually delete the DOM storage files after 200 milliseconds.
1567 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200)
1573 // Consume the event.
1577 R.id.clear_form_data -> { // Clear form data. This can be remove once the minimum API >= 26.
1578 // Create a snackbar.
1579 Snackbar.make(webViewViewPager2, R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1580 .setAction(R.string.undo) {} // Everything will be handled by `onDismissed()` below.
1581 .addCallback(object : Snackbar.Callback() {
1582 override fun onDismissed(snackbar: Snackbar, event: Int) {
1583 if (event != DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1584 // Get a handle for the webView database.
1585 val webViewDatabase = WebViewDatabase.getInstance(applicationContext)
1587 // Delete the form data.
1588 @Suppress("DEPRECATION")
1589 webViewDatabase.clearFormData()
1595 // Consume the event.
1599 R.id.easylist -> { // EasyList.
1600 // Toggle the EasyList status.
1601 currentWebView!!.easyListEnabled = !currentWebView!!.easyListEnabled
1603 // Update the menu checkbox.
1604 menuItem.isChecked = currentWebView!!.easyListEnabled
1606 // Reload the current WebView.
1607 currentWebView!!.reload()
1609 // Consume the event.
1613 R.id.easyprivacy -> { // EasyPrivacy.
1614 // Toggle the EasyPrivacy status.
1615 currentWebView!!.easyPrivacyEnabled = !currentWebView!!.easyPrivacyEnabled
1617 // Update the menu checkbox.
1618 menuItem.isChecked = currentWebView!!.easyPrivacyEnabled
1620 // Reload the current WebView.
1621 currentWebView!!.reload()
1623 // Consume the event.
1627 R.id.fanboys_annoyance_list -> { // Fanboy's Annoyance List.
1628 // Toggle Fanboy's Annoyance List status.
1629 currentWebView!!.fanboysAnnoyanceListEnabled = !currentWebView!!.fanboysAnnoyanceListEnabled
1631 // Update the menu checkbox.
1632 menuItem.isChecked = currentWebView!!.fanboysAnnoyanceListEnabled
1634 // Update the status of Fanboy's Social Blocking List.
1635 optionsFanboysSocialBlockingListMenuItem.isEnabled = !currentWebView!!.fanboysAnnoyanceListEnabled
1637 // Reload the current WebView.
1638 currentWebView!!.reload()
1640 // Consume the event.
1644 R.id.fanboys_social_blocking_list -> { // Fanboy's Social Blocking List.
1645 // Toggle Fanboy's Social Blocking List status.
1646 currentWebView!!.fanboysSocialBlockingListEnabled = !currentWebView!!.fanboysSocialBlockingListEnabled
1648 // Update the menu checkbox.
1649 menuItem.isChecked = currentWebView!!.fanboysSocialBlockingListEnabled
1651 // Reload the current WebView.
1652 currentWebView!!.reload()
1654 // Consume the event.
1658 R.id.ultralist -> { // UltraList.
1659 // Toggle the UltraList status.
1660 currentWebView!!.ultraListEnabled = !currentWebView!!.ultraListEnabled
1662 // Update the menu checkbox.
1663 menuItem.isChecked = currentWebView!!.ultraListEnabled
1665 // Reload the current WebView.
1666 currentWebView!!.reload()
1668 // Consume the event.
1672 R.id.ultraprivacy -> { // UltraPrivacy.
1673 // Toggle the UltraPrivacy status.
1674 currentWebView!!.ultraPrivacyEnabled = !currentWebView!!.ultraPrivacyEnabled
1676 // Update the menu checkbox.
1677 menuItem.isChecked = currentWebView!!.ultraPrivacyEnabled
1679 // Reload the current WebView.
1680 currentWebView!!.reload()
1682 // Consume the event.
1686 R.id.block_all_third_party_requests -> { // Block all third-party requests.
1687 //Toggle the third-party requests blocker status.
1688 currentWebView!!.blockAllThirdPartyRequests = !currentWebView!!.blockAllThirdPartyRequests
1690 // Update the menu checkbox.
1691 menuItem.isChecked = currentWebView!!.blockAllThirdPartyRequests
1693 // Reload the current WebView.
1694 currentWebView!!.reload()
1696 // Consume the event.
1700 R.id.proxy_none -> { // Proxy - None.
1701 // Update the proxy mode.
1702 proxyMode = ProxyHelper.NONE
1704 // Apply the proxy mode.
1707 // Consume the event.
1711 R.id.proxy_tor -> { // Proxy - Tor.
1712 // Update the proxy mode.
1713 proxyMode = ProxyHelper.TOR
1715 // Apply the proxy mode.
1718 // Consume the event.
1722 R.id.proxy_i2p -> { // Proxy - I2P.
1723 // Update the proxy mode.
1724 proxyMode = ProxyHelper.I2P
1726 // Apply the proxy mode.
1729 // Consume the event.
1733 R.id.proxy_custom -> { // Proxy - Custom.
1734 // Update the proxy mode.
1735 proxyMode = ProxyHelper.CUSTOM
1737 // Apply the proxy mode.
1740 // Consume the event.
1744 R.id.user_agent_privacy_browser -> { // User Agent - Privacy Browser.
1745 // Update the user agent.
1746 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[0]
1748 // Reload the current WebView.
1749 currentWebView!!.reload()
1751 // Consume the event.
1755 R.id.user_agent_webview_default -> { // User Agent - WebView Default.
1756 // Update the user agent.
1757 currentWebView!!.settings.userAgentString = ""
1759 // Reload the current WebView.
1760 currentWebView!!.reload()
1762 // Consume the event.
1766 R.id.user_agent_firefox_on_android -> { // User Agent - Firefox on Android.
1767 // Update the user agent.
1768 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[2]
1770 // Reload the current WebView.
1771 currentWebView!!.reload()
1773 // Consume the event.
1777 R.id.user_agent_chrome_on_android -> { // User Agent - Chrome on Android.
1778 // Update the user agent.
1779 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[3]
1781 // Reload the current WebView.
1782 currentWebView!!.reload()
1784 // Consume the event.
1788 R.id.user_agent_safari_on_ios -> { // User Agent - Safari on iOS.
1789 // Update the user agent.
1790 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[4]
1792 // Reload the current WebView.
1793 currentWebView!!.reload()
1795 // Consume the event.
1799 R.id.user_agent_firefox_on_linux -> { // User Agent - Firefox on Linux.
1800 // Update the user agent.
1801 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[5]
1803 // Reload the current WebView.
1804 currentWebView!!.reload()
1806 // Consume the event.
1810 R.id.user_agent_chromium_on_linux -> { // User Agent - Chromium on Linux.
1811 // Update the user agent.
1812 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[6]
1814 // Reload the current WebView.
1815 currentWebView!!.reload()
1817 // Consume the event.
1821 R.id.user_agent_firefox_on_windows -> { // User Agent - Firefox on Windows.
1822 // Update the user agent.
1823 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[7]
1825 // Reload the current WebView.
1826 currentWebView!!.reload()
1828 // Consume the event.
1832 R.id.user_agent_chrome_on_windows -> { // User Agent - Chrome on Windows.
1833 // Update the user agent.
1834 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[8]
1836 // Reload the current WebView.
1837 currentWebView!!.reload()
1839 // Consume the event.
1843 R.id.user_agent_edge_on_windows -> { // User Agent - Edge on Windows.
1844 // Update the user agent.
1845 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[9]
1847 // Reload the current WebView.
1848 currentWebView!!.reload()
1850 // Consume the event.
1854 R.id.user_agent_safari_on_macos -> { // User Agent - Safari on macOS.
1855 // Update the user agent.
1856 currentWebView!!.settings.userAgentString = resources.getStringArray(R.array.user_agent_data)[10]
1858 // Reload the current WebView.
1859 currentWebView!!.reload()
1861 // Consume the event.
1865 R.id.user_agent_custom -> { // User Agent - Custom.
1866 // Update the user agent.
1867 currentWebView!!.settings.userAgentString = sharedPreferences.getString(getString(R.string.custom_user_agent_key), getString(R.string.custom_user_agent_default_value))
1869 // Reload the current WebView.
1870 currentWebView!!.reload()
1872 // Consume the event.
1876 R.id.font_size -> { // Font size.
1877 // Instantiate the font size dialog.
1878 val fontSizeDialogFragment: DialogFragment = FontSizeDialog.displayDialog(currentWebView!!.settings.textZoom)
1880 // Show the font size dialog.
1881 fontSizeDialogFragment.show(supportFragmentManager, getString(R.string.font_size))
1883 // Consume the event.
1887 R.id.swipe_to_refresh -> { // Swipe to refresh.
1888 // Toggle the stored status of swipe to refresh.
1889 currentWebView!!.swipeToRefresh = !currentWebView!!.swipeToRefresh
1891 // Update the swipe refresh layout.
1892 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.
1893 swipeRefreshLayout.isEnabled = currentWebView!!.scrollY == 0
1894 else // Swipe to refresh is disabled.
1895 swipeRefreshLayout.isEnabled = false
1897 // Consume the event.
1901 R.id.wide_viewport -> { // Wide viewport.
1902 // Toggle the viewport.
1903 currentWebView!!.settings.useWideViewPort = !currentWebView!!.settings.useWideViewPort
1905 // Consume the event.
1909 R.id.display_images -> { // Display images.
1910 // Toggle the displaying of images.
1911 if (currentWebView!!.settings.loadsImagesAutomatically) { // Images are currently loaded automatically.
1912 // Disable loading of images.
1913 currentWebView!!.settings.loadsImagesAutomatically = false
1915 // Reload the website to remove existing images.
1916 currentWebView!!.reload()
1917 } else { // Images are not currently loaded automatically.
1918 // Enable loading of images. Missing images will be loaded without the need for a reload.
1919 currentWebView!!.settings.loadsImagesAutomatically = true
1922 // Consume the event.
1926 R.id.dark_webview -> { // Dark WebView.
1927 // Toggle dark WebView if supported.
1928 if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING))
1929 WebSettingsCompat.setAlgorithmicDarkeningAllowed(currentWebView!!.settings, !WebSettingsCompat.isAlgorithmicDarkeningAllowed(currentWebView!!.settings)
1932 // Consume the event.
1936 R.id.find_on_page -> { // Find on page.
1937 // Set the minimum height of the find on page linear layout to match the toolbar.
1938 findOnPageLinearLayout.minimumHeight = toolbar.height
1940 // Hide the toolbar.
1941 toolbar.visibility = View.GONE
1943 // Show the find on page linear layout.
1944 findOnPageLinearLayout.visibility = View.VISIBLE
1946 // Display the keyboard. The app must wait 200 ms before running the command to work around a bug in Android.
1947 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1948 findOnPageEditText.postDelayed({
1949 // Set the focus on the find on page edit text.
1950 findOnPageEditText.requestFocus()
1952 // Get a handle for the input method manager.
1953 val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
1955 // Display the keyboard. `0` sets no input flags.
1956 inputMethodManager.showSoftInput(findOnPageEditText, 0)
1959 // Consume the event.
1963 R.id.print -> { // Print.
1964 // Get a print manager instance.
1965 val printManager = (getSystemService(PRINT_SERVICE) as PrintManager)
1967 // Create a print document adapter from the current WebView.
1968 val printDocumentAdapter = currentWebView!!.createPrintDocumentAdapter(getString(R.string.print))
1970 // Print the document.
1971 printManager.print(getString(R.string.privacy_browser_webpage), printDocumentAdapter, null)
1973 // Consume the event.
1977 R.id.save_url -> { // Save URL.
1978 // Check the download preference.
1979 if (downloadWithExternalApp) // Download with an external app.
1980 saveWithExternalApp(currentWebView!!.currentUrl)
1981 else // Handle the download inside of Privacy Browser. The dialog will be displayed once the file size and the content disposition have been acquired.
1982 PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, currentWebView!!.currentUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
1984 // Consume the event.
1988 R.id.save_archive -> {
1989 // Open the file picker with a default file name built from the website title.
1990 saveWebpageArchiveActivityResultLauncher.launch(currentWebView!!.title + ".mht")
1992 // Consume the event.
1996 R.id.save_image -> { // Save image.
1997 // Open the file picker with a default file name built from the current domain name.
1998 saveWebpageImageActivityResultLauncher.launch(currentWebView!!.currentDomainName + ".png")
2000 // Consume the event.
2004 R.id.add_to_homescreen -> { // Add to homescreen.
2005 // Instantiate the create home screen shortcut dialog.
2006 val createHomeScreenShortcutDialogFragment: DialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView!!.title!!, currentWebView!!.url!!, currentWebView!!.getFavoriteIcon())
2008 // Show the create home screen shortcut dialog.
2009 createHomeScreenShortcutDialogFragment.show(supportFragmentManager, getString(R.string.create_shortcut))
2011 // Consume the event.
2015 R.id.view_source -> { // View source.
2016 // Open a new tab according to the current URL.
2017 if (currentWebView!!.currentUrl.startsWith("view-source:")) { // The source is currently viewed.
2018 // Open the rendered website in a new tab.
2019 addNewPage(currentWebView!!.currentUrl.substring(12, currentWebView!!.currentUrl.length), true, moveToTab = true)
2020 } else { // The rendered website is currently viewed.
2021 // Open the source in a new tab.
2022 addNewPage("view-source:${currentWebView!!.currentUrl}", adjacent = true, moveToTab = true)
2025 // Consume the event.
2029 R.id.view_headers -> { // View headers.
2030 // Create an intent to launch the view headers activity.
2031 val viewHeadersIntent = Intent(this, ViewHeadersActivity::class.java)
2033 // Add the variables to the intent.
2034 viewHeadersIntent.putExtra(CURRENT_URL, currentWebView!!.url)
2035 viewHeadersIntent.putExtra(USER_AGENT, currentWebView!!.settings.userAgentString)
2038 startActivity(viewHeadersIntent)
2040 // Consume the event.
2044 R.id.share_message -> { // Share a message.
2045 // Prepare the share string.
2046 val shareString = currentWebView!!.title + " – " + currentWebView!!.url
2048 // Create the share intent.
2049 val shareMessageIntent = Intent(Intent.ACTION_SEND)
2051 // Add the share string to the intent.
2052 shareMessageIntent.putExtra(Intent.EXTRA_TEXT, shareString)
2054 // Set the MIME type.
2055 shareMessageIntent.type = "text/plain"
2057 // Set the intent to open in a new task.
2058 shareMessageIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
2061 startActivity(Intent.createChooser(shareMessageIntent, getString(R.string.share_message)))
2063 // Consume the event.
2067 R.id.share_url -> { // Share URL.
2068 // Create the share intent.
2069 val shareUrlIntent = Intent(Intent.ACTION_SEND)
2071 // Add the URL to the intent.
2072 shareUrlIntent.putExtra(Intent.EXTRA_TEXT, currentWebView!!.url)
2074 // Add the title to the intent.
2075 shareUrlIntent.putExtra(Intent.EXTRA_SUBJECT, currentWebView!!.title)
2077 // Set the MIME type.
2078 shareUrlIntent.type = "text/plain"
2080 // Set the intent to open in a new task.
2081 shareUrlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
2084 startActivity(Intent.createChooser(shareUrlIntent, getString(R.string.share_url)))
2086 // Consume the event.
2090 R.id.open_with_app -> { // Open with app.
2091 // Open the URL with an outside app.
2092 openWithApp(currentWebView!!.url!!)
2094 // Consume the event.
2098 R.id.open_with_browser -> { // Open with browser.
2099 // Open the URL with an outside browser.
2100 openWithBrowser(currentWebView!!.url!!)
2102 // Consume the event.
2106 R.id.add_or_edit_domain -> { // Add or edit domain.
2107 // Reapply the domain settings on returning to the main WebView activity.
2108 reapplyDomainSettingsOnRestart = true
2110 // Check if domain settings are currently applied.
2111 if (currentWebView!!.domainSettingsApplied) { // Edit the current domain settings.
2112 // Create an intent to launch the domains activity.
2113 val domainsIntent = Intent(this, DomainsActivity::class.java)
2115 // Add the extra information to the intent.
2116 domainsIntent.putExtra(LOAD_DOMAIN, currentWebView!!.domainSettingsDatabaseId)
2117 domainsIntent.putExtra(CLOSE_ON_BACK, true)
2118 domainsIntent.putExtra(CURRENT_IP_ADDRESSES, currentWebView!!.currentIpAddresses)
2120 // Get the current certificate.
2121 val sslCertificate = currentWebView!!.certificate
2123 // Check to see if the SSL certificate is populated.
2124 if (sslCertificate != null) {
2125 // Extract the certificate to strings.
2126 val issuedToCName = sslCertificate.issuedTo.cName
2127 val issuedToOName = sslCertificate.issuedTo.oName
2128 val issuedToUName = sslCertificate.issuedTo.uName
2129 val issuedByCName = sslCertificate.issuedBy.cName
2130 val issuedByOName = sslCertificate.issuedBy.oName
2131 val issuedByUName = sslCertificate.issuedBy.uName
2132 val startDateLong = sslCertificate.validNotBeforeDate.time
2133 val endDateLong = sslCertificate.validNotAfterDate.time
2135 // Add the certificate to the intent.
2136 domainsIntent.putExtra(SSL_ISSUED_TO_CNAME, issuedToCName)
2137 domainsIntent.putExtra(SSL_ISSUED_TO_ONAME, issuedToOName)
2138 domainsIntent.putExtra(SSL_ISSUED_TO_UNAME, issuedToUName)
2139 domainsIntent.putExtra(SSL_ISSUED_BY_CNAME, issuedByCName)
2140 domainsIntent.putExtra(SSL_ISSUED_BY_ONAME, issuedByOName)
2141 domainsIntent.putExtra(SSL_ISSUED_BY_UNAME, issuedByUName)
2142 domainsIntent.putExtra(SSL_START_DATE, startDateLong)
2143 domainsIntent.putExtra(SSL_END_DATE, endDateLong)
2147 startActivity(domainsIntent)
2148 } else { // Add a new domain.
2149 // Get the current URI.
2150 val currentUri = Uri.parse(currentWebView!!.url)
2152 // Get the current domain from the URI. Use an empty string if it is null.
2153 val currentDomain = currentUri.host?: ""
2155 // Get the current settings status.
2156 val javaScriptInt = calculateSettingsInt(currentWebView!!.settings.javaScriptEnabled, sharedPreferences.getBoolean(getString(R.string.javascript_key), false))
2157 val cookiesInt = calculateSettingsInt(currentWebView!!.acceptCookies, sharedPreferences.getBoolean(getString(R.string.cookies_key), false))
2158 val domStorageInt = calculateSettingsInt(currentWebView!!.settings.domStorageEnabled, sharedPreferences.getBoolean(getString(R.string.dom_storage_key), false))
2159 val easyListInt = calculateSettingsInt(currentWebView!!.easyListEnabled, sharedPreferences.getBoolean(getString(R.string.easylist_key), true))
2160 val easyPrivacyInt = calculateSettingsInt(currentWebView!!.easyPrivacyEnabled, sharedPreferences.getBoolean(getString(R.string.easyprivacy_key), true))
2161 val fanboysAnnoyanceListInt = calculateSettingsInt(currentWebView!!.fanboysAnnoyanceListEnabled, sharedPreferences.getBoolean(getString(R.string.fanboys_annoyance_list_key), true))
2162 val fanboysSocialBlockingListInt = calculateSettingsInt(currentWebView!!.fanboysSocialBlockingListEnabled, sharedPreferences.getBoolean(getString(R.string.fanboys_social_blocking_list_key), true))
2163 val ultraListInt = calculateSettingsInt(currentWebView!!.ultraListEnabled, sharedPreferences.getBoolean(getString(R.string.ultralist_key), true))
2164 val ultraPrivacyInt = calculateSettingsInt(currentWebView!!.ultraPrivacyEnabled, sharedPreferences.getBoolean(getString(R.string.ultraprivacy_key), true))
2165 val blockAllThirdPartyRequestsInt = calculateSettingsInt(currentWebView!!.blockAllThirdPartyRequests, sharedPreferences.getBoolean(getString(R.string.block_all_third_party_requests_key), true))
2166 val swipeToRefreshInt = calculateSettingsInt(currentWebView!!.swipeToRefresh, sharedPreferences.getBoolean(getString(R.string.swipe_to_refresh_key), true))
2167 val wideViewportInt = calculateSettingsInt(currentWebView!!.settings.useWideViewPort, sharedPreferences.getBoolean(getString(R.string.wide_viewport_key), true))
2168 val displayImagesInt = calculateSettingsInt(currentWebView!!.settings.loadsImagesAutomatically, sharedPreferences.getBoolean(getString(R.string.display_webpage_images_key), true))
2170 // Initialize the form data int.
2171 var formDataInt = SYSTEM_DEFAULT
2173 // Set the form data int, which can be removed once the minimum API >= 26.
2174 @Suppress("DEPRECATION")
2175 if (Build.VERSION.SDK_INT < 26) {
2176 // Get the form data status.
2177 val formDataEnabled = currentWebView!!.settings.saveFormData
2179 // Calculate the form data Int.
2180 formDataInt = calculateSettingsInt(formDataEnabled, sharedPreferences.getBoolean(getString(R.string.save_form_data_key), false))
2183 // Get the current user agent string.
2184 val currentUserAgentString = currentWebView!!.settings.userAgentString
2186 // Get the user agent string array position.
2187 val userAgentStringArrayPosition = userAgentDataArrayAdapter.getPosition(currentUserAgentString)
2189 // Set the user agent name.
2190 val userAgentName = if ((userAgentStringArrayPosition >= 0) && (defaultUserAgentName == userAgentNamesArray[userAgentStringArrayPosition])) { // The system default user agent is in use.
2191 getString(R.string.system_default_user_agent)
2192 } else { // An on-the-fly user agent is being used (or the WebView default user agent is applied).
2193 when (userAgentStringArrayPosition) {
2194 UNRECOGNIZED_USER_AGENT -> { // The user agent is unrecognized.
2195 if (currentUserAgentString == webViewDefaultUserAgent) { // The WebView default user agent is being used.
2196 if (defaultUserAgentName == getString(R.string.webview_default)) { // The WebView default user agent is the system default.
2197 // Set the user agent name to be the system default.
2198 getString(R.string.system_default_user_agent)
2199 } else { // The WebView default user agent is set as an on-the-fly setting.
2200 // Set the default user agent name.
2201 getString(R.string.webview_default)
2203 } else { // A custom user agent is being used.
2204 if (defaultUserAgentName == getString(R.string.custom_user_agent_non_translatable)) { // The system custom user agent is in use.
2205 // Set the user agent name to be the system default.
2206 getString(R.string.system_default_user_agent)
2207 } else { // An on-the-fly custom user agent is in use.
2208 // Store the user agent as currently applied.
2209 currentUserAgentString
2214 else -> // Store the standard user agent name.
2215 userAgentNamesArray[userAgentStringArrayPosition]
2219 // Get the current text zoom integer.
2220 val textZoomInt = currentWebView!!.settings.textZoom
2222 // Set the font size integer.
2223 val fontSizeInt = if (textZoomInt == defaultFontSizeString.toInt()) // The current system default is used, which is encoded as a zoom of `0`.
2225 else // A custom font size is used.
2228 // Get the current WebView dark theme status.
2229 val webViewDarkThemeCurrentlyEnabled = if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) // Algorithmic darkening is supported.
2230 WebSettingsCompat.isAlgorithmicDarkeningAllowed(currentWebView!!.settings)
2231 else // Algorithmic darkening is not supported.
2234 // Get the default WebView dark theme setting.
2235 val defaultWebViewDarkThemeEnabled = if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) { // Algorithmic darkening is supported.
2236 when (defaultWebViewTheme) {
2237 webViewThemeEntryValuesStringArray[1] -> // The dark theme is disabled by default.
2240 webViewThemeEntryValuesStringArray[2] -> // The dark theme is enabled by default.
2243 else -> { // The system default theme is selected.
2244 // Get the current app theme status.
2245 val currentAppThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
2247 // Check if the current app theme is dark.
2248 currentAppThemeStatus == Configuration.UI_MODE_NIGHT_YES
2251 } else { // Algorithmic darkening is not supported.
2255 // Set the WebView theme int.
2256 val webViewThemeInt = if (webViewDarkThemeCurrentlyEnabled == defaultWebViewDarkThemeEnabled) // The current WebView theme matches the default.
2258 else if (webViewDarkThemeCurrentlyEnabled) // The current WebView theme is dark and that is not the default.
2260 else // The current WebView theme is light and that is not the default.
2263 // Create the domain and store the database ID.
2264 val newDomainDatabaseId = domainsDatabaseHelper!!.addDomain(currentDomain, javaScriptInt, cookiesInt, domStorageInt, formDataInt, userAgentName, easyListInt, easyPrivacyInt,
2265 fanboysAnnoyanceListInt, fanboysSocialBlockingListInt, ultraListInt, ultraPrivacyInt, blockAllThirdPartyRequestsInt, fontSizeInt,
2266 swipeToRefreshInt, webViewThemeInt, wideViewportInt, displayImagesInt)
2268 // Create an intent to launch the domains activity.
2269 val domainsIntent = Intent(this, DomainsActivity::class.java)
2271 // Add the extra information to the intent.
2272 domainsIntent.putExtra(LOAD_DOMAIN, newDomainDatabaseId)
2273 domainsIntent.putExtra(CLOSE_ON_BACK, true)
2274 domainsIntent.putExtra(CURRENT_IP_ADDRESSES, currentWebView!!.currentIpAddresses)
2276 // Get the current certificate.
2277 val sslCertificate = currentWebView!!.certificate
2279 // Check to see if the SSL certificate is populated.
2280 if (sslCertificate != null) {
2281 // Extract the certificate to strings.
2282 val issuedToCName = sslCertificate.issuedTo.cName
2283 val issuedToOName = sslCertificate.issuedTo.oName
2284 val issuedToUName = sslCertificate.issuedTo.uName
2285 val issuedByCName = sslCertificate.issuedBy.cName
2286 val issuedByOName = sslCertificate.issuedBy.oName
2287 val issuedByUName = sslCertificate.issuedBy.uName
2288 val startDateLong = sslCertificate.validNotBeforeDate.time
2289 val endDateLong = sslCertificate.validNotAfterDate.time
2291 // Add the certificate to the intent.
2292 domainsIntent.putExtra(SSL_ISSUED_TO_CNAME, issuedToCName)
2293 domainsIntent.putExtra(SSL_ISSUED_TO_ONAME, issuedToOName)
2294 domainsIntent.putExtra(SSL_ISSUED_TO_UNAME, issuedToUName)
2295 domainsIntent.putExtra(SSL_ISSUED_BY_CNAME, issuedByCName)
2296 domainsIntent.putExtra(SSL_ISSUED_BY_ONAME, issuedByOName)
2297 domainsIntent.putExtra(SSL_ISSUED_BY_UNAME, issuedByUName)
2298 domainsIntent.putExtra(SSL_START_DATE, startDateLong)
2299 domainsIntent.putExtra(SSL_END_DATE, endDateLong)
2303 startActivity(domainsIntent)
2306 // Consume the event.
2310 else -> { // There is no match with the options menu. Pass the event up to the parent method.
2311 // Don't consume the event.
2312 super.onOptionsItemSelected(menuItem)
2317 override fun onNavigationItemSelected(menuItem: MenuItem): Boolean {
2318 // Run the commands that correspond to the selected menu item.
2319 when (menuItem.itemId) {
2320 R.id.clear_and_exit -> { // Clear and exit.
2321 // Clear and exit Privacy Browser.
2325 R.id.home -> { // Home.
2326 // Load the homepage.
2327 loadUrl(currentWebView!!, sharedPreferences.getString(getString(R.string.homepage_key), getString(R.string.homepage_default_value))!!)
2330 R.id.back -> { // Back.
2331 // Check if the WebView can go back.
2332 if (currentWebView!!.canGoBack()) {
2333 // Get the current web back forward list.
2334 val webBackForwardList = currentWebView!!.copyBackForwardList()
2336 // Get the previous entry data.
2337 val previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex - 1).url
2338 val previousFavoriteIcon = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex - 1).favicon!!
2340 // Apply the domain settings.
2341 applyDomainSettings(currentWebView!!, previousUrl, resetTab = false, reloadWebsite = false, loadUrl = false)
2343 // Get the current tab.
2344 val tab = tabLayout.getTabAt(tabLayout.selectedTabPosition)!!
2346 // Get the custom view from the tab.
2347 val tabView = tab.customView!!
2349 // Get the favorite icon image view from the tab.
2350 val tabFavoriteIconImageView = tabView.findViewById<ImageView>(R.id.favorite_icon_imageview)
2352 // Set the previous favorite icon.
2353 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(previousFavoriteIcon, 64, 64, true))
2355 // Load the previous website in the history.
2356 currentWebView!!.goBack()
2358 // Update the URL edit text after a delay.
2359 updateUrlEditTextAfterDelay()
2363 R.id.forward -> { // Forward.
2364 // Check if the WebView can go forward.
2365 if (currentWebView!!.canGoForward()) {
2366 // Get the current web back forward list.
2367 val webBackForwardList = currentWebView!!.copyBackForwardList()
2369 // Get the next entry data.
2370 val nextUrl = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex + 1).url
2371 val nextFavoriteIcon = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex + 1).favicon!!
2373 // Apply the domain settings.
2374 applyDomainSettings(currentWebView!!, nextUrl, resetTab = false, reloadWebsite = false, loadUrl = false)
2376 // Get the current tab.
2377 val tab = tabLayout.getTabAt(tabLayout.selectedTabPosition)!!
2379 // Get the custom view from the tab.
2380 val tabView = tab.customView!!
2382 // Get the favorite icon image view from the tab.
2383 val tabFavoriteIconImageView = tabView.findViewById<ImageView>(R.id.favorite_icon_imageview)
2385 // Set the next favorite icon.
2386 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nextFavoriteIcon, 64, 64, true))
2388 // Load the next website in the history.
2389 currentWebView!!.goForward()
2391 // Update the URL edit text after a delay.
2392 updateUrlEditTextAfterDelay()
2396 R.id.scroll_to_bottom -> { // Scroll to Bottom.
2397 // Check if the WebView is scrolled to the top.
2398 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.
2399 currentWebView!!.scrollTo(0, 1_000_000_000)
2400 } else { // The WebView is not at the top; scroll to the top.
2401 currentWebView!!.scrollTo(0, 0)
2405 R.id.history -> { // History.
2406 // Instantiate the URL history dialog.
2407 val urlHistoryDialogFragment: DialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView!!.webViewFragmentId)
2409 // Show the URL history dialog.
2410 urlHistoryDialogFragment.show(supportFragmentManager, getString(R.string.history))
2413 R.id.open -> { // Open.
2414 // Instantiate the open file dialog.
2415 val openDialogFragment: DialogFragment = OpenDialog()
2417 // Show the open file dialog.
2418 openDialogFragment.show(supportFragmentManager, getString(R.string.open))
2421 R.id.requests -> { // Requests.
2422 // Populate the resource requests.
2423 RequestsActivity.resourceRequests = currentWebView!!.getResourceRequests()
2425 // Create an intent to launch the Requests activity.
2426 val requestsIntent = Intent(this, RequestsActivity::class.java)
2428 // Add the block third-party requests status to the intent.
2429 requestsIntent.putExtra(BLOCK_ALL_THIRD_PARTY_REQUESTS, currentWebView!!.blockAllThirdPartyRequests)
2432 startActivity(requestsIntent)
2435 R.id.downloads -> { // Downloads.
2436 // Try the default system download manager.
2438 // Launch the default system Download Manager.
2439 val defaultDownloadManagerIntent = Intent(DownloadManager.ACTION_VIEW_DOWNLOADS)
2441 // Launch as a new task so that the download manager and Privacy Browser show as separate windows in the recent tasks list.
2442 defaultDownloadManagerIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2445 startActivity(defaultDownloadManagerIntent)
2446 } catch (defaultDownloadManagerException: Exception) { // The system download manager is not available.
2447 // Try a generic file manager.
2449 // Create a generic file manager intent.
2450 val genericFileManagerIntent = Intent(Intent.ACTION_VIEW)
2452 // Open the download directory.
2453 genericFileManagerIntent.setDataAndType(Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()), DocumentsContract.Document.MIME_TYPE_DIR)
2455 // Launch as a new task so that the file manager and Privacy Browser show as separate windows in the recent tasks list.
2456 genericFileManagerIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2459 startActivity(genericFileManagerIntent)
2460 } catch (genericFileManagerException: Exception) { // A generic file manager is not available.
2461 // Try an alternate file manager.
2463 // Create an alternate file manager intent.
2464 val alternateFileManagerIntent = Intent(Intent.ACTION_VIEW)
2466 // Open the download directory.
2467 alternateFileManagerIntent.setDataAndType(Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()), "resource/folder")
2469 // Launch as a new task so that the file manager and Privacy Browser show as separate windows in the recent tasks list.
2470 alternateFileManagerIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2472 // Open the alternate file manager.
2473 startActivity(alternateFileManagerIntent)
2474 } catch (alternateFileManagerException: Exception) {
2475 // Display a snackbar.
2476 Snackbar.make(currentWebView!!, R.string.no_file_manager_detected, Snackbar.LENGTH_INDEFINITE).show()
2482 R.id.domains -> { // Domains.
2483 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2484 reapplyDomainSettingsOnRestart = true
2486 // Create a domains activity intent.
2487 val domainsIntent = Intent(this, DomainsActivity::class.java)
2489 // Add the extra information to the intent.
2490 domainsIntent.putExtra(CURRENT_IP_ADDRESSES, currentWebView!!.currentIpAddresses)
2492 // Get the current certificate.
2493 val sslCertificate = currentWebView!!.certificate
2495 // Check to see if the SSL certificate is populated.
2496 if (sslCertificate != null) {
2497 // Extract the certificate to strings.
2498 val issuedToCName = sslCertificate.issuedTo.cName
2499 val issuedToOName = sslCertificate.issuedTo.oName
2500 val issuedToUName = sslCertificate.issuedTo.uName
2501 val issuedByCName = sslCertificate.issuedBy.cName
2502 val issuedByOName = sslCertificate.issuedBy.oName
2503 val issuedByUName = sslCertificate.issuedBy.uName
2504 val startDateLong = sslCertificate.validNotBeforeDate.time
2505 val endDateLong = sslCertificate.validNotAfterDate.time
2507 // Add the certificate to the intent.
2508 domainsIntent.putExtra(SSL_ISSUED_TO_CNAME, issuedToCName)
2509 domainsIntent.putExtra(SSL_ISSUED_TO_ONAME, issuedToOName)
2510 domainsIntent.putExtra(SSL_ISSUED_TO_UNAME, issuedToUName)
2511 domainsIntent.putExtra(SSL_ISSUED_BY_CNAME, issuedByCName)
2512 domainsIntent.putExtra(SSL_ISSUED_BY_ONAME, issuedByOName)
2513 domainsIntent.putExtra(SSL_ISSUED_BY_UNAME, issuedByUName)
2514 domainsIntent.putExtra(SSL_START_DATE, startDateLong)
2515 domainsIntent.putExtra(SSL_END_DATE, endDateLong)
2519 startActivity(domainsIntent)
2522 R.id.settings -> { // Settings.
2523 // Set the reapply on restart flags.
2524 reapplyAppSettingsOnRestart = true
2525 reapplyDomainSettingsOnRestart = true
2527 // Create a settings intent.
2528 val settingsIntent = Intent(this, SettingsActivity::class.java)
2531 startActivity(settingsIntent)
2534 R.id.import_export -> { // Import/Export.
2535 // Create an intent to launch the import/export activity.
2536 val importExportIntent = Intent(this, ImportExportActivity::class.java)
2539 startActivity(importExportIntent)
2542 R.id.logcat -> { // Logcat.
2543 // Create an intent to launch the logcat activity.
2544 val logcatIntent = Intent(this, LogcatActivity::class.java)
2547 startActivity(logcatIntent)
2550 R.id.webview_devtools -> { // WebView DevTools.
2551 // Create a WebView DevTools intent.
2552 val webViewDevToolsIntent = Intent("com.android.webview.SHOW_DEV_UI")
2554 // Launch as a new task so that the WebView DevTools and Privacy Browser show as a separate windows in the recent tasks list.
2555 webViewDevToolsIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2558 startActivity(webViewDevToolsIntent)
2561 R.id.guide -> { // Guide.
2562 // Create an intent to launch the guide activity.
2563 val guideIntent = Intent(this, GuideActivity::class.java)
2566 startActivity(guideIntent)
2569 R.id.about -> { // About
2570 // Create an intent to launch the about activity.
2571 val aboutIntent = Intent(this, AboutActivity::class.java)
2573 // Create a string array for the filter list versions.
2574 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])
2576 // Add the filter list versions to the intent.
2577 aboutIntent.putExtra(FILTERLIST_VERSIONS, filterListVersions)
2580 startActivity(aboutIntent)
2584 // Close the navigation drawer.
2585 drawerLayout.closeDrawer(GravityCompat.START)
2591 override fun onCreateContextMenu(contextMenu: ContextMenu, view: View, contextMenuInfo: ContextMenu.ContextMenuInfo?) {
2592 // Get the hit test result.
2593 val hitTestResult = currentWebView!!.hitTestResult
2595 // Define the URL strings.
2596 val imageUrl: String?
2597 val linkUrl: String?
2599 // Get a handle for the clipboard manager.
2600 val clipboardManager = (getSystemService(CLIPBOARD_SERVICE) as ClipboardManager)
2602 // Process the link according to the type.
2603 when (hitTestResult.type) {
2604 // `SRC_ANCHOR_TYPE` is a link.
2605 WebView.HitTestResult.SRC_ANCHOR_TYPE -> {
2606 // Get the target URL.
2607 linkUrl = hitTestResult.extra!!
2609 // Set the target URL as the context menu title.
2610 contextMenu.setHeaderTitle(linkUrl)
2612 // Add an open in new tab entry.
2613 contextMenu.add(R.string.open_in_new_tab).setOnMenuItemClickListener {
2614 // Load the link URL in a new tab and move to it.
2615 addNewPage(linkUrl, adjacent = true, moveToTab = true)
2617 // Consume the event.
2621 // Add an open in background entry.
2622 contextMenu.add(R.string.open_in_background).setOnMenuItemClickListener {
2623 // Load the link URL in a new tab but do not move to it.
2624 addNewPage(linkUrl, adjacent = true, moveToTab = false)
2626 // Consume the event.
2630 // Add an open with app entry.
2631 contextMenu.add(R.string.open_with_app).setOnMenuItemClickListener {
2632 // Open the URL with another app.
2633 openWithApp(linkUrl)
2635 // Consume the event.
2639 // Add an open with browser entry.
2640 contextMenu.add(R.string.open_with_browser).setOnMenuItemClickListener {
2641 // Open the URL with another browser.
2642 openWithBrowser(linkUrl)
2644 // Consume the event.
2648 // Add a copy URL entry.
2649 contextMenu.add(R.string.copy_url).setOnMenuItemClickListener {
2650 // Save the link URL in a clip data.
2651 val srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl)
2653 // Set the clip data as the clipboard's primary clip.
2654 clipboardManager.setPrimaryClip(srcAnchorTypeClipData)
2656 // Consume the event.
2660 // Add a Save URL entry.
2661 contextMenu.add(R.string.save_url).setOnMenuItemClickListener {
2662 // Check the download preference.
2663 if (downloadWithExternalApp) // Download with an external app.
2664 saveWithExternalApp(linkUrl)
2665 else // Handle the download inside of Privacy Browser. The dialog will be displayed once the file size and the content disposition have been acquired.
2666 PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, linkUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
2668 // Consume the event.
2672 // Add a Share URL entry.
2673 contextMenu.add(R.string.share_url).setOnMenuItemClickListener {
2674 // Create the share intent.
2675 val shareUrlIntent = Intent(Intent.ACTION_SEND)
2677 // Add the URL to the intent.
2678 shareUrlIntent.putExtra(Intent.EXTRA_TEXT, linkUrl)
2680 // Set the MIME type.
2681 shareUrlIntent.type = "text/plain"
2683 // Set the intent to open in a new task.
2684 shareUrlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
2687 startActivity(Intent.createChooser(shareUrlIntent, getString(R.string.share_url)))
2689 // Consume the event.
2693 // Add an empty cancel entry, which by default closes the context menu.
2694 contextMenu.add(R.string.cancel)
2697 // `IMAGE_TYPE` is an image.
2698 WebView.HitTestResult.IMAGE_TYPE -> {
2699 // Get the image URL.
2700 imageUrl = hitTestResult.extra!!
2702 // Set the context menu title.
2703 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.
2704 contextMenu.setHeaderTitle(imageUrl.substring(0, 100))
2705 else // The image URL does not contain the full image data. Set the image URL as the title of the context menu.
2706 contextMenu.setHeaderTitle(imageUrl)
2708 // Add an open in new tab entry.
2709 contextMenu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener {
2710 // Load the image in a new tab.
2711 addNewPage(imageUrl, adjacent = true, moveToTab = true)
2713 // Consume the event.
2717 // Add an open with app entry.
2718 contextMenu.add(R.string.open_with_app).setOnMenuItemClickListener {
2719 // Open the image URL with an external app.
2720 openWithApp(imageUrl)
2722 // Consume the event.
2726 // Add an open with browser entry.
2727 contextMenu.add(R.string.open_with_browser).setOnMenuItemClickListener {
2728 // Open the image URL with an external browser.
2729 openWithBrowser(imageUrl)
2731 // Consume the event.
2735 // Add a view image entry.
2736 contextMenu.add(R.string.view_image).setOnMenuItemClickListener {
2737 // Load the image in the current tab.
2738 loadUrl(currentWebView!!, imageUrl)
2740 // Consume the event.
2744 // Add a save image entry.
2745 contextMenu.add(R.string.save_image).setOnMenuItemClickListener {
2746 // Check the download preference.
2747 if (downloadWithExternalApp) { // Download with an external app.
2748 saveWithExternalApp(imageUrl)
2749 } else { // Handle the download inside of Privacy Browser. The dialog will be displayed once the file size and the content disposition have been acquired.
2750 PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, imageUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
2753 // Consume the event.
2757 // Add a copy URL entry.
2758 contextMenu.add(R.string.copy_url).setOnMenuItemClickListener {
2759 // Save the image URL in a clip data.
2760 val imageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl)
2762 // Set the clip data as the clipboard's primary clip.
2763 clipboardManager.setPrimaryClip(imageTypeClipData)
2765 // Consume the event.
2769 // Add a Share URL entry.
2770 contextMenu.add(R.string.share_url).setOnMenuItemClickListener {
2771 // Create the share intent.
2772 val shareUrlIntent = Intent(Intent.ACTION_SEND)
2774 // Add the URL to the intent.
2775 shareUrlIntent.putExtra(Intent.EXTRA_TEXT, imageUrl)
2777 // Set the MIME type.
2778 shareUrlIntent.type = "text/plain"
2780 // Set the intent to open in a new task.
2781 shareUrlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
2784 startActivity(Intent.createChooser(shareUrlIntent, getString(R.string.share_url)))
2786 // Consume the event.
2790 // Add an empty cancel entry, which by default closes the context menu.
2791 contextMenu.add(R.string.cancel)
2794 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2795 WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE -> {
2796 // Get the image URL.
2797 imageUrl = hitTestResult.extra!!
2799 // Instantiate a handler.
2800 val handler = Handler(Looper.getMainLooper())
2802 // Get a handle for the handler message.
2803 val message = handler.obtainMessage()
2805 // Request the image details from the last touched node be returned in the message.
2806 currentWebView!!.requestFocusNodeHref(message)
2808 // Get the link URL from the message data.
2809 linkUrl = message.data.getString("url")!!
2811 // Set the link URL as the title of the context menu.
2812 contextMenu.setHeaderTitle(linkUrl)
2814 // Add an open in new tab entry.
2815 contextMenu.add(R.string.open_in_new_tab).setOnMenuItemClickListener {
2816 // Load the link URL in a new tab and move to it.
2817 addNewPage(linkUrl, adjacent = true, moveToTab = true)
2819 // Consume the event.
2823 // Add an open in background entry.
2824 contextMenu.add(R.string.open_in_background).setOnMenuItemClickListener {
2825 // Lod the link URL in a new tab but do not move to it.
2826 addNewPage(linkUrl, adjacent = true, moveToTab = false)
2828 // Consume the event.
2832 // Add an open image in new tab entry.
2833 contextMenu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener {
2834 // Load the image in a new tab and move to it.
2835 addNewPage(imageUrl, adjacent = true, moveToTab = true)
2837 // Consume the event.
2841 // Add an open with app entry.
2842 contextMenu.add(R.string.open_with_app).setOnMenuItemClickListener {
2843 // Open the link URL with an external app.
2844 openWithApp(linkUrl)
2846 // Consume the event.
2850 // Add an open with browser entry.
2851 contextMenu.add(R.string.open_with_browser).setOnMenuItemClickListener {
2852 // Open the link URL with an external browser.
2853 openWithBrowser(linkUrl)
2855 // Consume the event.
2859 // Add a view image entry.
2860 contextMenu.add(R.string.view_image).setOnMenuItemClickListener {
2861 // View the image in the current tab.
2862 loadUrl(currentWebView!!, imageUrl)
2864 // Consume the event.
2868 // Add a Save Image entry.
2869 contextMenu.add(R.string.save_image).setOnMenuItemClickListener {
2870 // Check the download preference.
2871 if (downloadWithExternalApp) // Download with an external app.
2872 saveWithExternalApp(imageUrl)
2873 else // Handle the download inside of Privacy Browser. The dialog will be displayed once the file size and the content disposition have been acquired.
2874 PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, imageUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
2876 // Consume the event.
2880 // Add a Share Image entry.
2881 contextMenu.add(R.string.share_image).setOnMenuItemClickListener {
2882 // Create the share intent.
2883 val shareUrlIntent = Intent(Intent.ACTION_SEND)
2885 // Add the URL to the intent.
2886 shareUrlIntent.putExtra(Intent.EXTRA_TEXT, imageUrl)
2888 // Set the MIME type.
2889 shareUrlIntent.type = "text/plain"
2891 // Set the intent to open in a new task.
2892 shareUrlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
2895 startActivity(Intent.createChooser(shareUrlIntent, getString(R.string.share_url)))
2897 // Consume the event.
2901 // Add a copy URL entry.
2902 contextMenu.add(R.string.copy_url).setOnMenuItemClickListener {
2903 // Save the link URL in a clip data.
2904 val srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl)
2906 // Set the clip data as the clipboard's primary clip.
2907 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData)
2909 // Consume the event.
2913 // Add a save URL entry.
2914 contextMenu.add(R.string.save_url).setOnMenuItemClickListener {
2915 // Check the download preference.
2916 if (downloadWithExternalApp) // Download with an external app.
2917 saveWithExternalApp(linkUrl)
2918 else // Handle the download inside of Privacy Browser. The dialog will be displayed once the file size and the content disposition have been acquired.
2919 PrepareSaveDialogCoroutine.prepareSaveDialog(this, supportFragmentManager, linkUrl, currentWebView!!.settings.userAgentString, currentWebView!!.acceptCookies)
2921 // Consume the event.
2925 // Add a Share URL entry.
2926 contextMenu.add(R.string.share_url).setOnMenuItemClickListener {
2927 // Create the share intent.
2928 val shareUrlIntent = Intent(Intent.ACTION_SEND)
2930 // Add the URL to the intent.
2931 shareUrlIntent.putExtra(Intent.EXTRA_TEXT, linkUrl)
2933 // Set the MIME type.
2934 shareUrlIntent.type = "text/plain"
2936 // Set the intent to open in a new task.
2937 shareUrlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
2940 startActivity(Intent.createChooser(shareUrlIntent, getString(R.string.share_url)))
2942 // Consume the event.
2946 // Add an empty cancel entry, which by default closes the context menu.
2947 contextMenu.add(R.string.cancel)
2950 WebView.HitTestResult.EMAIL_TYPE -> {
2951 // Get the target URL.
2952 linkUrl = hitTestResult.extra
2954 // Set the target URL as the title of the context menu.
2955 contextMenu.setHeaderTitle(linkUrl)
2957 // Add a write email entry.
2958 contextMenu.add(R.string.write_email).setOnMenuItemClickListener {
2959 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2960 val emailIntent = Intent(Intent.ACTION_SENDTO)
2962 // Parse the url and set it as the data for the intent.
2963 emailIntent.data = Uri.parse("mailto:$linkUrl")
2965 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2966 emailIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
2970 startActivity(emailIntent)
2971 } catch (exception: ActivityNotFoundException) {
2972 // Display a snackbar.
2973 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
2976 // Consume the event.
2980 // Add a copy email address entry.
2981 contextMenu.add(R.string.copy_email_address).setOnMenuItemClickListener {
2982 // Save the email address in a clip data.
2983 val srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl)
2985 // Set the clip data as the clipboard's primary clip.
2986 clipboardManager.setPrimaryClip(srcEmailTypeClipData)
2988 // Consume the event.
2992 // Add an empty cancel entry, which by default closes the context menu.
2993 contextMenu.add(R.string.cancel)
2998 // The view parameter cannot be removed because it is called from the layout onClick.
2999 fun addTab(@Suppress("UNUSED_PARAMETER")view: View?) {
3000 // Add a new tab with a blank URL.
3001 addNewPage(urlString = "", adjacent = true, moveToTab = true)
3004 private fun addNewPage(urlString: String, adjacent: Boolean, moveToTab: Boolean) {
3005 // Clear the focus from the URL edit text, so that it will be populated with the information from the new tab.
3006 urlEditText.clearFocus()
3008 // Add the new tab after the tab layout has quiesced.
3009 // Otherwise, there can be problems when restoring a large number of tabs and processing a new intent at the same time. <https://redmine.stoutner.com/issues/1136>
3011 // Get the new tab position.
3012 val newTabPosition = if (adjacent) // The new tab position is immediately to the right of the current tab position.
3013 tabLayout.selectedTabPosition + 1
3014 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.
3017 // Add the new WebView page.
3018 webViewStateAdapter!!.addPage(newTabPosition, urlString)
3021 addNewTab(newTabPosition, moveToTab)
3025 private fun addNewTab(newTabPosition: Int, moveToTab: Boolean) {
3026 // Check to see if the new page is ready.
3027 if (webViewStateAdapter!!.itemCount >= tabLayout.tabCount) { // The new page is ready.
3028 // Create a new tab.
3029 val newTab = tabLayout.newTab()
3031 // Set a custom view on the new tab.
3032 newTab.setCustomView(R.layout.tab_custom_view)
3035 tabLayout.addTab(newTab, newTabPosition, moveToTab)
3037 // 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.
3038 if (newTabPosition == 0)
3039 tabLayout.selectTab(newTab)
3041 // Scroll to the new tab position if moving to the new tab.
3044 tabLayout.setScrollPosition(newTabPosition, 0F, false, false)
3047 // Show the app bar if it is at the bottom of the screen and the new tab is taking focus.
3048 if (bottomAppBar && moveToTab && appBarLayout.translationY != 0f) {
3049 // Animate the bottom app bar onto the screen.
3050 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0f)
3053 objectAnimator.start()
3055 } else { // The new page is not ready.
3056 // Create a new tab handler.
3057 val newTabHandler = Handler(Looper.getMainLooper())
3059 // Create a new tab runnable.
3060 val newTabRunnable = Runnable {
3061 // Create the new tab.
3062 addNewTab(newTabPosition, moveToTab)
3065 // Try adding the new tab again after 50 milliseconds.
3066 newTabHandler.postDelayed(newTabRunnable, 50)
3070 private fun applyAppSettings() {
3071 // 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.
3072 defaultJavaScript = sharedPreferences.getBoolean(getString(R.string.javascript_key), false)
3073 defaultCookies = sharedPreferences.getBoolean(getString(R.string.cookies_key), false)
3074 defaultDomStorage = sharedPreferences.getBoolean(getString(R.string.dom_storage_key), false)
3075 defaultFormData = sharedPreferences.getBoolean(getString(R.string.save_form_data_key), false) // Form data can be removed once the minimum API >= 26.
3076 defaultEasyList = sharedPreferences.getBoolean(getString(R.string.easylist_key), true)
3077 defaultEasyPrivacy = sharedPreferences.getBoolean(getString(R.string.easyprivacy_key), true)
3078 defaultFanboysAnnoyanceList = sharedPreferences.getBoolean(getString(R.string.fanboys_annoyance_list_key), true)
3079 defaultFanboysSocialBlockingList = sharedPreferences.getBoolean(getString(R.string.fanboys_social_blocking_list_key), true)
3080 defaultUltraList = sharedPreferences.getBoolean(getString(R.string.ultralist_key), true)
3081 defaultUltraPrivacy = sharedPreferences.getBoolean(getString(R.string.ultraprivacy_key), true)
3082 defaultBlockAllThirdPartyRequests = sharedPreferences.getBoolean(getString(R.string.block_all_third_party_requests_key), false)
3083 defaultFontSizeString = sharedPreferences.getString(getString(R.string.font_size_key), getString(R.string.font_size_default_value))!!
3084 defaultUserAgentName = sharedPreferences.getString(getString(R.string.user_agent_key), getString(R.string.user_agent_default_value))!!
3085 defaultSwipeToRefresh = sharedPreferences.getBoolean(getString(R.string.swipe_to_refresh_key), true)
3086 defaultWebViewTheme = sharedPreferences.getString(getString(R.string.webview_theme_key), getString(R.string.webview_theme_default_value))!!
3087 defaultWideViewport = sharedPreferences.getBoolean(getString(R.string.wide_viewport_key), true)
3088 defaultDisplayWebpageImages = sharedPreferences.getBoolean(getString(R.string.display_webpage_images_key), true)
3090 // Get the string arrays. These are done here so that expensive resource requests are not made each time a domain is loaded.
3091 webViewThemeEntryValuesStringArray = resources.getStringArray(R.array.webview_theme_entry_values)
3092 userAgentDataArray = resources.getStringArray(R.array.user_agent_data)
3093 userAgentNamesArray = resources.getStringArray(R.array.user_agent_names)
3094 val downloadProviderEntryValuesStringArray = resources.getStringArray(R.array.download_provider_entry_values)
3096 // Get the user agent array adapters. These are done here so that expensive resource requests are not made each time a domain is loaded.
3097 userAgentDataArrayAdapter = ArrayAdapter.createFromResource(this, R.array.user_agent_data, R.layout.spinner_item)
3098 userAgentNamesArrayAdapter = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item)
3100 // Store the values from the shared preferences in variables.
3101 incognitoModeEnabled = sharedPreferences.getBoolean(getString(R.string.incognito_mode_key), false)
3102 sanitizeTrackingQueries = sharedPreferences.getBoolean(getString(R.string.tracking_queries_key), true)
3103 sanitizeAmpRedirects = sharedPreferences.getBoolean(getString(R.string.amp_redirects_key), true)
3104 proxyMode = sharedPreferences.getString(getString(R.string.proxy_key), getString(R.string.proxy_default_value))!!
3105 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean(getString(R.string.full_screen_browsing_mode_key), false)
3106 hideAppBar = sharedPreferences.getBoolean(getString(R.string.hide_app_bar_key), true)
3107 val downloadProvider = sharedPreferences.getString(getString(R.string.download_provider_key), getString(R.string.download_provider_default_value))!!
3108 scrollAppBar = sharedPreferences.getBoolean(getString(R.string.scroll_app_bar_key), false)
3110 // Determine if downloading should be handled by an external app.
3111 downloadWithExternalApp = (downloadProvider == downloadProviderEntryValuesStringArray[2])
3113 // Apply the saved proxy mode if the app has been restarted.
3114 if (savedProxyMode != null) {
3115 // Apply the saved proxy mode.
3116 proxyMode = savedProxyMode!!
3118 // Reset the saved proxy mode.
3119 savedProxyMode = null
3122 // Get the search string.
3123 val searchString = sharedPreferences.getString(getString(R.string.search_key), getString(R.string.search_default_value))!!
3125 // Set the search string, using the custom search URL if specified.
3126 searchURL = if (searchString == getString(R.string.custom_url_item))
3127 sharedPreferences.getString(getString(R.string.search_custom_url_key), getString(R.string.search_custom_url_default_value))!!
3134 // Adjust the layout and scrolling parameters according to the position of the app bar.
3135 if (bottomAppBar) { // The app bar is on the bottom.
3137 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) { // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
3138 // Reset the WebView padding to fill the available space.
3139 swipeRefreshLayout.setPadding(0, 0, 0, 0)
3140 } else { // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
3141 // Move the WebView above the app bar layout.
3142 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
3144 // Show the app bar if it is scrolled off the screen.
3145 if (appBarLayout.translationY != 0f) {
3146 // Animate the bottom app bar onto the screen.
3147 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0f)
3150 objectAnimator.start()
3153 } else { // The app bar is on the top.
3154 // Get the current layout parameters. Using coordinator layout parameters allows the `setBehavior()` command and using app bar layout parameters allows the `setScrollFlags()` command.
3155 val swipeRefreshLayoutParams = swipeRefreshLayout.layoutParams as CoordinatorLayout.LayoutParams
3156 val toolbarLayoutParams = toolbar.layoutParams as AppBarLayout.LayoutParams
3157 val findOnPageLayoutParams = findOnPageLinearLayout.layoutParams as AppBarLayout.LayoutParams
3158 val tabsLayoutParams = tabsLinearLayout.layoutParams as AppBarLayout.LayoutParams
3160 // Add the scrolling behavior to the layout parameters.
3162 // Enable scrolling of the app bar.
3163 swipeRefreshLayoutParams.behavior = AppBarLayout.ScrollingViewBehavior()
3164 toolbarLayoutParams.scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS or AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP
3165 findOnPageLayoutParams.scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS or AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP
3166 tabsLayoutParams.scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS or AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP
3168 // Disable scrolling of the app bar.
3169 swipeRefreshLayoutParams.behavior = null
3170 toolbarLayoutParams.scrollFlags = 0
3171 findOnPageLayoutParams.scrollFlags = 0
3172 tabsLayoutParams.scrollFlags = 0
3174 // Expand the app bar if it is currently collapsed.
3175 appBarLayout.setExpanded(true)
3178 // Set the app bar scrolling for each WebView.
3179 for (i in 0 until webViewStateAdapter!!.itemCount) {
3180 // Get the WebView tab fragment.
3181 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
3183 // Get the fragment view.
3184 val fragmentView = webViewTabFragment.view
3186 // Only modify the WebViews if they exist.
3187 if (fragmentView != null) {
3188 // Get the nested scroll WebView from the tab fragment.
3189 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
3191 // Set the app bar scrolling.
3192 nestedScrollWebView.isNestedScrollingEnabled = scrollAppBar
3197 // Update the full screen browsing mode settings.
3198 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
3199 // Update the visibility of the app bar, which might have changed in the settings.
3201 // Hide the tab linear layout.
3202 tabsLinearLayout.visibility = View.GONE
3204 // Hide the app bar.
3207 // Show the tab linear layout.
3208 tabsLinearLayout.visibility = View.VISIBLE
3210 // Show the app bar.
3214 /* Hide the system bars.
3215 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3216 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
3217 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3218 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3221 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
3222 @Suppress("DEPRECATION")
3223 rootFrameLayout.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
3224 } else { // Privacy Browser is not in full screen browsing mode.
3225 // Reset the full screen tracker, which could be true if Privacy Browser was in full screen mode before entering settings and full screen browsing was disabled.
3226 inFullScreenBrowsingMode = false
3228 // Show the tab linear layout.
3229 tabsLinearLayout.visibility = View.VISIBLE
3231 // Show the app bar.
3234 // Remove the `SYSTEM_UI` flags from the root frame layout. The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
3235 @Suppress("DEPRECATION")
3236 rootFrameLayout.systemUiVisibility = 0
3240 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
3241 @SuppressLint("SetJavaScriptEnabled")
3242 private fun applyDomainSettings(nestedScrollWebView: NestedScrollWebView, url: String?, resetTab: Boolean, reloadWebsite: Boolean, loadUrl: Boolean) {
3243 // Store the current URL.
3244 nestedScrollWebView.currentUrl = url!!
3246 // Parse the URL into a URI.
3247 val uri = Uri.parse(url)
3249 // Extract the domain from the URI.
3250 var newHostName = uri.host
3252 // Strings don't like to be null.
3253 if (newHostName == null)
3256 // Apply the domain settings if a new domain is being loaded or if the new domain is blank. This allows the user to set temporary settings for JavaScript, cookies, DOM storage, etc.
3257 if ((nestedScrollWebView.currentDomainName != newHostName) || (newHostName == "")) { // A new domain is being loaded.
3258 // Set the new host name as the current domain name.
3259 nestedScrollWebView.currentDomainName = newHostName
3261 // Reset the ignoring of pinned domain information.
3262 nestedScrollWebView.ignorePinnedDomainInformation = false
3264 // Clear any pinned SSL certificate or IP addresses.
3265 nestedScrollWebView.clearPinnedSslCertificate()
3266 nestedScrollWebView.pinnedIpAddresses = ""
3268 // Reset the favorite icon if specified.
3270 // Initialize the favorite icon.
3271 nestedScrollWebView.initializeFavoriteIcon()
3273 // Get the current page position.
3274 val currentPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
3276 // Get the corresponding tab.
3277 val tab = tabLayout.getTabAt(currentPagePosition)
3279 // Update the tab if it isn't null, which sometimes happens when restarting from the background.
3281 // Get the tab custom view.
3282 val tabCustomView = tab.customView!!
3284 // Get the tab views.
3285 val tabFavoriteIconImageView = tabCustomView.findViewById<ImageView>(R.id.favorite_icon_imageview)
3286 val tabTitleTextView = tabCustomView.findViewById<TextView>(R.id.title_textview)
3288 // Store the current values in case they need to be restored.
3289 nestedScrollWebView.previousFavoriteIconDrawable = tabFavoriteIconImageView.drawable
3290 nestedScrollWebView.previousWebpageTitle = tabTitleTextView.text.toString()
3292 // Set the default favorite icon as the favorite icon for this tab.
3293 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nestedScrollWebView.getFavoriteIcon(), 64, 64, true))
3295 // Set the loading title text.
3296 tabTitleTextView.setText(R.string.loading)
3300 // Initialize the domain name in database variable.
3301 var domainNameInDatabase: String? = null
3303 // Check the hostname against the domain settings set.
3304 if (domainsSettingsSet.contains(newHostName)) { // The hostname is contained in the domain settings set.
3305 // Record the domain name in the database.
3306 domainNameInDatabase = newHostName
3308 // Set the domain settings applied tracker to true.
3309 nestedScrollWebView.domainSettingsApplied = true
3310 } else { // The hostname is not contained in the domain settings set.
3311 // Set the domain settings applied tracker to false.
3312 nestedScrollWebView.domainSettingsApplied = false
3315 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3316 while (!nestedScrollWebView.domainSettingsApplied && newHostName!!.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the hostname.
3317 if (domainsSettingsSet.contains("*.$newHostName")) { // Check the host name prepended by `*.`.
3318 // Set the domain settings applied tracker to true.
3319 nestedScrollWebView.domainSettingsApplied = true
3321 // Store the applied domain names as it appears in the database.
3322 domainNameInDatabase = "*.$newHostName"
3325 // Strip out the lowest subdomain of of the host name.
3326 newHostName = newHostName.substring(newHostName.indexOf(".") + 1)
3329 // Apply either the domain settings or the default settings.
3330 if (nestedScrollWebView.domainSettingsApplied) { // The url has custom domain settings.
3331 // Get a cursor for the current host.
3332 val currentDomainSettingsCursor = domainsDatabaseHelper!!.getCursorForDomainName(domainNameInDatabase!!)
3334 // Move to the first position.
3335 currentDomainSettingsCursor.moveToFirst()
3337 // Get the settings from the cursor.
3338 nestedScrollWebView.domainSettingsDatabaseId = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ID))
3339 val javaScriptInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_JAVASCRIPT))
3340 val cookiesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(COOKIES))
3341 val domStorageInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_DOM_STORAGE))
3342 val formDataInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_FORM_DATA)) // Form data can be removed once the minimum API >= 26.
3343 val easyListInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_EASYLIST))
3344 val easyPrivacyInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_EASYPRIVACY))
3345 val fanboysAnnoyanceListInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_FANBOYS_ANNOYANCE_LIST))
3346 val fanboysSocialBlockingListInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST))
3347 val ultraListInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.ULTRALIST))
3348 val ultraPrivacyInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(ENABLE_ULTRAPRIVACY))
3349 val blockAllThirdPartyRequestsInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.BLOCK_ALL_THIRD_PARTY_REQUESTS))
3350 val userAgentName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.USER_AGENT))
3351 val fontSize = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(FONT_SIZE))
3352 val swipeToRefreshInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(SWIPE_TO_REFRESH))
3353 val webViewThemeInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(WEBVIEW_THEME))
3354 val wideViewportInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(WIDE_VIEWPORT))
3355 val displayWebpageImagesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(DISPLAY_IMAGES))
3356 val pinnedSslCertificate = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(PINNED_SSL_CERTIFICATE)) == 1)
3357 val pinnedSslIssuedToCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_TO_COMMON_NAME))
3358 val pinnedSslIssuedToOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_TO_ORGANIZATION))
3359 val pinnedSslIssuedToUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_TO_ORGANIZATIONAL_UNIT))
3360 val pinnedSslIssuedByCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_BY_COMMON_NAME))
3361 val pinnedSslIssuedByOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_BY_ORGANIZATION))
3362 val pinnedSslIssuedByUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(SSL_ISSUED_BY_ORGANIZATIONAL_UNIT))
3363 val pinnedSslStartDate = Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.SSL_START_DATE)))
3364 val pinnedSslEndDate = Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndexOrThrow(com.stoutner.privacybrowser.helpers.SSL_END_DATE)))
3365 val pinnedIpAddresses = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndexOrThrow(PINNED_IP_ADDRESSES)) == 1)
3366 val pinnedHostIpAddresses = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndexOrThrow(IP_ADDRESSES))
3368 // Close the current host domain settings cursor.
3369 currentDomainSettingsCursor.close()
3371 // Set the JavaScript status.
3372 when (javaScriptInt) {
3373 SYSTEM_DEFAULT -> nestedScrollWebView.settings.javaScriptEnabled = defaultJavaScript
3374 ENABLED -> nestedScrollWebView.settings.javaScriptEnabled = true
3375 DISABLED -> nestedScrollWebView.settings.javaScriptEnabled = false
3378 // Store the cookies status.
3380 SYSTEM_DEFAULT -> nestedScrollWebView.acceptCookies = defaultCookies
3381 ENABLED -> nestedScrollWebView.acceptCookies = true
3382 DISABLED -> nestedScrollWebView.acceptCookies = false
3385 // Apply the cookies status.
3386 cookieManager.setAcceptCookie(nestedScrollWebView.acceptCookies)
3388 // Set the DOM storage status.
3389 when (domStorageInt) {
3390 SYSTEM_DEFAULT -> nestedScrollWebView.settings.domStorageEnabled = defaultDomStorage
3391 ENABLED -> nestedScrollWebView.settings.domStorageEnabled = true
3392 DISABLED -> nestedScrollWebView.settings.domStorageEnabled = false
3395 // Apply the form data setting if the API < 26.
3396 @Suppress("DEPRECATION")
3397 if (Build.VERSION.SDK_INT < 26) {
3398 // Set the form data status.
3399 when (formDataInt) {
3400 SYSTEM_DEFAULT -> nestedScrollWebView.settings.saveFormData = defaultFormData
3401 ENABLED -> nestedScrollWebView.settings.saveFormData = true
3402 DISABLED -> nestedScrollWebView.settings.saveFormData = false
3406 // Set the EasyList status.
3407 when (easyListInt) {
3408 SYSTEM_DEFAULT -> nestedScrollWebView.easyListEnabled = defaultEasyList
3409 ENABLED -> nestedScrollWebView.easyListEnabled = true
3410 DISABLED -> nestedScrollWebView.easyListEnabled = false
3413 // Set the EasyPrivacy status.
3414 when (easyPrivacyInt) {
3415 SYSTEM_DEFAULT -> nestedScrollWebView.easyPrivacyEnabled = defaultEasyPrivacy
3416 ENABLED -> nestedScrollWebView.easyPrivacyEnabled = true
3417 DISABLED -> nestedScrollWebView.easyPrivacyEnabled = false
3420 // Set the Fanboy's Annoyance List status.
3421 when (fanboysAnnoyanceListInt) {
3422 SYSTEM_DEFAULT -> nestedScrollWebView.fanboysAnnoyanceListEnabled = defaultFanboysAnnoyanceList
3423 ENABLED -> nestedScrollWebView.fanboysAnnoyanceListEnabled = true
3424 DISABLED -> nestedScrollWebView.fanboysAnnoyanceListEnabled = false
3427 // Set the Fanboy's Social Blocking List status.
3428 when (fanboysSocialBlockingListInt) {
3429 SYSTEM_DEFAULT -> nestedScrollWebView.fanboysSocialBlockingListEnabled = defaultFanboysSocialBlockingList
3430 ENABLED -> nestedScrollWebView.fanboysSocialBlockingListEnabled = true
3431 DISABLED -> nestedScrollWebView.fanboysSocialBlockingListEnabled = false
3434 // Set the UltraList status.
3435 when (ultraListInt) {
3436 SYSTEM_DEFAULT -> nestedScrollWebView.ultraListEnabled = defaultUltraList
3437 ENABLED -> nestedScrollWebView.ultraListEnabled = true
3438 DISABLED -> nestedScrollWebView.ultraListEnabled = false
3441 // Set the UltraPrivacy status.
3442 when (ultraPrivacyInt) {
3443 SYSTEM_DEFAULT -> nestedScrollWebView.ultraPrivacyEnabled = defaultUltraPrivacy
3444 ENABLED -> nestedScrollWebView.ultraPrivacyEnabled = true
3445 DISABLED -> nestedScrollWebView.ultraPrivacyEnabled = false
3448 // Set the block all third-party requests status.
3449 when (blockAllThirdPartyRequestsInt) {
3450 SYSTEM_DEFAULT -> nestedScrollWebView.blockAllThirdPartyRequests = defaultBlockAllThirdPartyRequests
3451 ENABLED -> nestedScrollWebView.blockAllThirdPartyRequests = true
3452 DISABLED -> nestedScrollWebView.blockAllThirdPartyRequests = false
3455 // Set the user agent.
3456 if (userAgentName == getString(R.string.system_default_user_agent)) { // Use the system default user agent.
3457 // Set the user agent according to the system default.
3458 when (val defaultUserAgentArrayPosition = userAgentNamesArrayAdapter.getPosition(defaultUserAgentName)) {
3459 UNRECOGNIZED_USER_AGENT -> // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3460 nestedScrollWebView.settings.userAgentString = defaultUserAgentName
3462 SETTINGS_WEBVIEW_DEFAULT_USER_AGENT -> // Set the user agent to `""`, which uses the default value.
3463 nestedScrollWebView.settings.userAgentString = ""
3465 SETTINGS_CUSTOM_USER_AGENT -> // Set the default custom user agent.
3466 nestedScrollWebView.settings.userAgentString = sharedPreferences.getString(getString(R.string.custom_user_agent_key), getString(R.string.custom_user_agent_default_value))
3468 else -> // Get the user agent string from the user agent data array
3469 nestedScrollWebView.settings.userAgentString = userAgentDataArray[defaultUserAgentArrayPosition]
3471 } else { // Set the user agent according to the stored name.
3472 // Set the user agent.
3473 when (val userAgentArrayPosition = userAgentNamesArrayAdapter.getPosition(userAgentName)) {
3474 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3475 UNRECOGNIZED_USER_AGENT ->
3476 nestedScrollWebView.settings.userAgentString = userAgentName
3478 // Set the user agent to `""`, which uses the default value.
3479 SETTINGS_WEBVIEW_DEFAULT_USER_AGENT ->
3480 nestedScrollWebView.settings.userAgentString = ""
3482 // Get the user agent string from the user agent data array.
3484 nestedScrollWebView.settings.userAgentString = userAgentDataArray[userAgentArrayPosition]
3488 // Apply the font size.
3489 try { // Try the specified font size to see if it is valid.
3490 if (fontSize == 0) { // Apply the default font size.
3491 // Set the font size from the value in the app settings.
3492 nestedScrollWebView.settings.textZoom = defaultFontSizeString.toInt()
3493 } else { // Apply the font size from domain settings.
3494 nestedScrollWebView.settings.textZoom = fontSize
3496 } catch (exception: Exception) { // The specified font size is invalid
3497 // Set the font size to be 100%
3498 nestedScrollWebView.settings.textZoom = 100
3501 // Set swipe to refresh.
3502 when (swipeToRefreshInt) {
3504 // Store the swipe to refresh status in the nested scroll WebView.
3505 nestedScrollWebView.swipeToRefresh = defaultSwipeToRefresh
3507 // Update the swipe refresh layout.
3508 if (defaultSwipeToRefresh) { // Swipe to refresh is enabled.
3509 // Update the status of the swipe refresh layout if the current WebView is not null (crash reports indicate that in some unexpected way it sometimes is null).
3510 if (currentWebView != null) {
3511 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
3512 swipeRefreshLayout.isEnabled = (currentWebView!!.scrollY == 0)
3514 } else { // Swipe to refresh is disabled.
3515 // Disable the swipe refresh layout.
3516 swipeRefreshLayout.isEnabled = false
3521 // Store the swipe to refresh status in the nested scroll WebView.
3522 nestedScrollWebView.swipeToRefresh = true
3524 // Update the status of the swipe refresh layout if the current WebView is not null (crash reports indicate that in some unexpected way it sometimes is null).
3525 if (currentWebView != null) {
3526 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
3527 swipeRefreshLayout.isEnabled = (currentWebView!!.scrollY == 0)
3532 // Store the swipe to refresh status in the nested scroll WebView.
3533 nestedScrollWebView.swipeToRefresh = false
3535 // Disable swipe to refresh.
3536 swipeRefreshLayout.isEnabled = false
3540 // Set the WebView theme if algorithmic darkening is supported.
3541 if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {
3542 // Set the WebView theme.
3543 when (webViewThemeInt) {
3544 SYSTEM_DEFAULT -> // Set the WebView theme.
3545 when (defaultWebViewTheme) {
3546 webViewThemeEntryValuesStringArray[1] -> // The light theme is selected. Turn off algorithmic darkening.
3547 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
3549 webViewThemeEntryValuesStringArray[2] -> // The dark theme is selected. Turn on algorithmic darkening.
3550 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
3552 else -> { // The system default theme is selected.
3553 // Get the current system theme status.
3554 val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
3556 // Set the algorithmic darkening according to the current system theme status.
3557 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, currentThemeStatus == Configuration.UI_MODE_NIGHT_YES)
3561 LIGHT_THEME -> // Turn off algorithmic darkening.
3562 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
3564 DARK_THEME -> // Turn on algorithmic darkening.
3565 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
3569 // Set the wide viewport status.
3570 when (wideViewportInt) {
3571 SYSTEM_DEFAULT -> nestedScrollWebView.settings.useWideViewPort = defaultWideViewport
3572 ENABLED -> nestedScrollWebView.settings.useWideViewPort = true
3573 DISABLED -> nestedScrollWebView.settings.useWideViewPort = false
3576 // Set the display webpage images status.
3577 when (displayWebpageImagesInt) {
3578 SYSTEM_DEFAULT -> nestedScrollWebView.settings.loadsImagesAutomatically = defaultDisplayWebpageImages
3579 ENABLED -> nestedScrollWebView.settings.loadsImagesAutomatically = true
3580 DISABLED -> nestedScrollWebView.settings.loadsImagesAutomatically = false
3583 // If there is a pinned SSL certificate, store it in the WebView.
3584 if (pinnedSslCertificate)
3585 nestedScrollWebView.setPinnedSslCertificate(pinnedSslIssuedToCName, pinnedSslIssuedToOName, pinnedSslIssuedToUName, pinnedSslIssuedByCName, pinnedSslIssuedByOName, pinnedSslIssuedByUName,
3586 pinnedSslStartDate, pinnedSslEndDate)
3588 // If there is a pinned IP address, store it in the WebView.
3589 if (pinnedIpAddresses)
3590 nestedScrollWebView.pinnedIpAddresses = pinnedHostIpAddresses
3592 // Set a background on the URL relative layout to indicate that custom domain settings are being used.
3593 urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.drawable.domain_settings_url_background)
3594 } else { // The new URL does not have custom domain settings. Load the defaults.
3595 // Store the values from the shared preferences.
3596 nestedScrollWebView.settings.javaScriptEnabled = defaultJavaScript
3597 nestedScrollWebView.acceptCookies = defaultCookies
3598 nestedScrollWebView.settings.domStorageEnabled = defaultDomStorage
3599 nestedScrollWebView.easyListEnabled = defaultEasyList
3600 nestedScrollWebView.easyPrivacyEnabled = defaultEasyPrivacy
3601 nestedScrollWebView.fanboysAnnoyanceListEnabled = defaultFanboysAnnoyanceList
3602 nestedScrollWebView.fanboysSocialBlockingListEnabled = defaultFanboysSocialBlockingList
3603 nestedScrollWebView.ultraListEnabled = defaultUltraList
3604 nestedScrollWebView.ultraPrivacyEnabled = defaultUltraPrivacy
3605 nestedScrollWebView.blockAllThirdPartyRequests = defaultBlockAllThirdPartyRequests
3607 // Apply the default cookie setting.
3608 cookieManager.setAcceptCookie(nestedScrollWebView.acceptCookies)
3610 // Apply the form data setting if the API < 26.
3611 if (Build.VERSION.SDK_INT < 26)
3612 @Suppress("DEPRECATION")
3613 nestedScrollWebView.settings.saveFormData = defaultFormData
3615 // Apply the default font size setting.
3617 // Try to set the font size from the value in the app settings.
3618 nestedScrollWebView.settings.textZoom = defaultFontSizeString.toInt()
3619 } catch (exception: Exception) {
3620 // If the app settings value is invalid, set the font size to 100%.
3621 nestedScrollWebView.settings.textZoom = 100
3624 // Store the swipe to refresh status in the nested scroll WebView.
3625 nestedScrollWebView.swipeToRefresh = defaultSwipeToRefresh
3627 // Update the swipe refresh layout.
3628 if (defaultSwipeToRefresh) { // Swipe to refresh is enabled.
3629 // Update the status of the swipe refresh layout if the current WebView is not null (crash reports indicate that in some unexpected way it sometimes is null).
3630 if (currentWebView != null) {
3631 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
3632 swipeRefreshLayout.isEnabled = currentWebView!!.scrollY == 0
3634 } else { // Swipe to refresh is disabled.
3635 // Disable the swipe refresh layout.
3636 swipeRefreshLayout.isEnabled = false
3639 // Reset the domain settings database ID.
3640 nestedScrollWebView.domainSettingsDatabaseId = -1
3642 // Set the user agent.
3643 when (val userAgentArrayPosition = userAgentNamesArrayAdapter.getPosition(defaultUserAgentName)) {
3644 UNRECOGNIZED_USER_AGENT -> // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3645 nestedScrollWebView.settings.userAgentString = defaultUserAgentName
3647 SETTINGS_WEBVIEW_DEFAULT_USER_AGENT -> // Set the user agent to `""`, which uses the default value.
3648 nestedScrollWebView.settings.userAgentString = ""
3650 SETTINGS_CUSTOM_USER_AGENT -> // Set the default custom user agent.
3651 nestedScrollWebView.settings.userAgentString = sharedPreferences.getString(getString(R.string.custom_user_agent_key), getString(R.string.custom_user_agent_default_value))
3653 else -> // Get the user agent string from the user agent data array
3654 nestedScrollWebView.settings.userAgentString = userAgentDataArray[userAgentArrayPosition]
3657 // Set the WebView theme if algorithmic darkening is supported.
3658 if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {
3659 // Set the WebView theme.
3660 when (defaultWebViewTheme) {
3661 webViewThemeEntryValuesStringArray[1] -> // The light theme is selected. Turn off algorithmic darkening.
3662 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
3664 webViewThemeEntryValuesStringArray[2] -> // The dark theme is selected. Turn on algorithmic darkening.
3665 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
3667 else -> { // The system default theme is selected. Get the current system theme status.
3668 // Get the current theme status.
3669 val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
3671 // Set the algorithmic darkening according to the current system theme status.
3672 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, currentThemeStatus == Configuration.UI_MODE_NIGHT_YES)
3677 // Set the viewport.
3678 nestedScrollWebView.settings.useWideViewPort = defaultWideViewport
3680 // Set the loading of webpage images.
3681 nestedScrollWebView.settings.loadsImagesAutomatically = defaultDisplayWebpageImages
3683 // Set a transparent background on the URL relative layout.
3684 urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.color.transparent)
3687 // Update the privacy icons.
3688 updatePrivacyIcons(true)
3691 // Reload the website if returning from the Domains activity.
3693 nestedScrollWebView.reload()
3695 // Disable the wide viewport if the source is being viewed.
3696 if (url.startsWith("view-source:"))
3697 nestedScrollWebView.settings.useWideViewPort = false
3699 // Load the URL if directed. This makes sure that the domain settings are properly loaded before the URL. By using `loadUrl()`, instead of `loadUrlFromBase()`, the Referer header will never be sent.
3701 nestedScrollWebView.loadUrl(url)
3704 private fun applyProxy(reloadWebViews: Boolean) {
3705 // Set the proxy according to the mode.
3706 proxyHelper.setProxy(applicationContext, appBarLayout, proxyMode)
3708 // Reset the waiting for proxy tracker.
3709 waitingForProxy = false
3713 ProxyHelper.NONE -> {
3714 // Initialize a color background typed value.
3715 val colorBackgroundTypedValue = TypedValue()
3717 // Get the color background from the theme.
3718 theme.resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true)
3720 // Get the color background int from the typed value.
3721 val colorBackgroundInt = colorBackgroundTypedValue.data
3723 // Set the default app bar layout background.
3724 appBarLayout.setBackgroundColor(colorBackgroundInt)
3727 ProxyHelper.TOR -> {
3728 // Set the app bar background to indicate proxying is enabled.
3729 appBarLayout.setBackgroundResource(R.color.blue_background)
3731 // Check to see if Orbot is installed.
3733 // Get the package manager.
3734 val packageManager = packageManager
3736 // Check to see if Orbot is in the list. This will throw an error and drop to the catch section if it isn't installed.
3737 packageManager.getPackageInfo("org.torproject.android", 0)
3739 // Check to see if the proxy is ready.
3740 if (orbotStatus != ProxyHelper.ORBOT_STATUS_ON) { // Orbot is not ready.
3741 // Set the waiting for proxy status.
3742 waitingForProxy = true
3744 // Show the waiting for proxy dialog if it isn't already displayed.
3745 if (supportFragmentManager.findFragmentByTag(getString(R.string.waiting_for_proxy_dialog)) == null) {
3746 // Get a handle for the waiting for proxy alert dialog.
3747 val waitingForProxyDialogFragment = WaitingForProxyDialog()
3749 // Try to show the dialog. Sometimes the window is not yet active if returning from Settings.
3751 // Show the waiting for proxy alert dialog.
3752 waitingForProxyDialogFragment.show(supportFragmentManager, getString(R.string.waiting_for_proxy_dialog))
3753 } catch (waitingForTorException: Exception) {
3754 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
3755 pendingDialogsArrayList.add(PendingDialogDataClass(waitingForProxyDialogFragment, getString(R.string.waiting_for_proxy_dialog)))
3759 } catch (exception: PackageManager.NameNotFoundException) { // Orbot is not installed.
3760 // Show the Orbot not installed dialog if it is not already displayed.
3761 if (supportFragmentManager.findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
3762 // Get a handle for the Orbot not installed alert dialog.
3763 val orbotNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode)
3765 // Try to show the dialog. Sometimes the window is not yet active if returning from Settings.
3767 // Display the Orbot not installed alert dialog.
3768 orbotNotInstalledDialogFragment.show(supportFragmentManager, getString(R.string.proxy_not_installed_dialog))
3769 } catch (orbotNotInstalledException: Exception) {
3770 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
3771 pendingDialogsArrayList.add(PendingDialogDataClass(orbotNotInstalledDialogFragment, getString(R.string.proxy_not_installed_dialog)))
3777 ProxyHelper.I2P -> {
3778 // Set the app bar background to indicate proxying is enabled.
3779 appBarLayout.setBackgroundResource(R.color.blue_background)
3781 // Check to see if I2P is installed.
3783 // Check to see if the F-Droid flavor is installed. This will throw an error and drop to the catch section if it isn't installed.
3784 packageManager.getPackageInfo("net.i2p.android.router", 0)
3785 } catch (fdroidException: PackageManager.NameNotFoundException) { // The F-Droid flavor is not installed.
3787 // Check to see if the Google Play flavor is installed. This will throw an error and drop to the catch section if it isn't installed.
3788 packageManager.getPackageInfo("net.i2p.android", 0)
3789 } catch (googlePlayException: PackageManager.NameNotFoundException) { // The Google Play flavor is not installed.
3790 // Sow the I2P not installed dialog if it is not already displayed.
3791 if (supportFragmentManager.findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
3792 // Get a handle for the waiting for proxy alert dialog.
3793 val i2pNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode)
3795 // Try to show the dialog. Sometimes the window is not yet active if returning from Settings.
3797 // Display the I2P not installed alert dialog.
3798 i2pNotInstalledDialogFragment.show(supportFragmentManager, getString(R.string.proxy_not_installed_dialog))
3799 } catch (i2pNotInstalledException: Exception) {
3800 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
3801 pendingDialogsArrayList.add(PendingDialogDataClass(i2pNotInstalledDialogFragment, getString(R.string.proxy_not_installed_dialog)))
3808 ProxyHelper.CUSTOM ->
3809 // Set the app bar background to indicate proxying is enabled.
3810 appBarLayout.setBackgroundResource(R.color.blue_background)
3813 // Reload the WebViews if requested and not waiting for the proxy.
3814 if (reloadWebViews && !waitingForProxy) {
3815 // Reload the WebViews.
3816 for (i in 0 until webViewStateAdapter!!.itemCount) {
3817 // Get the WebView tab fragment.
3818 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
3820 // Get the fragment view.
3821 val fragmentView = webViewTabFragment.view
3823 // Only reload the WebViews if they exist.
3824 if (fragmentView != null) {
3825 // Get the nested scroll WebView from the tab fragment.
3826 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
3828 // Reload the WebView.
3829 nestedScrollWebView.reload()
3835 // The view parameter cannot be removed because it is called from the layout onClick.
3836 fun bookmarksBack(@Suppress("UNUSED_PARAMETER")view: View?) {
3837 if (currentBookmarksFolderId == HOME_FOLDER_ID) { // The home folder is displayed.
3838 // close the bookmarks drawer.
3839 drawerLayout.closeDrawer(GravityCompat.END)
3840 } else { // A subfolder is displayed.
3841 // Set the former parent folder as the current folder.
3842 currentBookmarksFolderId = bookmarksDatabaseHelper!!.getParentFolderId(currentBookmarksFolderId)
3844 // Load the new folder.
3845 loadBookmarksFolder()
3849 private fun calculateSettingsInt(settingCurrentlyEnabled: Boolean, settingEnabledByDefault: Boolean): Int {
3850 return if (settingCurrentlyEnabled == settingEnabledByDefault) // The current system default is used.
3852 else if (settingCurrentlyEnabled) // The setting is enabled, which is different from the system default.
3854 else // The setting is disabled, which is different from the system default.
3858 private fun clearAndExit() {
3859 // Close the bookmarks cursor if it exists.
3860 bookmarksCursor?.close()
3862 // Close the databases helpers if they exist.
3863 bookmarksDatabaseHelper?.close()
3864 domainsDatabaseHelper?.close()
3866 // Get the status of the clear everything preference.
3867 val clearEverything = sharedPreferences.getBoolean(getString(R.string.clear_everything_key), true)
3869 // Get a handle for the runtime.
3870 val runtime = Runtime.getRuntime()
3872 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
3873 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
3874 val privateDataDirectoryString = applicationInfo.dataDir
3877 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_cookies_key), true)) {
3878 // Ass the cookie manager to delete all the cookies.
3879 cookieManager.removeAllCookies(null)
3881 // Ask the cookie manager to flush the cookie database.
3882 cookieManager.flush()
3884 // Manually delete the cookies database, as the cookie manager sometimes will not flush its changes to disk before system exit is run.
3886 // Two commands must be used because `Runtime.exec()` does not like `*`.
3887 val deleteCookiesProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/Cookies")
3888 val deleteCookiesJournalProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/Cookies-journal")
3890 // Wait until the processes have finished.
3891 deleteCookiesProcess.waitFor()
3892 deleteCookiesJournalProcess.waitFor()
3893 } catch (exception: Exception) {
3894 // Do nothing if an error is thrown.
3898 // Clear DOM storage.
3899 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_dom_storage_key), true)) {
3900 // Ask web storage to clear the DOM storage.
3901 WebStorage.getInstance().deleteAllData()
3903 // Manually delete the DOM storage files and directories, as web storage sometimes will not flush its changes to disk before system exit is run.
3905 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
3906 val deleteLocalStorageProcess = runtime.exec(arrayOf("rm", "-rf", "$privateDataDirectoryString/app_webview/Local Storage/"))
3908 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
3909 val deleteIndexProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview/IndexedDB")
3910 val deleteQuotaManagerProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/QuotaManager")
3911 val deleteQuotaManagerJournalProcess = runtime.exec("rm -f $privateDataDirectoryString/app_webview/QuotaManager-journal")
3912 val deleteDatabaseProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview/databases")
3914 // Wait until the processes have finished.
3915 deleteLocalStorageProcess.waitFor()
3916 deleteIndexProcess.waitFor()
3917 deleteQuotaManagerProcess.waitFor()
3918 deleteQuotaManagerJournalProcess.waitFor()
3919 deleteDatabaseProcess.waitFor()
3920 } catch (exception: Exception) {
3921 // Do nothing if an error is thrown.
3925 // Clear form data if the API < 26.
3926 if (Build.VERSION.SDK_INT < 26 && (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_form_data_key), true))) {
3927 // Ask the WebView database to clear the form data.
3928 @Suppress("DEPRECATION")
3929 WebViewDatabase.getInstance(this).clearFormData()
3931 // Manually delete the form data database, as the WebView database sometimes will not flush its changes to disk before system exit is run.
3933 // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
3934 val deleteWebDataProcess = runtime.exec(arrayOf("rm", "-f", "$privateDataDirectoryString/app_webview/Web Data"))
3935 val deleteWebDataJournalProcess = runtime.exec(arrayOf("rm", "-f", "$privateDataDirectoryString/app_webview/Web Data-journal"))
3937 // Wait until the processes have finished.
3938 deleteWebDataProcess.waitFor()
3939 deleteWebDataJournalProcess.waitFor()
3940 } catch (exception: Exception) {
3941 // Do nothing if an error is thrown.
3945 // Clear the logcat.
3946 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_logcat_key), true)) {
3948 // Clear the logcat. `-c` clears the logcat. `-b all` clears all the buffers (instead of just crash, main, and system).
3949 val process = Runtime.getRuntime().exec("logcat -b all -c")
3951 // Wait for the process to finish.
3953 } catch (exception: IOException) {
3955 } catch (exception: InterruptedException) {
3961 if (clearEverything || sharedPreferences.getBoolean(getString(R.string.clear_cache_key), true)) {
3962 // Clear the cache from each WebView.
3963 for (i in 0 until webViewStateAdapter!!.itemCount) {
3964 // Get the WebView tab fragment.
3965 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
3967 // Get the WebView fragment view.
3968 val webViewFragmentView = webViewTabFragment.view
3970 // Only clear the cache if the WebView exists.
3971 if (webViewFragmentView != null) {
3972 // Get the nested scroll WebView from the tab fragment.
3973 val nestedScrollWebView = webViewFragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
3975 // Clear the cache for this WebView.
3976 nestedScrollWebView.clearCache(true)
3980 // Manually delete the cache directories.
3982 // Delete the main cache directory.
3983 val deleteCacheProcess = runtime.exec("rm -rf $privateDataDirectoryString/cache")
3985 // Delete the secondary `Service Worker` cache directory.
3986 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
3987 val deleteServiceWorkerProcess = runtime.exec(arrayOf("rm", "-rf", "$privateDataDirectoryString/app_webview/Default/Service Worker/"))
3989 // Wait until the processes have finished.
3990 deleteCacheProcess.waitFor()
3991 deleteServiceWorkerProcess.waitFor()
3992 } catch (exception: Exception) {
3993 // Do nothing if an error is thrown.
3997 // Wipe out each WebView.
3998 for (i in 0 until webViewStateAdapter!!.itemCount) {
3999 // Get the WebView tab fragment.
4000 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
4002 // Get the WebView frame layout.
4003 val webViewFrameLayout = webViewTabFragment.view as FrameLayout?
4005 // Only wipe out the WebView if it exists.
4006 if (webViewFrameLayout != null) {
4007 // Get the nested scroll WebView from the tab fragment.
4008 val nestedScrollWebView = webViewFrameLayout.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
4010 // Clear SSL certificate preferences for this WebView.
4011 nestedScrollWebView.clearSslPreferences()
4013 // Clear the back/forward history for this WebView.
4014 nestedScrollWebView.clearHistory()
4016 // Remove all the views from the frame layout.
4017 webViewFrameLayout.removeAllViews()
4019 // Destroy the internal state of the WebView.
4020 nestedScrollWebView.destroy()
4024 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
4025 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
4026 if (clearEverything) {
4028 // Delete the folder.
4029 val deleteAppWebviewProcess = runtime.exec("rm -rf $privateDataDirectoryString/app_webview")
4031 // Wait until the process has finished.
4032 deleteAppWebviewProcess.waitFor()
4033 } catch (exception: Exception) {
4034 // Do nothing if an error is thrown.
4038 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
4039 finishAndRemoveTask()
4041 // Remove the terminated program from RAM. The status code is `0`.
4045 // The view parameter cannot be removed because it is called from the layout onClick.
4046 fun closeFindOnPage(@Suppress("UNUSED_PARAMETER")view: View?) {
4047 // Delete the contents of the find on page edit text.
4048 findOnPageEditText.text = null
4050 // Clear the highlighted phrases if the WebView is not null.
4051 currentWebView?.clearMatches()
4053 // Hide the find on page linear layout.
4054 findOnPageLinearLayout.visibility = View.GONE
4056 // Show the toolbar.
4057 toolbar.visibility = View.VISIBLE
4059 // Get a handle for the input method manager.
4060 val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
4062 // Hide the keyboard.
4063 inputMethodManager.hideSoftInputFromWindow(toolbar.windowToken, 0)
4066 // The view parameter cannot be removed because it is called from the layout onClick.
4067 fun closeTab(@Suppress("UNUSED_PARAMETER")view: View?) {
4068 // Run the command according to the number of tabs.
4069 if (tabLayout.tabCount > 1) { // There is more than one tab open.
4070 // Get the current tab number.
4071 val currentTabNumber = tabLayout.selectedTabPosition
4073 // Delete the current tab.
4074 tabLayout.removeTabAt(currentTabNumber)
4076 // Delete the current page. If the selected page number did not change during the delete (because the newly selected tab has has same number as the previously deleted tab), it will return true,
4077 // meaning that the current WebView must be reset. Otherwise it will happen automatically as the selected tab number changes.
4078 if (webViewStateAdapter!!.deletePage(currentTabNumber, webViewViewPager2))
4079 setCurrentWebView(currentTabNumber)
4080 } else { // There is only one tab open.
4085 override fun createBookmark(dialogFragment: DialogFragment, favoriteIconBitmap: Bitmap) {
4087 val dialog = dialogFragment.dialog!!
4089 // Get the views from the dialog fragment.
4090 val createBookmarkNameEditText = dialog.findViewById<EditText>(R.id.create_bookmark_name_edittext)
4091 val createBookmarkUrlEditText = dialog.findViewById<EditText>(R.id.create_bookmark_url_edittext)
4093 // Extract the strings from the edit texts.
4094 val bookmarkNameString = createBookmarkNameEditText.text.toString()
4095 val bookmarkUrlString = createBookmarkUrlEditText.text.toString()
4097 // Create a favorite icon byte array output stream.
4098 val favoriteIconByteArrayOutputStream = ByteArrayOutputStream()
4100 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
4101 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream)
4103 // Convert the favorite icon byte array stream to a byte array.
4104 val favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray()
4106 // Display the new bookmark below the current items in the (0 indexed) list.
4107 val newBookmarkDisplayOrder = bookmarksListView.count
4109 // Create the bookmark.
4110 bookmarksDatabaseHelper!!.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolderId, newBookmarkDisplayOrder, favoriteIconByteArray)
4112 // Update the bookmarks cursor with the current contents of this folder.
4113 bookmarksCursor = bookmarksDatabaseHelper!!.getBookmarksByDisplayOrder(currentBookmarksFolderId)
4115 // Update the list view.
4116 bookmarksCursorAdapter.changeCursor(bookmarksCursor)
4118 // Scroll to the new bookmark.
4119 bookmarksListView.setSelection(newBookmarkDisplayOrder)
4122 override fun createBookmarkFolder(dialogFragment: DialogFragment, favoriteIconBitmap: Bitmap) {
4124 val dialog = dialogFragment.dialog!!
4126 // Get handles for the views in the dialog fragment.
4127 val folderNameEditText = dialog.findViewById<EditText>(R.id.folder_name_edittext)
4128 val defaultIconRadioButton = dialog.findViewById<RadioButton>(R.id.default_icon_radiobutton)
4129 val defaultIconImageView = dialog.findViewById<ImageView>(R.id.default_icon_imageview)
4131 // Get new folder name string.
4132 val folderNameString = folderNameEditText.text.toString()
4134 // Set the folder icon bitmap according to the dialog.
4135 val folderIconBitmap: Bitmap = if (defaultIconRadioButton.isChecked) { // Use the default folder icon.
4136 // Get the default folder icon drawable.
4137 val folderIconDrawable = defaultIconImageView.drawable
4139 // Convert the folder icon drawable to a bitmap drawable.
4140 val folderIconBitmapDrawable = folderIconDrawable as BitmapDrawable
4142 // Convert the folder icon bitmap drawable to a bitmap.
4143 folderIconBitmapDrawable.bitmap
4144 } else { // Use the WebView favorite icon.
4145 // Copy the favorite icon bitmap to the folder icon bitmap.
4149 // Create a folder icon byte array output stream.
4150 val folderIconByteArrayOutputStream = ByteArrayOutputStream()
4152 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
4153 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream)
4155 // Convert the folder icon byte array stream to a byte array.
4156 val folderIconByteArray = folderIconByteArrayOutputStream.toByteArray()
4158 // Move all the bookmarks down one in the display order.
4159 for (i in 0 until bookmarksListView.count) {
4160 // Get the bookmark database id.
4161 val databaseId = bookmarksListView.getItemIdAtPosition(i).toInt()
4163 // Move the bookmark down one slot.
4164 bookmarksDatabaseHelper!!.updateDisplayOrder(databaseId, displayOrder = i + 1)
4167 // Create the folder, which will be placed at the top of the list view.
4168 bookmarksDatabaseHelper!!.createFolder(folderNameString, currentBookmarksFolderId, displayOrder = 0, folderIconByteArray)
4170 // Update the bookmarks cursor with the current contents of this folder.
4171 bookmarksCursor = bookmarksDatabaseHelper!!.getBookmarksByDisplayOrder(currentBookmarksFolderId)
4173 // Update the list view.
4174 bookmarksCursorAdapter.changeCursor(bookmarksCursor)
4176 // Scroll to the new folder.
4177 bookmarksListView.setSelection(0)
4180 private fun exitFullScreenVideo() {
4181 // Re-enable the screen timeout.
4182 fullScreenVideoFrameLayout.keepScreenOn = false
4184 // Unset the full screen video flag.
4185 displayingFullScreenVideo = false
4187 // Remove all the views from the full screen video frame layout.
4188 fullScreenVideoFrameLayout.removeAllViews()
4190 // Hide the full screen video frame layout.
4191 fullScreenVideoFrameLayout.visibility = View.GONE
4193 // Enable the sliding drawers.
4194 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED)
4196 // Show the coordinator layout.
4197 coordinatorLayout.visibility = View.VISIBLE
4199 // Apply the appropriate full screen mode flags.
4200 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
4201 // Hide the app bar if specified.
4203 // Hide the tab linear layout.
4204 tabsLinearLayout.visibility = View.GONE
4206 // Hide the app bar.
4210 /* Hide the system bars.
4211 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4212 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4213 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4214 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4217 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4218 @Suppress("DEPRECATION")
4219 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
4220 } else { // Switch to normal viewing mode.
4221 // Remove the `SYSTEM_UI` flags from the root frame layout. The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4222 @Suppress("DEPRECATION")
4223 rootFrameLayout.systemUiVisibility = 0
4227 // The view parameter cannot be removed because it is called from the layout onClick.
4228 fun findNextOnPage(@Suppress("UNUSED_PARAMETER")view: View?) {
4229 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
4230 currentWebView!!.findNext(true)
4233 // The view parameter cannot be removed because it is called from the layout onClick.
4234 fun findPreviousOnPage(@Suppress("UNUSED_PARAMETER")view: View?) {
4235 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
4236 currentWebView!!.findNext(false)
4239 override fun finishedPopulatingFilterLists(combinedFilterLists: ArrayList<ArrayList<List<Array<String>>>>) {
4240 // Store the filter lists.
4241 easyList = combinedFilterLists[0]
4242 easyPrivacy = combinedFilterLists[1]
4243 fanboysAnnoyanceList = combinedFilterLists[2]
4244 fanboysSocialList = combinedFilterLists[3]
4245 ultraList = combinedFilterLists[4]
4246 ultraPrivacy = combinedFilterLists[5]
4248 // Check to see if the activity has been restarted with a saved state.
4249 if ((savedStateArrayList == null) || (savedStateArrayList!!.size == 0)) { // The activity has not been restarted or it was restarted on start to change the theme.
4250 // Add the first tab.
4251 addNewPage(urlString = "", adjacent = false, moveToTab = false)
4252 } else { // The activity has been restarted with a saved state.
4253 // Restore each tab.
4254 for (i in savedStateArrayList!!.indices) {
4256 tabLayout.addTab(tabLayout.newTab())
4259 val newTab = tabLayout.getTabAt(i)!!
4261 // Set a custom view on the new tab.
4262 newTab.setCustomView(R.layout.tab_custom_view)
4264 // Add the new page.
4265 webViewStateAdapter!!.restorePage(savedStateArrayList!![i], savedNestedScrollWebViewStateArrayList!![i])
4268 // Reset the saved state variables.
4269 savedStateArrayList = null
4270 savedNestedScrollWebViewStateArrayList = null
4272 // Get the intent that started the app.
4275 // Reset the intent. This prevents a duplicate tab from being created on restart.
4278 // Get the information from the intent.
4279 val intentAction = intent.action
4280 val intentUriData = intent.data
4281 val intentStringExtra = intent.getStringExtra(Intent.EXTRA_TEXT)
4283 // Determine if this is a web search.
4284 val isWebSearch = (intentAction != null) && (intentAction == Intent.ACTION_WEB_SEARCH)
4286 // 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.
4287 if ((intentUriData != null) || (intentStringExtra != null) || isWebSearch) { // A new tab is being loaded.
4288 // Get the URL string.
4289 val urlString = if (isWebSearch) { // The intent is a web search.
4290 // Sanitize the search input.
4291 val encodedSearchString: String = try {
4292 URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8")
4293 } catch (exception: UnsupportedEncodingException) {
4297 // Add the base search URL.
4298 searchURL + encodedSearchString
4299 } else { // The intent contains a URL formatted as a URI or a URL in the string extra.
4300 // Get the URL string.
4301 intentUriData?.toString() ?: intentStringExtra!!
4304 // Add a new tab if specified in the preferences.
4305 if (sharedPreferences.getBoolean(getString(R.string.open_intents_in_new_tab_key), true)) { // Load the URL in a new tab.
4306 // Set the loading new intent flag.
4307 loadingNewIntent = true
4310 addNewPage(urlString, adjacent = false, moveToTab = true)
4311 } else { // Load the URL in the current tab.
4313 loadUrl(currentWebView!!, urlString)
4315 } else { // A new tab is not being loaded.
4316 // Restore the selected tab position.
4317 if (savedTabPosition == 0) { // The first tab is selected.
4318 // Set the first page as the current WebView.
4319 setCurrentWebView(0)
4320 } else { // The first tab is not selected.
4321 // Select the tab when the layout has finished populating.
4323 // Get a handle for the tab.
4324 val tab = tabLayout.getTabAt(savedTabPosition)!!
4334 // Remove the warning that `OnTouchListener()` needs to override `performClick()`, as the only purpose of setting the `OnTouchListener()` is to make it do nothing.
4335 @SuppressLint("ClickableViewAccessibility")
4336 private fun initializeApp() {
4337 // Get a handle for the input method.
4338 val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
4340 // Initialize the color spans for highlighting the URLs.
4341 initialGrayColorSpan = ForegroundColorSpan(getColor(R.color.gray_500))
4342 finalGrayColorSpan = ForegroundColorSpan(getColor(R.color.gray_500))
4343 redColorSpan = ForegroundColorSpan(getColor(R.color.red_text))
4345 // Remove the formatting from the URL edit text when the user is editing the text.
4346 urlEditText.onFocusChangeListener = View.OnFocusChangeListener { _: View?, hasFocus: Boolean ->
4347 if (hasFocus) { // The user is editing the URL text box.
4348 // Remove the syntax highlighting.
4349 urlEditText.text.removeSpan(redColorSpan)
4350 urlEditText.text.removeSpan(initialGrayColorSpan)
4351 urlEditText.text.removeSpan(finalGrayColorSpan)
4352 } else { // The user has stopped editing the URL text box.
4353 // Move to the beginning of the string.
4354 urlEditText.setSelection(0)
4356 // Reapply the syntax highlighting.
4357 UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
4361 // Set the go button on the keyboard to load the URL in url text box.
4362 urlEditText.setOnKeyListener { _: View?, keyCode: Int, keyEvent: KeyEvent ->
4363 // If the event is a key-down event on the `enter` button, load the URL.
4364 if ((keyEvent.action == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The enter key was pressed.
4366 loadUrlFromTextBox()
4368 // Consume the event.
4369 return@setOnKeyListener true
4370 } else { // Some other key was pressed.
4371 // Do not consume the event.
4372 return@setOnKeyListener false
4376 // Create an Orbot status broadcast receiver.
4377 orbotStatusBroadcastReceiver = object : BroadcastReceiver() {
4378 override fun onReceive(context: Context, intent: Intent) {
4379 // Get the content of the status message.
4380 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS")!!
4382 // If Privacy Browser is waiting on the proxy, load the website now that Orbot is connected.
4383 if ((orbotStatus == ProxyHelper.ORBOT_STATUS_ON) && waitingForProxy) {
4384 // Reset the waiting for proxy status.
4385 waitingForProxy = false
4387 // Get a list of the current fragments.
4388 val fragmentList = supportFragmentManager.fragments
4390 // Check each fragment to see if it is a waiting for proxy dialog. Sometimes more than one is displayed.
4391 for (i in fragmentList.indices) {
4392 // Get the fragment tag.
4393 val fragmentTag = fragmentList[i].tag
4395 // Check to see if it is the waiting for proxy dialog.
4396 if (fragmentTag != null && fragmentTag == getString(R.string.waiting_for_proxy_dialog)) {
4397 // Dismiss the waiting for proxy dialog.
4398 (fragmentList[i] as DialogFragment).dismiss()
4402 // Reload existing URLs and load any URLs that are waiting for the proxy.
4403 for (i in 0 until webViewStateAdapter!!.itemCount) {
4404 // Get the WebView tab fragment.
4405 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(i)
4407 // Get the fragment view.
4408 val fragmentView = webViewTabFragment.view
4410 // Only process the WebViews if they exist.
4411 if (fragmentView != null) {
4412 // Get the nested scroll WebView from the tab fragment.
4413 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
4415 // Get the waiting for proxy URL string.
4416 val waitingForProxyUrlString = nestedScrollWebView.waitingForProxyUrlString
4418 // Load the pending URL if it exists.
4419 if (waitingForProxyUrlString.isNotEmpty()) { // A URL is waiting to be loaded.
4421 loadUrl(nestedScrollWebView, waitingForProxyUrlString)
4423 // Reset the waiting for proxy URL string.
4424 nestedScrollWebView.waitingForProxyUrlString = ""
4425 } else { // No URL is waiting to be loaded.
4426 // Reload the existing URL.
4427 nestedScrollWebView.reload()
4435 // Register the Orbot status broadcast receiver. `ContextCompat` must be used until the minimum API >= 34.
4436 ContextCompat.registerReceiver(this, orbotStatusBroadcastReceiver, IntentFilter("org.torproject.android.intent.action.STATUS"), ContextCompat.RECEIVER_EXPORTED)
4438 // Get handles for views that need to be modified.
4439 val bookmarksHeaderLinearLayout = findViewById<LinearLayout>(R.id.bookmarks_header_linearlayout)
4440 val launchBookmarksActivityFab = findViewById<FloatingActionButton>(R.id.launch_bookmarks_activity_fab)
4441 val createBookmarkFolderFab = findViewById<FloatingActionButton>(R.id.create_bookmark_folder_fab)
4442 val createBookmarkFab = findViewById<FloatingActionButton>(R.id.create_bookmark_fab)
4444 // Handle tab selections.
4445 tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
4446 override fun onTabSelected(tab: TabLayout.Tab) {
4447 // Close the find on page bar if it is open.
4448 closeFindOnPage(null)
4450 // 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.
4451 webViewViewPager2.post {
4452 // Select the same page in the view pager.
4453 webViewViewPager2.currentItem = tab.position
4455 // 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>
4457 setCurrentWebView(tab.position)
4462 override fun onTabUnselected(tab: TabLayout.Tab) {}
4464 override fun onTabReselected(tab: TabLayout.Tab) {
4465 // Only display the view SSL certificate dialog if the current WebView is not null.
4466 // This can happen if the tab is programmatically reselected while the app is being restarted and is not yet populated.
4467 if (currentWebView != null) {
4468 // Instantiate the View SSL Certificate dialog.
4469 val viewSslCertificateDialogFragment: DialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView!!.webViewFragmentId, currentWebView!!.getFavoriteIcon())
4471 // Display the View SSL Certificate dialog.
4472 viewSslCertificateDialogFragment.show(supportFragmentManager, getString(R.string.view_ssl_certificate))
4477 // Set a touch listener on the bookmarks header linear layout so that touches don't pass through to the button underneath.
4478 bookmarksHeaderLinearLayout.setOnTouchListener { _: View?, _: MotionEvent? -> true }
4480 // Set the launch bookmarks activity floating action button to launch the bookmarks activity.
4481 launchBookmarksActivityFab.setOnClickListener {
4482 // Get a copy of the favorite icon bitmap.
4483 val currentFavoriteIconBitmap = currentWebView!!.getFavoriteIcon()
4485 // Create a favorite icon byte array output stream.
4486 val currentFavoriteIconByteArrayOutputStream = ByteArrayOutputStream()
4488 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
4489 currentFavoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, currentFavoriteIconByteArrayOutputStream)
4491 // Convert the favorite icon byte array stream to a byte array.
4492 val currentFavoriteIconByteArray = currentFavoriteIconByteArrayOutputStream.toByteArray()
4494 // Create an intent to launch the bookmarks activity.
4495 val bookmarksIntent = Intent(applicationContext, BookmarksActivity::class.java)
4497 // Add the extra information to the intent.
4498 bookmarksIntent.putExtra(CURRENT_FOLDER_ID, currentBookmarksFolderId)
4499 bookmarksIntent.putExtra(CURRENT_TITLE, currentWebView!!.title)
4500 bookmarksIntent.putExtra(CURRENT_URL, currentWebView!!.url)
4501 bookmarksIntent.putExtra(CURRENT_FAVORITE_ICON_BYTE_ARRAY, currentFavoriteIconByteArray)
4504 startActivity(bookmarksIntent)
4507 // Set the create new bookmark folder floating action button to display an alert dialog.
4508 createBookmarkFolderFab.setOnClickListener {
4509 // Create a create bookmark folder dialog.
4510 val createBookmarkFolderDialog: DialogFragment = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView!!.getFavoriteIcon())
4512 // Show the create bookmark folder dialog.
4513 createBookmarkFolderDialog.show(supportFragmentManager, getString(R.string.create_folder))
4516 // Set the create new bookmark floating action button to display an alert dialog.
4517 createBookmarkFab.setOnClickListener {
4518 // Instantiate the create bookmark dialog.
4519 val createBookmarkDialog: DialogFragment = CreateBookmarkDialog.createBookmark(currentWebView!!.url!!, currentWebView!!.title!!, currentWebView!!.getFavoriteIcon())
4521 // Display the create bookmark dialog.
4522 createBookmarkDialog.show(supportFragmentManager, getString(R.string.create_bookmark))
4525 // Search for the string on the page whenever a character changes in the find on page edit text.
4526 findOnPageEditText.addTextChangedListener(object : TextWatcher {
4527 override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
4529 override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
4531 override fun afterTextChanged(s: Editable) {
4532 // 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.
4533 currentWebView?.findAllAsync(findOnPageEditText.text.toString())
4537 // Set the `check mark` button for the find on page edit text keyboard to close the soft keyboard.
4538 findOnPageEditText.setOnKeyListener { _: View?, keyCode: Int, keyEvent: KeyEvent ->
4539 if ((keyEvent.action == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
4540 // Hide the soft keyboard.
4541 inputMethodManager.hideSoftInputFromWindow(currentWebView!!.windowToken, 0)
4543 // Consume the event.
4544 return@setOnKeyListener true
4545 } else { // A different key was pressed.
4546 // Do not consume the event.
4547 return@setOnKeyListener false
4551 // Implement swipe to refresh.
4552 swipeRefreshLayout.setOnRefreshListener {
4553 // Reload the website.
4554 currentWebView!!.reload()
4557 // Store the default progress view offsets.
4558 defaultProgressViewStartOffset = swipeRefreshLayout.progressViewStartOffset
4559 defaultProgressViewEndOffset = swipeRefreshLayout.progressViewEndOffset
4561 // Set the refresh color scheme according to the theme.
4562 swipeRefreshLayout.setColorSchemeResources(R.color.blue_text)
4564 // Initialize a color background typed value.
4565 val colorBackgroundTypedValue = TypedValue()
4567 // Get the color background from the theme.
4568 theme.resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true)
4570 // Get the color background int from the typed value.
4571 val colorBackgroundInt = colorBackgroundTypedValue.data
4573 // Set the swipe refresh background color.
4574 swipeRefreshLayout.setProgressBackgroundColorSchemeColor(colorBackgroundInt)
4576 // Set the drawer titles, which identify the drawer layouts in accessibility mode.
4577 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer))
4578 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks))
4580 // Load the bookmarks folder.
4581 loadBookmarksFolder()
4583 // Handle clicks on bookmarks.
4584 bookmarksListView.onItemClickListener = AdapterView.OnItemClickListener { _: AdapterView<*>?, _: View?, _: Int, id: Long ->
4585 // Convert the id from long to int to match the format of the bookmarks database.
4586 val databaseId = id.toInt()
4588 // Get the bookmark cursor for this ID.
4589 val bookmarkCursor = bookmarksDatabaseHelper!!.getBookmark(databaseId)
4591 // Move the bookmark cursor to the first row.
4592 bookmarkCursor.moveToFirst()
4594 // Act upon the bookmark according to the type.
4595 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndexOrThrow(IS_FOLDER)) == 1) { // The selected bookmark is a folder.
4596 // Store the folder ID.
4597 currentBookmarksFolderId = bookmarkCursor.getLong(bookmarkCursor.getColumnIndexOrThrow(FOLDER_ID))
4599 // Load the new folder.
4600 loadBookmarksFolder()
4601 } else { // The selected bookmark is not a folder.
4602 // Load the bookmark URL.
4603 loadUrl(currentWebView!!, bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BOOKMARK_URL)))
4605 // Close the bookmarks drawer if it is not pinned.
4606 if (!bookmarksDrawerPinned)
4607 drawerLayout.closeDrawer(GravityCompat.END)
4610 // Close the cursor.
4611 bookmarkCursor.close()
4614 // Handle long-presses on bookmarks.
4615 bookmarksListView.onItemLongClickListener = AdapterView.OnItemLongClickListener { _: AdapterView<*>?, _: View?, _: Int, id: Long ->
4616 // Convert the database ID from `long` to `int`.
4617 val databaseId = id.toInt()
4619 // Run the commands associated with the type.
4620 if (bookmarksDatabaseHelper!!.isFolder(databaseId)) { // The bookmark is a folder.
4621 // Get the folder ID.
4622 val folderId = bookmarksDatabaseHelper!!.getFolderId(databaseId)
4624 // Get a cursor of all the bookmarks in the folder.
4625 val bookmarksCursor = bookmarksDatabaseHelper!!.getFolderBookmarks(folderId)
4627 // Move to the first entry in the cursor.
4628 bookmarksCursor.moveToFirst()
4630 // Open each bookmark
4631 for (i in 0 until bookmarksCursor.count) {
4632 // Load the bookmark in a new tab, moving to the tab for the first bookmark if the drawer is not pinned.
4633 addNewPage(bookmarksCursor.getString(bookmarksCursor.getColumnIndexOrThrow(BOOKMARK_URL)), adjacent = false, moveToTab = !bookmarksDrawerPinned && (i == 0))
4635 // Move to the next bookmark.
4636 bookmarksCursor.moveToNext()
4639 // Close the cursor.
4640 bookmarksCursor.close()
4641 } else { // The bookmark is not a folder.
4642 // Get the bookmark cursor for this ID.
4643 val bookmarkCursor = bookmarksDatabaseHelper!!.getBookmark(databaseId)
4645 // Move the bookmark cursor to the first row.
4646 bookmarkCursor.moveToFirst()
4648 // Load the bookmark in a new tab and move to the tab if the drawer is not pinned.
4649 addNewPage(bookmarkCursor.getString(bookmarkCursor.getColumnIndexOrThrow(BOOKMARK_URL)), adjacent = true, moveToTab = !bookmarksDrawerPinned)
4651 // Close the cursor.
4652 bookmarkCursor.close()
4655 // Close the bookmarks drawer if it is not pinned.
4656 if (!bookmarksDrawerPinned)
4657 drawerLayout.closeDrawer(GravityCompat.END)
4659 // Consume the event.
4663 // The drawer listener is used to update the navigation menu.
4664 drawerLayout.addDrawerListener(object : DrawerLayout.DrawerListener {
4665 override fun onDrawerSlide(drawerView: View, slideOffset: Float) {}
4667 override fun onDrawerOpened(drawerView: View) {}
4669 override fun onDrawerClosed(drawerView: View) {}
4671 override fun onDrawerStateChanged(newState: Int) {
4672 if (newState == DrawerLayout.STATE_SETTLING || newState == DrawerLayout.STATE_DRAGGING) { // A drawer is opening or closing.
4673 // Update the navigation menu items if the WebView is not null.
4674 if (currentWebView != null) {
4675 // Set the enabled status of the menu items.
4676 navigationBackMenuItem.isEnabled = currentWebView!!.canGoBack()
4677 navigationForwardMenuItem.isEnabled = currentWebView!!.canGoForward()
4678 navigationScrollToBottomMenuItem.isEnabled = (currentWebView!!.canScrollVertically(-1) || currentWebView!!.canScrollVertically(1))
4679 navigationHistoryMenuItem.isEnabled = currentWebView!!.canGoBack() || currentWebView!!.canGoForward()
4681 // Update the scroll menu item.
4682 if (currentWebView!!.scrollY == 0) { // The WebView is scrolled to the top.
4684 navigationScrollToBottomMenuItem.title = getString(R.string.scroll_to_bottom)
4687 navigationScrollToBottomMenuItem.icon = AppCompatResources.getDrawable(applicationContext, R.drawable.move_down_enabled)
4688 } else { // The WebView is not scrolled to the top.
4690 navigationScrollToBottomMenuItem.title = getString(R.string.scroll_to_top)
4693 navigationScrollToBottomMenuItem.icon = AppCompatResources.getDrawable(applicationContext, R.drawable.move_up_enabled)
4696 // Display the number of blocked requests.
4697 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + currentWebView!!.getRequestsCount(BLOCKED_REQUESTS)
4699 // Hide the keyboard (if displayed).
4700 inputMethodManager.hideSoftInputFromWindow(currentWebView!!.windowToken, 0)
4703 // 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.
4704 urlEditText.clearFocus()
4706 // 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.
4707 // Clearing the focus from the WebView removes any text selection markers and context menus, which otherwise draw above the open drawers.
4708 currentWebView?.clearFocus()
4710 if (bottomAppBar && navigationDrawerFirstView) {
4711 // Reset the navigation drawer first view flag.
4712 navigationDrawerFirstView = false
4714 // Get a handle for the navigation recycler view.
4715 val navigationRecyclerView = navigationView.getChildAt(0) as RecyclerView
4717 // Get the navigation linear layout manager.
4718 val navigationLinearLayoutManager = navigationRecyclerView.layoutManager as LinearLayoutManager
4720 // Scroll the navigation drawer to the bottom.
4721 navigationLinearLayoutManager.scrollToPositionWithOffset(13, 0)
4727 // Inflate a bare WebView to get the default user agent. It is not used to render content on the screen.
4728 @SuppressLint("InflateParams") val webViewLayout = layoutInflater.inflate(R.layout.bare_webview, null, false)
4730 // Get a handle for the WebView.
4731 val bareWebView = webViewLayout.findViewById<WebView>(R.id.bare_webview)
4733 // Store the default user agent.
4734 webViewDefaultUserAgent = bareWebView.settings.userAgentString
4736 // Destroy the bare WebView.
4737 bareWebView.destroy()
4739 // Update the domains settings set.
4740 updateDomainsSettingsSet()
4742 // Instantiate the check filter list helper.
4743 checkFilterListHelper = CheckFilterListHelper()
4746 @SuppressLint("ClickableViewAccessibility")
4747 override fun initializeWebView(nestedScrollWebView: NestedScrollWebView, pagePosition: Int, progressBar: ProgressBar, urlString: String, restoringState: Boolean) {
4748 // Get the WebView theme.
4749 val webViewTheme = sharedPreferences.getString(getString(R.string.webview_theme_key), getString(R.string.webview_theme_default_value))
4751 // Get the WebView theme entry values string array.
4752 val webViewThemeEntryValuesStringArray = resources.getStringArray(R.array.webview_theme_entry_values)
4754 // Set the WebView theme if algorithmic darkening is supported.
4755 if (WebViewFeature.isFeatureSupported(WebViewFeature.ALGORITHMIC_DARKENING)) {
4756 // Set the WebView them. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
4757 if (webViewTheme == webViewThemeEntryValuesStringArray[1]) { // The light theme is selected.
4758 // Turn off algorithmic darkening.
4759 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
4761 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
4762 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
4763 nestedScrollWebView.visibility = View.VISIBLE
4764 } else if (webViewTheme == webViewThemeEntryValuesStringArray[2]) { // The dark theme is selected.
4765 // Turn on algorithmic darkening.
4766 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
4767 } else { // The system default theme is selected.
4768 // Get the current theme status.
4769 val currentThemeStatus = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
4771 // Set the algorithmic darkening according to the current system theme status.
4772 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_NO) { // The system is in day mode.
4773 // Turn off algorithmic darkening.
4774 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, false)
4776 // Make the WebView visible. The WebView was created invisible in `webview_framelayout` to prevent a white background splash in night mode.
4777 // If the system is currently in night mode, showing the WebView will be handled in `onProgressChanged()`.
4778 nestedScrollWebView.visibility = View.VISIBLE
4779 } else { // The system is in night mode.
4780 // Turn on algorithmic darkening.
4781 WebSettingsCompat.setAlgorithmicDarkeningAllowed(nestedScrollWebView.settings, true)
4786 // Get a handle for the input method manager.
4787 val inputMethodManager = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
4789 // Set the app bar scrolling.
4790 nestedScrollWebView.isNestedScrollingEnabled = scrollAppBar
4792 // Allow pinch to zoom.
4793 nestedScrollWebView.settings.builtInZoomControls = true
4795 // Hide zoom controls.
4796 nestedScrollWebView.settings.displayZoomControls = false
4798 // Don't allow mixed content (HTTP and HTTPS) on the same website.
4799 nestedScrollWebView.settings.mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW
4801 // Set the WebView to load in overview mode (zoomed out to the maximum width).
4802 nestedScrollWebView.settings.loadWithOverviewMode = true
4804 // Explicitly disable geolocation.
4805 nestedScrollWebView.settings.setGeolocationEnabled(false)
4807 // Allow loading of file:// URLs. This is necessary for opening MHT web archives, which are copied into a temporary cache location.
4808 nestedScrollWebView.settings.allowFileAccess = true
4810 // Create a double-tap gesture detector to toggle full-screen mode.
4811 val doubleTapGestureDetector = GestureDetector(this, object : GestureDetector.SimpleOnGestureListener() {
4812 // Override `onDoubleTap()`. All other events are handled using the default settings.
4813 override fun onDoubleTap(motionEvent: MotionEvent): Boolean {
4814 return if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
4815 // Toggle the full screen browsing mode tracker.
4816 inFullScreenBrowsingMode = !inFullScreenBrowsingMode
4818 // Toggle the full screen browsing mode.
4819 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
4820 // Hide the app bar if specified.
4821 if (hideAppBar) { // App bar hiding is enabled.
4822 // Close the find on page bar if it is visible.
4823 closeFindOnPage(null)
4825 // Hide the tab linear layout.
4826 tabsLinearLayout.visibility = View.GONE
4828 // Hide the app bar.
4831 // Set layout and scrolling parameters according to the position of the app bar.
4832 if (bottomAppBar) { // The app bar is at the bottom.
4833 // Reset the WebView padding to fill the available space.
4834 swipeRefreshLayout.setPadding(0, 0, 0, 0)
4835 } else { // The app bar is at the top.
4836 // Check to see if the app bar is normally scrolled.
4837 if (scrollAppBar) { // The app bar is scrolled when it is displayed.
4838 // Get the swipe refresh layout parameters.
4839 val swipeRefreshLayoutParams = swipeRefreshLayout.layoutParams as CoordinatorLayout.LayoutParams
4841 // Remove the off-screen scrolling layout.
4842 swipeRefreshLayoutParams.behavior = null
4843 } else { // The app bar is not scrolled when it is displayed.
4844 // Remove the padding from the top of the swipe refresh layout.
4845 swipeRefreshLayout.setPadding(0, 0, 0, 0)
4847 // The swipe refresh circle must be moved above the now removed status bar location.
4848 swipeRefreshLayout.setProgressViewOffset(false, -200, defaultProgressViewEndOffset)
4851 } else { // App bar hiding is not enabled.
4852 // Adjust the UI for the bottom app bar.
4854 // Adjust the UI according to the scrolling of the app bar.
4856 // Reset the WebView padding to fill the available space.
4857 swipeRefreshLayout.setPadding(0, 0, 0, 0)
4859 // Move the WebView above the app bar layout.
4860 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
4865 /* Hide the system bars.
4866 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4867 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
4868 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4869 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4872 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4873 @Suppress("DEPRECATION")
4874 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
4875 } else { // Switch to normal viewing mode.
4876 // Show the app bar if it was hidden.
4878 // Show the tab linear layout.
4879 tabsLinearLayout.visibility = View.VISIBLE
4881 // Show the app bar.
4885 // Set layout and scrolling parameters according to the position of the app bar.
4886 if (bottomAppBar) { // The app bar is at the bottom.
4889 // Reset the WebView padding to fill the available space.
4890 swipeRefreshLayout.setPadding(0, 0, 0, 0)
4892 // Move the WebView above the app bar layout.
4893 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
4895 } else { // The app bar is at the top.
4896 // Check to see if the app bar is normally scrolled.
4897 if (scrollAppBar) { // The app bar is scrolled when it is displayed.
4898 // Get the swipe refresh layout parameters.
4899 val swipeRefreshLayoutParams = swipeRefreshLayout.layoutParams as CoordinatorLayout.LayoutParams
4901 // Add the off-screen scrolling layout.
4902 swipeRefreshLayoutParams.behavior = AppBarLayout.ScrollingViewBehavior()
4903 } else { // The app bar is not scrolled when it is displayed.
4904 // The swipe refresh layout must be manually moved below the app bar layout.
4905 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0)
4907 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
4908 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight)
4912 // Remove the `SYSTEM_UI` flags from the root frame layout. The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
4913 @Suppress("DEPRECATION")
4914 rootFrameLayout.systemUiVisibility = 0
4917 // Consume the double-tap.
4919 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
4925 override fun onFling(motionEvent1: MotionEvent?, motionEvent2: MotionEvent, velocityX: Float, velocityY: Float): Boolean {
4926 // Scroll the bottom app bar if enabled.
4927 if (bottomAppBar && scrollAppBar && !objectAnimator.isRunning && (motionEvent1 != null)) {
4928 // Calculate the Y change.
4929 val motionY = motionEvent2.y - motionEvent1.y
4931 // Scroll the app bar if the change is greater than 50 pixels.
4933 // Animate the bottom app bar onto the screen.
4934 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", 0f)
4935 } else if (motionY < -50) {
4936 // Animate the bottom app bar off the screen.
4937 objectAnimator = ObjectAnimator.ofFloat(appBarLayout, "translationY", appBarLayout.height.toFloat())
4941 objectAnimator.start()
4944 // Do not consume the event.
4949 // Pass all touch events on the WebView through the double-tap gesture detector.
4950 nestedScrollWebView.setOnTouchListener { view: View, motionEvent: MotionEvent? ->
4951 // Call `performClick()` on the view, which is required for accessibility.
4954 // Check for double-taps.
4955 doubleTapGestureDetector.onTouchEvent(motionEvent!!)
4958 // Register the WebView for a context menu. This is used to see link targets and download images.
4959 registerForContextMenu(nestedScrollWebView)
4961 // Allow the downloading of files.
4962 nestedScrollWebView.setDownloadListener { downloadUrlString: String, userAgent: String, contentDisposition: String, mimetype: String, contentLength: Long ->
4963 // Use the specified download provider.
4964 if (downloadWithExternalApp) { // Download with an external app.
4965 // Download with an external app.
4966 saveWithExternalApp(downloadUrlString)
4967 } else { // Download with Privacy Browser or Android's download manager.
4968 // Process the content length if it contains data.
4969 val formattedFileSizeString = if (contentLength > 0) { // The content length is greater than 0.
4970 // Format the content length as a string.
4971 NumberFormat.getInstance().format(contentLength) + " " + getString(R.string.bytes)
4972 } else { // The content length is not greater than 0.
4973 // Set the formatted file size string to be `unknown size`.
4974 getString(R.string.unknown_size)
4977 // Get the file name from the content disposition.
4978 val fileNameString = UrlHelper.getFileName(this, contentDisposition, mimetype, downloadUrlString)
4980 // Instantiate the save dialog according.
4981 val saveDialogFragment = SaveDialog.saveUrl(downloadUrlString, fileNameString, formattedFileSizeString, userAgent, nestedScrollWebView.acceptCookies)
4983 // 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.
4985 // Show the save dialog.
4986 saveDialogFragment.show(supportFragmentManager, getString(R.string.save_dialog))
4987 } catch (exception: Exception) { // The dialog could not be shown.
4988 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
4989 pendingDialogsArrayList.add(PendingDialogDataClass(saveDialogFragment, getString(R.string.save_dialog)))
4993 // Get the current page position.
4994 val currentPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
4996 // Get the corresponding tab.
4997 val tab = tabLayout.getTabAt(currentPagePosition)!!
4999 // Get the tab custom view.
5000 val tabCustomView = tab.customView!!
5002 // Get the tab views.
5003 val tabFavoriteIconImageView = tabCustomView.findViewById<ImageView>(R.id.favorite_icon_imageview)
5004 val tabTitleTextView = tabCustomView.findViewById<TextView>(R.id.title_textview)
5006 // Restore the previous webpage favorite icon and title if the title is currently set to `Loading...`.
5007 if (tabTitleTextView.text.toString() == getString(R.string.loading)) {
5008 // Restore the previous webpage title text.
5009 tabTitleTextView.text = nestedScrollWebView.previousWebpageTitle
5011 // Restore the previous webpage favorite icon if it is not null.
5012 if (nestedScrollWebView.previousFavoriteIconDrawable != null)
5013 tabFavoriteIconImageView.setImageDrawable(nestedScrollWebView.previousFavoriteIconDrawable)
5017 // Update the find on page count.
5018 nestedScrollWebView.setFindListener { activeMatchOrdinal, numberOfMatches, isDoneCounting ->
5019 if (isDoneCounting && (numberOfMatches == 0)) { // There are no matches.
5020 // Set the find on page count text view to be `0/0`.
5021 findOnPageCountTextView.setText(R.string.zero_of_zero)
5022 } else if (isDoneCounting) { // There are matches.
5023 // The active match ordinal is zero-based.
5024 val activeMatch = activeMatchOrdinal + 1
5026 // Build the match string.
5027 val matchString = "$activeMatch/$numberOfMatches"
5029 // Update the find on page count text view.
5030 findOnPageCountTextView.text = matchString
5034 // Process scroll changes.
5035 nestedScrollWebView.setOnScrollChangeListener { _: View?, _: Int, _: Int, _: Int, _: Int ->
5036 // Set the swipe to refresh status.
5037 if (nestedScrollWebView.swipeToRefresh) // Only enable swipe to refresh if the WebView is scrolled to the top.
5038 swipeRefreshLayout.isEnabled = nestedScrollWebView.scrollY == 0
5039 else // Disable swipe to refresh.
5040 swipeRefreshLayout.isEnabled = false
5042 // Reinforce the system UI visibility flags if in full screen browsing mode.
5043 // This hides the status and navigation bars, which are displayed if other elements are shown, like dialog boxes, the options menu, or the keyboard.
5044 if (inFullScreenBrowsingMode) {
5045 /* Hide the system bars.
5046 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5047 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5048 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5049 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5052 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
5053 @Suppress("DEPRECATION")
5054 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
5058 // Set the web chrome client.
5059 nestedScrollWebView.webChromeClient = object : WebChromeClient() {
5060 // Update the progress bar when a page is loading.
5061 override fun onProgressChanged(view: WebView, progress: Int) {
5062 // Update the progress bar.
5063 progressBar.progress = progress
5065 // Set the visibility of the progress bar.
5066 if (progress < 100) {
5067 // Show the progress bar.
5068 progressBar.visibility = View.VISIBLE
5070 // Hide the progress bar.
5071 progressBar.visibility = View.GONE
5073 //Stop the swipe to refresh indicator if it is running
5074 swipeRefreshLayout.isRefreshing = false
5076 // 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.
5077 nestedScrollWebView.visibility = View.VISIBLE
5081 // Set the favorite icon when it changes.
5082 override fun onReceivedIcon(view: WebView, icon: Bitmap) {
5083 // 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.
5084 // This prevents low resolution icons from replacing high resolution one.
5085 // The check for the visibility of the progress bar can possibly be removed once https://redmine.stoutner.com/issues/747 is fixed.
5086 if ((progressBar.visibility == View.GONE) && (icon.height > nestedScrollWebView.getFavoriteIconHeight())) {
5087 // Store the new favorite icon.
5088 nestedScrollWebView.setFavoriteIcon(icon)
5090 // Get the current page position.
5091 val currentPosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
5093 // Get the current tab.
5094 val tab = tabLayout.getTabAt(currentPosition)
5096 // Check to see if the tab has been populated.
5098 // Get the custom view from the tab.
5099 val tabView = tab.customView
5101 // Check to see if the custom tab view has been populated.
5102 if (tabView != null) {
5103 // Get the favorite icon image view from the tab.
5104 val tabFavoriteIconImageView = tabView.findViewById<ImageView>(R.id.favorite_icon_imageview)
5106 // Display the favorite icon in the tab.
5107 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true))
5113 // Save a copy of the title when it changes.
5114 override fun onReceivedTitle(view: WebView, title: String) {
5115 // Get the current page position.
5116 val currentPosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
5118 // Get the current tab.
5119 val tab = tabLayout.getTabAt(currentPosition)
5121 // Only populate the title text view if the tab has been fully created.
5123 // Get the custom view from the tab.
5124 val tabView = tab.customView
5126 // Only populate the title text view if the tab view has been fully populated.
5127 if (tabView != null) {
5128 // Get the title text view from the tab.
5129 val tabTitleTextView = tabView.findViewById<TextView>(R.id.title_textview)
5131 // Set the title according to the URL.
5132 if (title == "about:blank") {
5133 // Set the title to indicate a new tab.
5134 tabTitleTextView.setText(R.string.new_tab)
5136 // Set the title as the tab text.
5137 tabTitleTextView.text = title
5143 // Enter full screen video.
5144 override fun onShowCustomView(video: View, callback: CustomViewCallback) {
5145 // Set the full screen video flag.
5146 displayingFullScreenVideo = true
5148 // Hide the keyboard.
5149 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.windowToken, 0)
5151 // Hide the coordinator layout.
5152 coordinatorLayout.visibility = View.GONE
5154 /* Hide the system bars.
5155 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5156 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5157 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5158 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5161 // The deprecated command can be switched to `WindowInsetsController` once the minimum API >= 30.
5162 @Suppress("DEPRECATION")
5163 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
5165 // Disable the sliding drawers.
5166 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
5168 // Add the video view to the full screen video frame layout.
5169 fullScreenVideoFrameLayout.addView(video)
5171 // Show the full screen video frame layout.
5172 fullScreenVideoFrameLayout.visibility = View.VISIBLE
5174 // Disable the screen timeout while the video is playing. YouTube does this automatically, but not all other videos do.
5175 fullScreenVideoFrameLayout.keepScreenOn = true
5178 // Exit full screen video.
5179 override fun onHideCustomView() {
5180 // Exit the full screen video.
5181 exitFullScreenVideo()
5185 override fun onShowFileChooser(webView: WebView, filePathCallback: ValueCallback<Array<Uri>>, fileChooserParams: FileChooserParams): Boolean {
5186 // Store the file path callback.
5187 fileChooserCallback = filePathCallback
5189 // Create an intent to open a chooser based on the file chooser parameters.
5190 val fileChooserIntent = fileChooserParams.createIntent()
5192 // Check to see if the file chooser intent resolves to an installed package.
5193 if (fileChooserIntent.resolveActivity(packageManager) != null) { // The file chooser intent is fine.
5194 // Launch the file chooser intent.
5195 browseFileUploadActivityResultLauncher.launch(fileChooserIntent)
5196 } else { // The file chooser intent will cause a crash.
5197 // Create a generic intent to open a chooser.
5198 val genericFileChooserIntent = Intent(Intent.ACTION_GET_CONTENT)
5200 // Request an openable file.
5201 genericFileChooserIntent.addCategory(Intent.CATEGORY_OPENABLE)
5203 // Set the file type to everything.
5204 genericFileChooserIntent.type = "*/*"
5206 // Launch the generic file chooser intent.
5207 browseFileUploadActivityResultLauncher.launch(genericFileChooserIntent)
5210 // Handle the event.
5214 nestedScrollWebView.webViewClient = object : WebViewClient() {
5215 // `shouldOverrideUrlLoading` makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
5216 override fun shouldOverrideUrlLoading(view: WebView, webResourceRequest: WebResourceRequest): Boolean {
5217 // Get the URL from the web resource request.
5218 var requestUrlString = webResourceRequest.url.toString()
5220 // Sanitize the url.
5221 requestUrlString = sanitizeUrl(requestUrlString)
5223 // Handle the URL according to the type.
5224 return if (requestUrlString.startsWith("http")) { // Load the URL in Privacy Browser.
5225 // Load the URL. By using `loadUrl()`, instead of `loadUrlFromBase()`, the Referer header will never be sent.
5226 loadUrl(nestedScrollWebView, requestUrlString)
5228 // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
5229 // Custom headers cannot be added if false is returned and the WebView handles the loading of the URL.
5231 } else if (requestUrlString.startsWith("mailto:")) { // Load the email address in an external email program.
5232 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
5233 val emailIntent = Intent(Intent.ACTION_SENDTO)
5235 // Parse the url and set it as the data for the intent.
5236 emailIntent.data = Uri.parse(requestUrlString)
5238 // Open the email program in a new task instead of as part of Privacy Browser.
5239 emailIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
5243 startActivity(emailIntent)
5244 } catch (exception: ActivityNotFoundException) {
5245 // Display a snackbar.
5246 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
5249 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5251 } else if (requestUrlString.startsWith("tel:")) { // Load the phone number in the dialer.
5252 // Create a dial intent.
5253 val dialIntent = Intent(Intent.ACTION_DIAL)
5255 // Add the phone number to the intent.
5256 dialIntent.data = Uri.parse(requestUrlString)
5258 // Open the dialer in a new task instead of as part of Privacy Browser.
5259 dialIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
5263 startActivity(dialIntent)
5264 } catch (exception: ActivityNotFoundException) {
5265 // Display a snackbar.
5266 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
5269 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5271 } else { // Load a system chooser to select an app that can handle the URL.
5272 // Create a generic intent to open an app.
5273 val genericIntent = Intent(Intent.ACTION_VIEW)
5275 // Add the URL to the intent.
5276 genericIntent.data = Uri.parse(requestUrlString)
5278 // List all apps that can handle the URL instead of just opening the first one.
5279 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE)
5281 // Open the app in a new task instead of as part of Privacy Browser.
5282 genericIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
5286 startActivity(genericIntent)
5287 } catch (exception: ActivityNotFoundException) {
5288 // Display a snackbar.
5289 Snackbar.make(nestedScrollWebView, getString(R.string.unrecognized_url, requestUrlString), Snackbar.LENGTH_SHORT).show()
5292 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5297 // Check requests against the block lists.
5298 override fun shouldInterceptRequest(view: WebView, webResourceRequest: WebResourceRequest): WebResourceResponse? {
5300 val requestUrlString = webResourceRequest.url.toString()
5302 // Check to see if the resource request is for the main URL.
5303 if (requestUrlString == nestedScrollWebView.currentUrl) {
5304 // `return null` loads the resource request, which should never be blocked if it is the main URL.
5308 // 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.
5309 while (ultraPrivacy == null) {
5311 // Check to see if the filter lists have been populated after 100 ms.
5313 } catch (exception: InterruptedException) {
5318 // Create an empty web resource response to be used if the resource request is blocked.
5319 val emptyWebResourceResponse = WebResourceResponse("text/plain", "utf8", ByteArrayInputStream("".toByteArray()))
5321 // Initialize the variables.
5322 var allowListResultStringArray: Array<String>? = null
5323 var isThirdPartyRequest = false
5325 // Get the current URL. `.getUrl()` throws an error because operations on the WebView cannot be made from this thread.
5326 var currentBaseDomain = nestedScrollWebView.currentDomainName
5328 // Store a copy of the current domain for use in later requests.
5329 val currentDomain = currentBaseDomain
5331 // Get the request host name.
5332 var requestBaseDomain = webResourceRequest.url.host
5334 // Only check for third-party requests if the current base domain is not empty and the request domain is not null.
5335 if (currentBaseDomain.isNotEmpty() && (requestBaseDomain != null)) {
5336 // Determine the current base domain.
5337 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5338 // Remove the first subdomain.
5339 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1)
5342 // Determine the request base domain.
5343 while (requestBaseDomain!!.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5344 // Remove the first subdomain.
5345 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1)
5348 // Update the third party request tracker.
5349 isThirdPartyRequest = currentBaseDomain != requestBaseDomain
5352 // Get the current WebView page position.
5353 val webViewPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
5355 // Determine if the WebView is currently displayed.
5356 val webViewDisplayed = (webViewPagePosition == tabLayout.selectedTabPosition)
5358 // Block third-party requests if enabled.
5359 if (isThirdPartyRequest && nestedScrollWebView.blockAllThirdPartyRequests) {
5360 // Add the result to the resource requests.
5361 nestedScrollWebView.addResourceRequest(arrayOf(REQUEST_THIRD_PARTY, requestUrlString))
5363 // Increment the blocked requests counters.
5364 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5365 nestedScrollWebView.incrementRequestsCount(THIRD_PARTY_REQUESTS)
5367 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5368 if (webViewDisplayed) {
5369 // Updating the UI must be run from the UI thread.
5371 // Update the menu item titles.
5372 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5374 // Update the options menu if it has been populated.
5375 if (optionsMenu != null) {
5376 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5377 optionsBlockAllThirdPartyRequestsMenuItem.title =
5378 nestedScrollWebView.getRequestsCount(THIRD_PARTY_REQUESTS).toString() + " - " + getString(R.string.block_all_third_party_requests)
5383 // The resource request was blocked. Return an empty web resource response.
5384 return emptyWebResourceResponse
5387 // Check UltraList if it is enabled.
5388 if (nestedScrollWebView.ultraListEnabled) {
5389 // Check the URL against UltraList.
5390 val ultraListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, ultraList)
5392 // Process the UltraList results.
5393 if (ultraListResults[0] == REQUEST_BLOCKED) { // The resource request matched UltraList's block list.
5394 // Add the result to the resource requests.
5395 nestedScrollWebView.addResourceRequest(arrayOf(ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]))
5397 // Increment the blocked requests counters.
5398 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5399 nestedScrollWebView.incrementRequestsCount(com.stoutner.privacybrowser.views.ULTRALIST)
5401 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5402 if (webViewDisplayed) {
5403 // Updating the UI must be run from the UI thread.
5405 // Update the menu item titles.
5406 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5408 // Update the options menu if it has been populated.
5409 if (optionsMenu != null) {
5410 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5411 optionsUltraListMenuItem.title = nestedScrollWebView.getRequestsCount(com.stoutner.privacybrowser.views.ULTRALIST).toString() + " - " + getString(R.string.ultralist)
5416 // The resource request was blocked. Return an empty web resource response.
5417 return emptyWebResourceResponse
5418 } else if (ultraListResults[0] == REQUEST_ALLOWED) { // The resource request matched UltraList's allow list.
5419 // Add an allow list entry to the resource requests array.
5420 nestedScrollWebView.addResourceRequest(arrayOf(ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]))
5422 // The resource request has been allowed by UltraList. `return null` loads the requested resource.
5427 // Check UltraPrivacy if it is enabled.
5428 if (nestedScrollWebView.ultraPrivacyEnabled) {
5429 // Check the URL against UltraPrivacy.
5430 val ultraPrivacyResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, ultraPrivacy!!)
5432 // Process the UltraPrivacy results.
5433 if (ultraPrivacyResults[0] == REQUEST_BLOCKED) { // The resource request matched UltraPrivacy's block list.
5434 // Add the result to the resource requests.
5435 nestedScrollWebView.addResourceRequest(arrayOf(ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5436 ultraPrivacyResults[5]))
5438 // Increment the blocked requests counters.
5439 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5440 nestedScrollWebView.incrementRequestsCount(ULTRAPRIVACY)
5442 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5443 if (webViewDisplayed) {
5444 // Updating the UI must be run from the UI thread.
5446 // Update the menu item titles.
5447 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5449 // Update the options menu if it has been populated.
5450 if (optionsMenu != null) {
5451 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5452 optionsUltraPrivacyMenuItem.title = nestedScrollWebView.getRequestsCount(ULTRAPRIVACY).toString() + " - " + getString(R.string.ultraprivacy)
5457 // The resource request was blocked. Return an empty web resource response.
5458 return emptyWebResourceResponse
5459 } else if (ultraPrivacyResults[0] == REQUEST_ALLOWED) { // The resource request matched UltraPrivacy's allow list.
5460 // Add an allow list entry to the resource requests array.
5461 nestedScrollWebView.addResourceRequest(arrayOf(ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5462 ultraPrivacyResults[5]))
5464 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
5469 // Check EasyList if it is enabled.
5470 if (nestedScrollWebView.easyListEnabled) {
5471 // Check the URL against EasyList.
5472 val easyListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, easyList)
5474 // Process the EasyList results.
5475 if (easyListResults[0] == REQUEST_BLOCKED) { // The resource request matched EasyList's block list.
5476 // Add the result to the resource requests.
5477 nestedScrollWebView.addResourceRequest(arrayOf(easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]))
5479 // Increment the blocked requests counters.
5480 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5481 nestedScrollWebView.incrementRequestsCount(EASYLIST)
5483 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5484 if (webViewDisplayed) {
5485 // Updating the UI must be run from the UI thread.
5487 // Update the menu item titles.
5488 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5490 // Update the options menu if it has been populated.
5491 if (optionsMenu != null) {
5492 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5493 optionsEasyListMenuItem.title = nestedScrollWebView.getRequestsCount(EASYLIST).toString() + " - " + getString(R.string.easylist)
5498 // The resource request was blocked. Return an empty web resource response.
5499 return emptyWebResourceResponse
5500 } else if (easyListResults[0] == REQUEST_ALLOWED) { // The resource request matched EasyList's allow list.
5501 // Update the allow list result string array tracker.
5502 allowListResultStringArray = arrayOf(easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5])
5506 // Check EasyPrivacy if it is enabled.
5507 if (nestedScrollWebView.easyPrivacyEnabled) {
5508 // Check the URL against EasyPrivacy.
5509 val easyPrivacyResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, easyPrivacy)
5511 // Process the EasyPrivacy results.
5512 if (easyPrivacyResults[0] == REQUEST_BLOCKED) { // The resource request matched EasyPrivacy's block list.
5513 // Add the result to the resource requests.
5514 nestedScrollWebView.addResourceRequest(arrayOf(easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5]))
5516 // Increment the blocked requests counters.
5517 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5518 nestedScrollWebView.incrementRequestsCount(EASYPRIVACY)
5520 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5521 if (webViewDisplayed) {
5522 // Updating the UI must be run from the UI thread.
5524 // Update the menu item titles.
5525 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5527 // Update the options menu if it has been populated.
5528 if (optionsMenu != null) {
5529 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5530 optionsEasyPrivacyMenuItem.title = nestedScrollWebView.getRequestsCount(EASYPRIVACY).toString() + " - " + getString(R.string.easyprivacy)
5535 // The resource request was blocked. Return an empty web resource response.
5536 return emptyWebResourceResponse
5537 } else if (easyPrivacyResults[0] == REQUEST_ALLOWED) { // The resource request matched EasyPrivacy's allow list.
5538 // Update the allow list result string array tracker.
5539 allowListResultStringArray = arrayOf(easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5])
5543 // Check Fanboy’s Annoyance List if it is enabled.
5544 if (nestedScrollWebView.fanboysAnnoyanceListEnabled) {
5545 // Check the URL against Fanboy's Annoyance List.
5546 val fanboysAnnoyanceListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, fanboysAnnoyanceList)
5548 // Process the Fanboy's Annoyance List results.
5549 if (fanboysAnnoyanceListResults[0] == REQUEST_BLOCKED) { // The resource request matched Fanboy's Annoyance List's block list.
5550 // Add the result to the resource requests.
5551 nestedScrollWebView.addResourceRequest(arrayOf(fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5552 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]))
5554 // Increment the blocked requests counters.
5555 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5556 nestedScrollWebView.incrementRequestsCount(FANBOYS_ANNOYANCE_LIST)
5558 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5559 if (webViewDisplayed) {
5560 // Updating the UI must be run from the UI thread.
5562 // Update the menu item titles.
5563 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5565 // Update the options menu if it has been populated.
5566 if (optionsMenu != null) {
5567 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5568 optionsFanboysAnnoyanceListMenuItem.title = nestedScrollWebView.getRequestsCount(FANBOYS_ANNOYANCE_LIST).toString() + " - " + getString(R.string.fanboys_annoyance_list)
5573 // The resource request was blocked. Return an empty web resource response.
5574 return emptyWebResourceResponse
5575 } else if (fanboysAnnoyanceListResults[0] == REQUEST_ALLOWED) { // The resource request matched Fanboy's Annoyance List's allow list.
5576 // Update the allow list result string array tracker.
5577 allowListResultStringArray = arrayOf(fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5578 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5])
5580 } else if (nestedScrollWebView.fanboysSocialBlockingListEnabled) { // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
5581 // Check the URL against Fanboy's Annoyance List.
5582 val fanboysSocialListResults = checkFilterListHelper.checkFilterList(currentDomain, requestUrlString, isThirdPartyRequest, fanboysSocialList)
5584 // Process the Fanboy's Social Blocking List results.
5585 if (fanboysSocialListResults[0] == REQUEST_BLOCKED) { // The resource request matched Fanboy's Social Blocking List's block list.
5586 // Add the result to the resource requests.
5587 nestedScrollWebView.addResourceRequest(arrayOf(fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5588 fanboysSocialListResults[4], fanboysSocialListResults[5]))
5590 // Increment the blocked requests counters.
5591 nestedScrollWebView.incrementRequestsCount(BLOCKED_REQUESTS)
5592 nestedScrollWebView.incrementRequestsCount(FANBOYS_SOCIAL_BLOCKING_LIST)
5594 // Update the titles of the filter lists menu items if the WebView is currently displayed.
5595 if (webViewDisplayed) {
5596 // Updating the UI must be run from the UI thread.
5598 // Update the menu item titles.
5599 navigationRequestsMenuItem.title = getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5601 // Update the options menu if it has been populated.
5602 if (optionsMenu != null) {
5603 optionsFilterListsMenuItem.title = getString(R.string.filterlists) + " - " + nestedScrollWebView.getRequestsCount(BLOCKED_REQUESTS)
5604 optionsFanboysSocialBlockingListMenuItem.title =
5605 nestedScrollWebView.getRequestsCount(FANBOYS_SOCIAL_BLOCKING_LIST).toString() + " - " + getString(R.string.fanboys_social_blocking_list)
5610 // The resource request was blocked. Return an empty web resource response.
5611 return emptyWebResourceResponse
5612 } else if (fanboysSocialListResults[0] == REQUEST_ALLOWED) { // The resource request matched Fanboy's Social Blocking List's allow list.
5613 // Update the allow list result string array tracker.
5614 allowListResultStringArray = arrayOf(fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3], fanboysSocialListResults[4],
5615 fanboysSocialListResults[5])
5619 // Add the request to the log because it hasn't been processed by any of the previous checks.
5620 if (allowListResultStringArray != null) { // The request was processed by an allow list.
5621 nestedScrollWebView.addResourceRequest(allowListResultStringArray)
5622 } else { // The request didn't match any filter list entry. Log it as a default request.
5623 nestedScrollWebView.addResourceRequest(arrayOf(REQUEST_DEFAULT, requestUrlString))
5626 // The resource request has not been blocked. `return null` loads the requested resource.
5630 // Handle HTTP authentication requests.
5631 override fun onReceivedHttpAuthRequest(view: WebView, handler: HttpAuthHandler, host: String, realm: String) {
5632 // Store the handler.
5633 nestedScrollWebView.httpAuthHandler = handler
5635 // Instantiate an HTTP authentication dialog.
5636 val httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm, nestedScrollWebView.webViewFragmentId)
5638 // Show the HTTP authentication dialog.
5639 httpAuthenticationDialogFragment.show(supportFragmentManager, getString(R.string.http_authentication))
5642 override fun onPageStarted(webView: WebView, url: String, favicon: Bitmap?) {
5643 // Get the app bar layout height. This can't be done in `applyAppSettings()` because the app bar is not yet populated there.
5644 // 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.
5645 if (appBarLayout.height > 0)
5646 appBarHeight = appBarLayout.height
5648 // Set the padding and layout settings according to the position of the app bar.
5649 if (bottomAppBar) { // The app bar is on the bottom.
5651 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) { // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
5652 // Reset the WebView padding to fill the available space.
5653 swipeRefreshLayout.setPadding(0, 0, 0, 0)
5654 } else { // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
5655 // Move the WebView above the app bar layout.
5656 swipeRefreshLayout.setPadding(0, 0, 0, appBarHeight)
5658 } else { // The app bar is on the top.
5659 // 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.
5660 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) { // The app bar scrolls or full screen browsing mode is engaged with the app bar hidden.
5661 // No padding is needed because it will automatically be placed below the app bar layout due to the scrolling layout behavior.
5662 swipeRefreshLayout.setPadding(0, 0, 0, 0)
5664 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5665 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10, defaultProgressViewEndOffset)
5666 } else { // The app bar doesn't scroll or full screen browsing mode is not engaged with the app bar hidden.
5667 // The swipe refresh layout must be manually moved below the app bar layout.
5668 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0)
5670 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5671 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight)
5675 // Reset the list of resource requests.
5676 nestedScrollWebView.clearResourceRequests()
5678 // Reset the requests counters.
5679 nestedScrollWebView.resetRequestsCounters()
5681 // Get the current page position.
5682 val currentPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
5684 // Update the URL text bar if the page is currently selected and the URL edit text is not currently being edited.
5685 if ((tabLayout.selectedTabPosition == currentPagePosition) && !urlEditText.hasFocus()) {
5686 // Display the formatted URL text. The nested scroll WebView current URL preserves any initial `view-source:`, and opposed to the method URL variable.
5687 urlEditText.setText(nestedScrollWebView.currentUrl)
5689 // Highlight the URL syntax.
5690 UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
5692 // Hide the keyboard.
5693 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.windowToken, 0)
5696 // Reset the list of host IP addresses.
5697 nestedScrollWebView.currentIpAddresses = ""
5699 // Get a URI for the current URL.
5700 val currentUri = Uri.parse(url)
5702 // Get the current domain name.
5703 val currentDomainName = currentUri.host
5705 // Get the IP addresses for the current domain.
5706 if (!currentDomainName.isNullOrEmpty())
5707 GetHostIpAddressesCoroutine.checkPinnedMismatch(currentDomainName, nestedScrollWebView, supportFragmentManager, getString(R.string.pinned_mismatch))
5709 // 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.)
5710 if ((optionsMenu != null) && (webView == currentWebView)) {
5712 optionsRefreshMenuItem.setTitle(R.string.stop)
5714 // Set the icon if it is displayed in the AppBar.
5715 if (displayAdditionalAppBarIcons)
5716 optionsRefreshMenuItem.setIcon(R.drawable.close_blue)
5720 override fun onPageFinished(webView: WebView, url: String) {
5721 // Flush any cookies to persistent storage. The cookie manager has become very lazy about flushing cookies in recent versions.
5722 if (nestedScrollWebView.acceptCookies)
5723 cookieManager.flush()
5725 // Update the Refresh menu item if the options menu has been created and the WebView is currently displayed.
5726 if (optionsMenu != null && (webView == currentWebView)) {
5727 // Reset the Refresh title.
5728 optionsRefreshMenuItem.setTitle(R.string.refresh)
5730 // Reset the icon if it is displayed in the app bar.
5731 if (displayAdditionalAppBarIcons)
5732 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled)
5735 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
5736 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
5737 val privateDataDirectoryString = applicationInfo.dataDir
5739 // Clear the cache, history, and logcat if Incognito Mode is enabled.
5740 if (incognitoModeEnabled) {
5741 // Clear the cache. `true` includes disk files.
5742 nestedScrollWebView.clearCache(true)
5744 // Clear the back/forward history.
5745 nestedScrollWebView.clearHistory()
5747 // Manually delete cache folders.
5749 // Delete the main cache directory.
5750 Runtime.getRuntime().exec("rm -rf $privateDataDirectoryString/cache")
5751 } catch (exception: IOException) {
5752 // Do nothing if an error is thrown.
5755 // Clear the logcat.
5757 // Clear the logcat. `-c` clears the logcat. `-b all` clears all the buffers (instead of just crash, main, and system).
5758 Runtime.getRuntime().exec("logcat -b all -c")
5759 } catch (exception: IOException) {
5764 // Clear the `Service Worker` directory.
5766 // A string array must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
5767 Runtime.getRuntime().exec(arrayOf("rm", "-rf", "$privateDataDirectoryString/app_webview/Default/Service Worker/"))
5768 } catch (exception: IOException) {
5772 // Get the current page position.
5773 val currentPagePosition = webViewStateAdapter!!.getPositionForId(nestedScrollWebView.webViewFragmentId)
5775 // 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.
5776 val currentUrl = nestedScrollWebView.url
5778 // Get the current tab.
5779 val tab = tabLayout.getTabAt(currentPagePosition)
5781 // Update the URL text bar if the page is currently selected and the user is not currently typing in the URL edit text.
5782 // Crash records show that, in some crazy way, it is possible for the current URL to be blank at this point.
5783 // Probably some sort of race condition when Privacy Browser is being resumed.
5784 if ((tabLayout.selectedTabPosition == currentPagePosition) && !urlEditText.hasFocus() && (currentUrl != null)) {
5785 // Check to see if the URL is `about:blank`.
5786 if (currentUrl == "about:blank") { // The WebView is blank.
5787 // Display the hint in the URL edit text.
5788 urlEditText.setText("")
5790 // Request focus for the URL text box.
5791 urlEditText.requestFocus()
5793 // Display the keyboard.
5794 inputMethodManager.showSoftInput(urlEditText, 0)
5796 // Apply the domain settings. This clears any settings from the previous domain.
5797 applyDomainSettings(nestedScrollWebView, "", resetTab = true, reloadWebsite = false, loadUrl = false)
5799 // Only populate the title text view if the tab has been fully created.
5801 // Get the custom view from the tab.
5802 val tabView = tab.customView!!
5804 // Get the title text view from the tab.
5805 val tabTitleTextView = tabView.findViewById<TextView>(R.id.title_textview)
5807 // Set the title as the tab text.
5808 tabTitleTextView.setText(R.string.new_tab)
5810 } else { // The WebView has loaded a webpage.
5811 // Update the URL edit text if it is not currently being edited.
5812 if (!urlEditText.hasFocus()) {
5813 // 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.
5814 val sanitizedUrl = sanitizeUrl(currentUrl)
5816 // Display the final URL. Getting the URL from the WebView instead of using the one provided by `onPageFinished()` makes websites like YouTube function correctly.
5817 urlEditText.setText(sanitizedUrl)
5819 // Highlight the URL syntax.
5820 UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
5823 // Only populate the title text view if the tab has been fully created.
5825 // Get the custom view from the tab.
5826 val tabView = tab.customView!!
5828 // Get the title text view from the tab.
5829 val tabTitleTextView = tabView.findViewById<TextView>(R.id.title_textview)
5831 // Set the title as the tab text. Sometimes `onReceivedTitle()` is not called, especially when navigating history.
5832 tabTitleTextView.text = nestedScrollWebView.title
5838 // Handle SSL Certificate errors. Suppress the lint warning that ignoring the error might be dangerous.
5839 @SuppressLint("WebViewClientOnReceivedSslError")
5840 override fun onReceivedSslError(view: WebView, handler: SslErrorHandler, error: SslError) {
5841 // Get the current website SSL certificate.
5842 val currentWebsiteSslCertificate = error.certificate
5844 // Extract the individual pieces of information from the current website SSL certificate.
5845 val currentWebsiteIssuedToCName = currentWebsiteSslCertificate.issuedTo.cName
5846 val currentWebsiteIssuedToOName = currentWebsiteSslCertificate.issuedTo.oName
5847 val currentWebsiteIssuedToUName = currentWebsiteSslCertificate.issuedTo.uName
5848 val currentWebsiteIssuedByCName = currentWebsiteSslCertificate.issuedBy.cName
5849 val currentWebsiteIssuedByOName = currentWebsiteSslCertificate.issuedBy.oName
5850 val currentWebsiteIssuedByUName = currentWebsiteSslCertificate.issuedBy.uName
5851 val currentWebsiteSslStartDate = currentWebsiteSslCertificate.validNotBeforeDate
5852 val currentWebsiteSslEndDate = currentWebsiteSslCertificate.validNotAfterDate
5854 // Get the pinned SSL certificate.
5855 val (pinnedSslCertificateStringArray, pinnedSslCertificateDateArray) = nestedScrollWebView.getPinnedSslCertificate()
5857 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
5858 if (nestedScrollWebView.hasPinnedSslCertificate() &&
5859 (currentWebsiteIssuedToCName == pinnedSslCertificateStringArray[0]) &&
5860 (currentWebsiteIssuedToOName == pinnedSslCertificateStringArray[1]) &&
5861 (currentWebsiteIssuedToUName == pinnedSslCertificateStringArray[2]) &&
5862 (currentWebsiteIssuedByCName == pinnedSslCertificateStringArray[3]) &&
5863 (currentWebsiteIssuedByOName == pinnedSslCertificateStringArray[4]) &&
5864 (currentWebsiteIssuedByUName == pinnedSslCertificateStringArray[5]) &&
5865 (currentWebsiteSslStartDate == pinnedSslCertificateDateArray[0]) &&
5866 (currentWebsiteSslEndDate == pinnedSslCertificateDateArray[1])) {
5868 // An SSL certificate is pinned and matches the current domain certificate. Proceed to the website without displaying an error.
5870 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
5871 // Store the SSL error handler.
5872 nestedScrollWebView.sslErrorHandler = handler
5874 // Instantiate an SSL certificate error alert dialog.
5875 val sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error, nestedScrollWebView.webViewFragmentId)
5877 // 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.
5879 // Show the SSL certificate error dialog.
5880 sslCertificateErrorDialogFragment.show(supportFragmentManager, getString(R.string.ssl_certificate_error))
5881 } catch (exception: Exception) {
5882 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
5883 pendingDialogsArrayList.add(PendingDialogDataClass(sslCertificateErrorDialogFragment, getString(R.string.ssl_certificate_error)))
5889 // Check to see if the state is being restored.
5890 if (restoringState) { // The state is being restored.
5891 // Resume the nested scroll WebView JavaScript timers.
5892 nestedScrollWebView.resumeTimers()
5893 } else if (pagePosition == 0) { // The first page is being loaded.
5894 // Set this nested scroll WebView as the current WebView.
5895 currentWebView = nestedScrollWebView
5897 // Get the intent that started the app.
5898 val launchingIntent = intent
5900 // Reset the intent. This prevents a duplicate tab from being created on restart.
5903 // Get the information from the intent.
5904 val launchingIntentAction = launchingIntent.action
5905 val launchingIntentUriData = launchingIntent.data
5906 val launchingIntentStringExtra = launchingIntent.getStringExtra(Intent.EXTRA_TEXT)
5908 // Parse the launching intent URL. Suppress the suggestions of using elvis expressions as they make the logic very difficult to follow.
5909 @Suppress("IfThenToElvis") val urlToLoadString = if ((launchingIntentAction != null) && (launchingIntentAction == Intent.ACTION_WEB_SEARCH)) { // The intent contains a search string.
5910 // Sanitize the search input and convert it to a search.
5911 val encodedSearchString = try {
5912 URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8")
5913 } catch (exception: UnsupportedEncodingException) {
5917 // Add the search URL to the encodedSearchString
5918 searchURL + encodedSearchString
5919 } else if (launchingIntentUriData != null) { // The launching intent contains a URL formatted as a URI.
5920 // Get the URL from the URI.
5921 launchingIntentUriData.toString()
5922 } else if (launchingIntentStringExtra != null) { // The launching intent contains text that might be a URL.
5923 // Get the URL from the string extra.
5924 launchingIntentStringExtra
5925 } else if (urlString != "") { // The activity has been restarted.
5926 // Load the saved URL.
5928 } else { // The is no saved URL and there is no URL in the intent.
5929 // Load the homepage.
5930 sharedPreferences.getString("homepage", getString(R.string.homepage_default_value))
5933 // Load the website if not waiting for the proxy.
5934 if (waitingForProxy) { // Store the URL to be loaded in the Nested Scroll WebView.
5935 nestedScrollWebView.waitingForProxyUrlString = urlToLoadString!!
5936 } else { // Load the URL.
5937 loadUrl(nestedScrollWebView, urlToLoadString!!)
5939 } else { // This is not the first tab.
5941 loadUrl(nestedScrollWebView, urlString)
5943 // Set the focus and display the keyboard if the URL is blank.
5944 if (urlString == "") {
5945 // Request focus for the URL text box.
5946 urlEditText.requestFocus()
5948 // Display the keyboard once the tab layout has settled.
5950 inputMethodManager.showSoftInput(urlEditText, 0)
5956 private fun loadBookmarksFolder() {
5957 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
5958 bookmarksCursor = bookmarksDatabaseHelper!!.getBookmarksByDisplayOrder(currentBookmarksFolderId)
5960 // Populate the bookmarks cursor adapter.
5961 bookmarksCursorAdapter = object : CursorAdapter(this, bookmarksCursor, false) {
5962 override fun newView(context: Context, cursor: Cursor, parent: ViewGroup): View {
5963 // Inflate the individual item layout.
5964 return layoutInflater.inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false)
5967 override fun bindView(view: View, context: Context, cursor: Cursor) {
5968 // Get handles for the views.
5969 val bookmarkFavoriteIcon = view.findViewById<ImageView>(R.id.bookmark_favorite_icon)
5970 val bookmarkNameTextView = view.findViewById<TextView>(R.id.bookmark_name)
5972 // Get the favorite icon byte array from the cursor.
5973 val favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndexOrThrow(FAVORITE_ICON))
5975 // Convert the byte array to a bitmap beginning at the first byte and ending at the last.
5976 val favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.size)
5978 // Display the bitmap in the bookmark favorite icon.
5979 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap)
5981 // Display the bookmark name from the cursor in the bookmark name text view.
5982 bookmarkNameTextView.text = cursor.getString(cursor.getColumnIndexOrThrow(BOOKMARK_NAME))
5984 // Make the font bold for folders.
5985 if (cursor.getInt(cursor.getColumnIndexOrThrow(IS_FOLDER)) == 1)
5986 bookmarkNameTextView.typeface = Typeface.DEFAULT_BOLD
5987 else // Reset the font to default for normal bookmarks.
5988 bookmarkNameTextView.typeface = Typeface.DEFAULT
5992 // Populate the list view with the adapter.
5993 bookmarksListView.adapter = bookmarksCursorAdapter
5995 // Set the bookmarks drawer title.
5996 if (currentBookmarksFolderId == HOME_FOLDER_ID) // The current bookmarks folder is the home folder.
5997 bookmarksTitleTextView.setText(R.string.bookmarks)
5999 bookmarksTitleTextView.text = bookmarksDatabaseHelper!!.getFolderName(currentBookmarksFolderId)
6002 private fun loadUrl(nestedScrollWebView: NestedScrollWebView, url: String) {
6003 // Sanitize the URL.
6004 val urlString = sanitizeUrl(url)
6006 // Apply the domain settings and load the URL.
6007 applyDomainSettings(nestedScrollWebView, urlString, resetTab = true, reloadWebsite = false, loadUrl = true)
6010 private fun loadUrlFromTextBox() {
6011 // 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.
6012 var unformattedUrlString = urlEditText.text.toString().trim { it <= ' ' }
6014 // Create the formatted URL string.
6017 // Check to see if the unformatted URL string is a valid URL. Otherwise, convert it into a search.
6018 if (unformattedUrlString.startsWith("content://") || unformattedUrlString.startsWith("view-source:")) { // This is a content or source URL.
6019 // Load the entire content URL.
6020 urlString = unformattedUrlString
6021 } else if (Patterns.WEB_URL.matcher(unformattedUrlString).matches() || unformattedUrlString.startsWith("http://") || unformattedUrlString.startsWith("https://") ||
6022 unformattedUrlString.startsWith("file://")) { // This is a standard URL.
6024 // Add `https://` at the beginning if there is no protocol. Otherwise the app will segfault.
6025 if (!unformattedUrlString.startsWith("http") && !unformattedUrlString.startsWith("file://"))
6026 unformattedUrlString = "https://$unformattedUrlString"
6028 // Initialize the unformatted URL.
6029 var unformattedUrl: URL? = null
6031 // Convert the unformatted URL string to a URL.
6033 unformattedUrl = URL(unformattedUrlString)
6034 } catch (exception: MalformedURLException) {
6035 exception.printStackTrace()
6038 // Get the components of the URL.
6039 val scheme = unformattedUrl?.protocol
6040 val authority = unformattedUrl?.authority
6041 val path = unformattedUrl?.path
6042 val query = unformattedUrl?.query
6043 val fragment = unformattedUrl?.ref
6046 val uri = Uri.Builder()
6048 // Build the URI from the components of the URL.
6049 uri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment)
6051 // Decode the URI as a UTF-8 string in.
6053 urlString = URLDecoder.decode(uri.build().toString(), "UTF-8")
6054 } catch (exception: UnsupportedEncodingException) {
6055 // Do nothing. The formatted URL string will remain blank.
6057 } else if (unformattedUrlString.isNotEmpty()) { // This is not a URL, but rather a search string.
6058 // Sanitize the search input.
6059 val encodedSearchString = try {
6060 URLEncoder.encode(unformattedUrlString, "UTF-8")
6061 } catch (exception: UnsupportedEncodingException) {
6065 // Add the base search URL.
6066 urlString = searchURL + encodedSearchString
6069 // 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.
6070 urlEditText.clearFocus()
6073 loadUrl(currentWebView!!, urlString)
6076 override fun navigateHistory(url: String, steps: Int) {
6077 // Apply the domain settings.
6078 applyDomainSettings(currentWebView!!, url, resetTab = false, reloadWebsite = false, loadUrl = false)
6080 // Load the history entry.
6081 currentWebView!!.goBackOrForward(steps)
6083 // Update the URL edit text after a delay.
6084 updateUrlEditTextAfterDelay()
6087 override fun openFile(dialogFragment: DialogFragment) {
6089 val dialog = dialogFragment.dialog!!
6091 // Get handles for the views.
6092 val fileNameEditText = dialog.findViewById<EditText>(R.id.file_name_edittext)
6093 val mhtCheckBox = dialog.findViewById<CheckBox>(R.id.mht_checkbox)
6095 // Get the file path string.
6096 val openFilePath = fileNameEditText.text.toString()
6098 // Apply the domain settings. This resets the favorite icon and removes any domain settings.
6099 applyDomainSettings(currentWebView!!, openFilePath, resetTab = true, reloadWebsite = false, loadUrl = false)
6101 // Open the file according to the type.
6102 if (mhtCheckBox.isChecked) { // Force opening of an MHT file.
6104 // Get the MHT file input stream.
6105 val mhtFileInputStream = contentResolver.openInputStream(Uri.parse(openFilePath))
6107 // Create a temporary MHT file.
6108 val temporaryMhtFile = File.createTempFile(TEMPORARY_MHT_FILE, ".mht", cacheDir)
6110 // Get a file output stream for the temporary MHT file.
6111 val temporaryMhtFileOutputStream = FileOutputStream(temporaryMhtFile)
6113 // Create a transfer byte array.
6114 val transferByteArray = ByteArray(1024)
6116 // Create an integer to track the number of bytes read.
6119 // Copy the temporary MHT file input stream to the MHT output stream.
6120 while (mhtFileInputStream!!.read(transferByteArray).also { bytesRead = it } > 0)
6121 temporaryMhtFileOutputStream.write(transferByteArray, 0, bytesRead)
6123 // Flush the temporary MHT file output stream.
6124 temporaryMhtFileOutputStream.flush()
6126 // Close the streams.
6127 temporaryMhtFileOutputStream.close()
6128 mhtFileInputStream.close()
6130 // Load the temporary MHT file.
6131 currentWebView!!.loadUrl(temporaryMhtFile.toString())
6132 } catch (exception: Exception) {
6133 // Display a snackbar.
6134 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
6136 } else { // Let the WebView handle opening of the file.
6138 currentWebView!!.loadUrl(openFilePath)
6141 // The view parameter cannot be removed because it is called from the layout onClick.
6142 fun openNavigationDrawer(@Suppress("UNUSED_PARAMETER")view: View) {
6143 // Open the navigation drawer.
6144 drawerLayout.openDrawer(GravityCompat.START)
6147 private fun openWithApp(url: String) {
6148 // Create an open with app intent with `ACTION_VIEW`.
6149 val openWithAppIntent = Intent(Intent.ACTION_VIEW)
6151 // Set the URI but not the MIME type. This should open all available apps.
6152 openWithAppIntent.data = Uri.parse(url)
6154 // Flag the intent to open in a new task.
6155 openWithAppIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
6159 // Show the chooser.
6160 startActivity(openWithAppIntent)
6161 } catch (exception: ActivityNotFoundException) { // There are no apps available to open the URL.
6162 // Show a snackbar with the error.
6163 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
6167 private fun openWithBrowser(url: String) {
6169 // Create an open with browser intent with `ACTION_VIEW`.
6170 val openWithBrowserIntent = Intent(Intent.ACTION_VIEW)
6172 // Set the URI and the MIME type. `"text/html"` should load browser options.
6173 openWithBrowserIntent.setDataAndType(Uri.parse(url), "text/html")
6175 // Flag the intent to open in a new task.
6176 openWithBrowserIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
6180 // Show the chooser.
6181 startActivity(openWithBrowserIntent)
6182 } catch (exception: ActivityNotFoundException) { // There are no browsers available to open the URL.
6183 // Show a snackbar with the error.
6184 Snackbar.make(currentWebView!!, getString(R.string.error, exception), Snackbar.LENGTH_INDEFINITE).show()
6188 override fun pinnedErrorGoBack() {
6189 // Get the current web back forward list.
6190 val webBackForwardList = currentWebView!!.copyBackForwardList()
6192 // Get the previous entry URL.
6193 val previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.currentIndex - 1).url
6195 // Apply the domain settings.
6196 applyDomainSettings(currentWebView!!, previousUrl, resetTab = false, reloadWebsite = false, loadUrl = false)
6199 currentWebView!!.goBack()
6201 // Update the URL edit text after a delay.
6202 updateUrlEditTextAfterDelay()
6205 private fun sanitizeUrl(urlString: String): String {
6206 // Initialize a sanitized URL string.
6207 var sanitizedUrlString = urlString
6209 // Sanitize tracking queries.
6210 if (sanitizeTrackingQueries)
6211 sanitizedUrlString = SanitizeUrlHelper.sanitizeTrackingQueries(sanitizedUrlString)
6213 // Sanitize AMP redirects.
6214 if (sanitizeAmpRedirects)
6215 sanitizedUrlString = SanitizeUrlHelper.sanitizeAmpRedirects(sanitizedUrlString)
6217 // Return the sanitized URL string.
6218 return sanitizedUrlString
6221 override fun saveWithAndroidDownloadManager(dialogFragment: DialogFragment) {
6223 val dialog = dialogFragment.dialog!!
6225 // Get handles for the dialog views.
6226 val dialogUrlEditText = dialog.findViewById<EditText>(R.id.url_edittext)
6227 val downloadDirectoryRadioGroup = dialog.findViewById<RadioGroup>(R.id.download_directory_radiogroup)
6228 val dialogFileNameEditText = dialog.findViewById<EditText>(R.id.file_name_edittext)
6230 // Get the string from the edit texts, which may have been modified by the user.
6231 val saveUrlString = dialogUrlEditText.text.toString()
6232 val fileNameString = dialogFileNameEditText.text.toString()
6234 // Get a handle for the system download service.
6235 val downloadManager = getSystemService(DOWNLOAD_SERVICE) as DownloadManager
6238 val downloadRequest = DownloadManager.Request(Uri.parse(saveUrlString))
6240 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
6241 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
6242 if (cookieManager.acceptCookie()) {
6243 // Get the cookies for the URL.
6244 val cookiesString = cookieManager.getCookie(saveUrlString)
6246 // Add the cookies to the download request. In the HTTP request header, cookies are named `Cookie`.
6247 downloadRequest.addRequestHeader("Cookie", cookiesString)
6250 // Get the download directory.
6251 val downloadDirectory = when (downloadDirectoryRadioGroup.checkedRadioButtonId) {
6252 R.id.downloads_radiobutton -> Environment.DIRECTORY_DOWNLOADS
6253 R.id.documents_radiobutton -> Environment.DIRECTORY_DOCUMENTS
6254 R.id.pictures_radiobutton -> Environment.DIRECTORY_PICTURES
6255 else -> Environment.DIRECTORY_MUSIC
6258 // Set the download destination.
6259 downloadRequest.setDestinationInExternalPublicDir(downloadDirectory, fileNameString)
6261 // Allow media scanner to index the download if it is a media file. This is automatic for API >= 29.
6262 @Suppress("DEPRECATION")
6263 if (Build.VERSION.SDK_INT <= 28)
6264 downloadRequest.allowScanningByMediaScanner()
6266 // Add the URL as the description for the download.
6267 downloadRequest.setDescription(saveUrlString)
6269 // Show the download notification after the download is completed.
6270 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
6272 // Initiate the download.
6273 downloadManager.enqueue(downloadRequest)
6276 private fun saveWithExternalApp(url: String) {
6277 // Create a download intent. Not specifying the action type will display the maximum number of options.
6278 val downloadIntent = Intent()
6280 // Set the URI and the mime type.
6281 downloadIntent.setDataAndType(Uri.parse(url), "text/html")
6283 // Flag the intent to open in a new task.
6284 downloadIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
6286 // Show the chooser.
6287 startActivity(Intent.createChooser(downloadIntent, getString(R.string.download_with_external_app)))
6290 override fun saveWithPrivacyBrowser(originalUrlString: String, fileNameString: String, dialogFragment: DialogFragment) {
6291 // Store the URL. This will be used in the save URL activity result launcher.
6292 saveUrlString = if (originalUrlString.startsWith("data:")) {
6293 // Save the original URL.
6297 val dialog = dialogFragment.dialog!!
6299 // Get a handle for the dialog URL edit text.
6300 val dialogUrlEditText = dialog.findViewById<EditText>(R.id.url_edittext)
6302 // Get the URL from the edit text, which may have been modified by the user.
6303 dialogUrlEditText.text.toString()
6306 // Open the file picker.
6307 saveUrlActivityResultLauncher.launch(fileNameString)
6310 private fun setCurrentWebView(pageNumber: Int) {
6311 // Stop the swipe to refresh indicator if it is running
6312 swipeRefreshLayout.isRefreshing = false
6314 // Try to set the current WebView. This will fail if the WebView has not yet been populated.
6316 // Get the WebView tab fragment.
6317 val webViewTabFragment = webViewStateAdapter!!.getPageFragment(pageNumber)
6319 // Get the fragment view.
6320 val webViewFragmentView = webViewTabFragment.view
6322 // Store the current WebView.
6323 currentWebView = webViewFragmentView!!.findViewById(R.id.nestedscroll_webview)
6325 // Update the status of swipe to refresh.
6326 if (currentWebView!!.swipeToRefresh) { // Swipe to refresh is enabled.
6327 // Enable the swipe refresh layout if the WebView is scrolled all the way to the top. It is updated every time the scroll changes.
6328 swipeRefreshLayout.isEnabled = (currentWebView!!.scrollY == 0)
6329 } else { // Swipe to refresh is disabled.
6330 // Disable the swipe refresh layout.
6331 swipeRefreshLayout.isEnabled = false
6334 // Set the cookie status.
6335 cookieManager.setAcceptCookie(currentWebView!!.acceptCookies)
6337 // Update the privacy icons. `true` redraws the icons in the app bar.
6338 updatePrivacyIcons(true)
6340 // Get a handle for the input method manager.
6341 val inputMethodManager = (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager)
6343 // Get the current URL.
6344 val urlString = currentWebView!!.url
6346 // Update the URL edit text if not loading a new intent. Otherwise, this will be handled by `onPageStarted()` (if called) and `onPageFinished()`.
6347 if (!loadingNewIntent) { // A new intent is not being loaded.
6348 if ((urlString == null) || (urlString == "about:blank")) { // The WebView is blank.
6349 // Display the hint in the URL edit text.
6350 urlEditText.setText("")
6352 // Request focus for the URL text box.
6353 urlEditText.requestFocus()
6355 // Display the keyboard.
6356 inputMethodManager.showSoftInput(urlEditText, 0)
6357 } else { // The WebView has a loaded URL.
6358 // Clear the focus from the URL text box.
6359 urlEditText.clearFocus()
6361 // Hide the soft keyboard.
6362 inputMethodManager.hideSoftInputFromWindow(currentWebView!!.windowToken, 0)
6364 // Display the current URL in the URL text box.
6365 urlEditText.setText(urlString)
6367 // Highlight the URL syntax.
6368 UrlHelper.highlightSyntax(urlEditText, initialGrayColorSpan, finalGrayColorSpan, redColorSpan)
6370 } else { // A new intent is being loaded.
6371 // Reset the loading new intent flag.
6372 loadingNewIntent = false
6375 // Set the background to indicate the domain settings status.
6376 if (currentWebView!!.domainSettingsApplied) {
6377 // Set a background on the URL relative layout to indicate that custom domain settings are being used.
6378 urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.drawable.domain_settings_url_background)
6380 // Remove any background on the URL relative layout.
6381 urlRelativeLayout.background = AppCompatResources.getDrawable(this, R.color.transparent)
6383 } catch (exception: Exception) { // Try again in 10 milliseconds if the WebView has not yet been populated.
6384 // Create a handler to set the current WebView.
6385 val setCurrentWebViewHandler = Handler(Looper.getMainLooper())
6387 // Create a runnable to set the current WebView.
6388 val setCurrentWebWebRunnable = Runnable {
6389 // Set the current WebView.
6390 setCurrentWebView(pageNumber)
6393 // Try setting the current WebView again after 10 milliseconds.
6394 setCurrentWebViewHandler.postDelayed(setCurrentWebWebRunnable, 10)
6398 // The view parameter cannot be removed because it is called from the layout onClick.
6399 fun toggleBookmarksDrawerPinned(@Suppress("UNUSED_PARAMETER")view: View?) {
6400 // Toggle the bookmarks drawer pinned tracker.
6401 bookmarksDrawerPinned = !bookmarksDrawerPinned
6403 // Update the bookmarks drawer pinned image view.
6404 updateBookmarksDrawerPinnedImageView()
6407 private fun updateBookmarksDrawerPinnedImageView() {
6408 // Set the current icon.
6409 if (bookmarksDrawerPinned)
6410 bookmarksDrawerPinnedImageView.setImageResource(R.drawable.pin_selected)
6412 bookmarksDrawerPinnedImageView.setImageResource(R.drawable.pin)
6415 private fun updateDomainsSettingsSet() {
6416 // Reset the domains settings set.
6417 domainsSettingsSet = HashSet()
6419 // Get a domains cursor.
6420 val domainsCursor = domainsDatabaseHelper!!.domainNameCursorOrderedByDomain
6422 // Get the current count of domains.
6423 val domainsCount = domainsCursor.count
6425 // Get the domain name column index.
6426 val domainNameColumnIndex = domainsCursor.getColumnIndexOrThrow(DOMAIN_NAME)
6428 // Populate the domain settings set.
6429 for (i in 0 until domainsCount) {
6430 // Move the domains cursor to the current row.
6431 domainsCursor.moveToPosition(i)
6433 // Store the domain name in the domain settings set.
6434 domainsSettingsSet.add(domainsCursor.getString(domainNameColumnIndex))
6437 // Close the domains cursor.
6438 domainsCursor.close()
6441 override fun updateFontSize(dialogFragment: DialogFragment) {
6443 val dialog = dialogFragment.dialog!!
6445 // Get a handle for the font size edit text.
6446 val fontSizeEditText = dialog.findViewById<EditText>(R.id.font_size_edittext)
6448 // Initialize the new font size variable with the current font size.
6449 var newFontSize = currentWebView!!.settings.textZoom
6451 // Get the font size from the edit text.
6453 newFontSize = fontSizeEditText.text.toString().toInt()
6454 } catch (exception: Exception) {
6455 // If the edit text does not contain a valid font size do nothing.
6458 // Apply the new font size.
6459 currentWebView!!.settings.textZoom = newFontSize
6462 private fun updatePrivacyIcons(runInvalidateOptionsMenu: Boolean) {
6463 // Only update the privacy icons if the options menu and the current WebView have already been populated.
6464 if ((optionsMenu != null) && (currentWebView != null)) {
6465 // Update the privacy icon.
6466 if (currentWebView!!.settings.javaScriptEnabled) // JavaScript is enabled.
6467 optionsPrivacyMenuItem.setIcon(R.drawable.javascript_enabled)
6468 else if (currentWebView!!.acceptCookies) // JavaScript is disabled but cookies are enabled.
6469 optionsPrivacyMenuItem.setIcon(R.drawable.warning)
6470 else // All the dangerous features are disabled.
6471 optionsPrivacyMenuItem.setIcon(R.drawable.privacy_mode)
6473 // Update the cookies icon.
6474 if (currentWebView!!.acceptCookies)
6475 optionsCookiesMenuItem.setIcon(R.drawable.cookies_enabled)
6477 optionsCookiesMenuItem.setIcon(R.drawable.cookies_disabled)
6479 // Update the refresh icon.
6480 if (optionsRefreshMenuItem.title == getString(R.string.refresh)) // The refresh icon is displayed.
6481 optionsRefreshMenuItem.setIcon(R.drawable.refresh_enabled)
6482 else // The stop icon is displayed.
6483 optionsRefreshMenuItem.setIcon(R.drawable.close_blue)
6485 // `invalidateOptionsMenu()` calls `onPrepareOptionsMenu()` and redraws the icons in the app bar.
6486 if (runInvalidateOptionsMenu)
6487 invalidateOptionsMenu()
6491 fun updateUrlEditTextAfterDelay() {
6492 // Create a handler to update the URL edit box.
6493 val urlEditTextUpdateHandler = Handler(Looper.getMainLooper())
6495 // Create a runnable to update the URL edit box.
6496 val urlEditTextUpdateRunnable = Runnable {
6497 // Update the URL edit text.
6498 urlEditText.setText(currentWebView!!.url)
6500 // Disable the wide viewport if the source is being viewed.
6501 if (currentWebView!!.url!!.startsWith("view-source:"))
6502 currentWebView!!.settings.useWideViewPort = false
6505 // Update the URL edit text after 50 milliseconds, so that the WebView has enough time to navigate to the new URL.
6506 urlEditTextUpdateHandler.postDelayed(urlEditTextUpdateRunnable, 50)