2 * Copyright © 2015-2020 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 <https://www.stoutner.com/privacy-browser>.
8 * Privacy Browser 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 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. If not, see <http://www.gnu.org/licenses/>.
22 package com.stoutner.privacybrowser.activities;
24 import android.Manifest;
25 import android.annotation.SuppressLint;
26 import android.app.Activity;
27 import android.app.Dialog;
28 import android.app.DownloadManager;
29 import android.app.SearchManager;
30 import android.content.ActivityNotFoundException;
31 import android.content.BroadcastReceiver;
32 import android.content.ClipData;
33 import android.content.ClipboardManager;
34 import android.content.Context;
35 import android.content.Intent;
36 import android.content.IntentFilter;
37 import android.content.SharedPreferences;
38 import android.content.pm.PackageManager;
39 import android.content.res.Configuration;
40 import android.database.Cursor;
41 import android.graphics.Bitmap;
42 import android.graphics.BitmapFactory;
43 import android.graphics.Typeface;
44 import android.graphics.drawable.BitmapDrawable;
45 import android.graphics.drawable.Drawable;
46 import android.net.Uri;
47 import android.net.http.SslCertificate;
48 import android.net.http.SslError;
49 import android.os.Build;
50 import android.os.Bundle;
51 import android.os.Handler;
52 import android.os.Message;
53 import android.preference.PreferenceManager;
54 import android.print.PrintDocumentAdapter;
55 import android.print.PrintManager;
56 import android.text.Editable;
57 import android.text.Spanned;
58 import android.text.TextWatcher;
59 import android.text.style.ForegroundColorSpan;
60 import android.util.Patterns;
61 import android.view.ContextMenu;
62 import android.view.GestureDetector;
63 import android.view.KeyEvent;
64 import android.view.Menu;
65 import android.view.MenuItem;
66 import android.view.MotionEvent;
67 import android.view.View;
68 import android.view.ViewGroup;
69 import android.view.WindowManager;
70 import android.view.inputmethod.InputMethodManager;
71 import android.webkit.CookieManager;
72 import android.webkit.HttpAuthHandler;
73 import android.webkit.SslErrorHandler;
74 import android.webkit.ValueCallback;
75 import android.webkit.WebBackForwardList;
76 import android.webkit.WebChromeClient;
77 import android.webkit.WebResourceResponse;
78 import android.webkit.WebSettings;
79 import android.webkit.WebStorage;
80 import android.webkit.WebView;
81 import android.webkit.WebViewClient;
82 import android.webkit.WebViewDatabase;
83 import android.widget.ArrayAdapter;
84 import android.widget.CursorAdapter;
85 import android.widget.EditText;
86 import android.widget.FrameLayout;
87 import android.widget.ImageView;
88 import android.widget.LinearLayout;
89 import android.widget.ListView;
90 import android.widget.ProgressBar;
91 import android.widget.RadioButton;
92 import android.widget.RelativeLayout;
93 import android.widget.TextView;
95 import androidx.annotation.NonNull;
96 import androidx.appcompat.app.ActionBar;
97 import androidx.appcompat.app.ActionBarDrawerToggle;
98 import androidx.appcompat.app.AppCompatActivity;
99 import androidx.appcompat.widget.Toolbar;
100 import androidx.coordinatorlayout.widget.CoordinatorLayout;
101 import androidx.core.app.ActivityCompat;
102 import androidx.core.content.ContextCompat;
103 import androidx.core.view.GravityCompat;
104 import androidx.drawerlayout.widget.DrawerLayout;
105 import androidx.fragment.app.DialogFragment;
106 import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
107 import androidx.viewpager.widget.ViewPager;
109 import com.google.android.material.appbar.AppBarLayout;
110 import com.google.android.material.floatingactionbutton.FloatingActionButton;
111 import com.google.android.material.navigation.NavigationView;
112 import com.google.android.material.snackbar.Snackbar;
113 import com.google.android.material.tabs.TabLayout;
115 import com.stoutner.privacybrowser.BuildConfig;
116 import com.stoutner.privacybrowser.R;
117 import com.stoutner.privacybrowser.adapters.WebViewPagerAdapter;
118 import com.stoutner.privacybrowser.asynctasks.GetHostIpAddresses;
119 import com.stoutner.privacybrowser.asynctasks.PopulateBlocklists;
120 import com.stoutner.privacybrowser.asynctasks.SaveUrl;
121 import com.stoutner.privacybrowser.asynctasks.SaveWebpageImage;
122 import com.stoutner.privacybrowser.dialogs.AdConsentDialog;
123 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
124 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
125 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
126 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
127 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
128 import com.stoutner.privacybrowser.dialogs.FontSizeDialog;
129 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
130 import com.stoutner.privacybrowser.dialogs.OpenDialog;
131 import com.stoutner.privacybrowser.dialogs.ProxyNotInstalledDialog;
132 import com.stoutner.privacybrowser.dialogs.PinnedMismatchDialog;
133 import com.stoutner.privacybrowser.dialogs.SaveDialog;
134 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
135 import com.stoutner.privacybrowser.dialogs.StoragePermissionDialog;
136 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
137 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
138 import com.stoutner.privacybrowser.dialogs.WaitingForProxyDialog;
139 import com.stoutner.privacybrowser.fragments.WebViewTabFragment;
140 import com.stoutner.privacybrowser.helpers.AdHelper;
141 import com.stoutner.privacybrowser.helpers.BlocklistHelper;
142 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
143 import com.stoutner.privacybrowser.helpers.CheckPinnedMismatchHelper;
144 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
145 import com.stoutner.privacybrowser.helpers.FileNameHelper;
146 import com.stoutner.privacybrowser.helpers.ProxyHelper;
147 import com.stoutner.privacybrowser.views.NestedScrollWebView;
149 import java.io.ByteArrayInputStream;
150 import java.io.ByteArrayOutputStream;
152 import java.io.IOException;
153 import java.io.UnsupportedEncodingException;
154 import java.net.MalformedURLException;
156 import java.net.URLDecoder;
157 import java.net.URLEncoder;
158 import java.util.ArrayList;
159 import java.util.Date;
160 import java.util.HashMap;
161 import java.util.HashSet;
162 import java.util.List;
163 import java.util.Map;
164 import java.util.Objects;
165 import java.util.Set;
167 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
168 EditBookmarkDialog.EditBookmarkListener, EditBookmarkFolderDialog.EditBookmarkFolderListener, FontSizeDialog.UpdateFontSizeListener, NavigationView.OnNavigationItemSelectedListener,
169 OpenDialog.OpenListener, PinnedMismatchDialog.PinnedMismatchListener, PopulateBlocklists.PopulateBlocklistsListener, SaveDialog.SaveWebpageListener,
170 StoragePermissionDialog.StoragePermissionDialogListener, UrlHistoryDialog.NavigateHistoryListener, WebViewTabFragment.NewTabListener {
172 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`, `onResume()`, and `applyProxy()`.
173 public static String orbotStatus = "unknown";
175 // The WebView pager adapter is accessed from `HttpAuthenticationDialog`, `PinnedMismatchDialog`, and `SslCertificateErrorDialog`. It is also used in `onCreate()`, `onResume()`, and `addTab()`.
176 public static WebViewPagerAdapter webViewPagerAdapter;
178 // The load URL on restart variables are public static so they can be accessed from `BookmarksActivity`. They are used in `onRestart()`.
179 public static boolean loadUrlOnRestart;
180 public static String urlToLoadOnRestart;
182 // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onRestart()`.
183 public static boolean restartFromBookmarksActivity;
185 // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
186 // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
187 public static String currentBookmarksFolder;
189 // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
190 public final static int UNRECOGNIZED_USER_AGENT = -1;
191 public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
192 public final static int SETTINGS_CUSTOM_USER_AGENT = 12;
193 public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
194 public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
195 public final static int DOMAINS_CUSTOM_USER_AGENT = 13;
197 // Start activity for result request codes. The public static entries are accessed from `OpenDialog()` and `SaveWebpageDialog()`.
198 public final static int BROWSE_OPEN_REQUEST_CODE = 0;
199 public final static int BROWSE_SAVE_WEBPAGE_REQUEST_CODE = 1;
200 private final int BROWSE_FILE_UPLOAD_REQUEST_CODE = 2;
202 // The proxy mode is public static so it can be accessed from `ProxyHelper()`.
203 // It is also used in `onRestart()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `applyAppSettings()`, and `applyProxy()`.
204 // It will be updated in `applyAppSettings()`, but it needs to be initialized here or the first run of `onPrepareOptionsMenu()` crashes.
205 public static String proxyMode = ProxyHelper.NONE;
208 // The permission result request codes are used in `onCreateContextMenu()`, `onRequestPermissionResult()`, `onSaveWebpage()`, `onCloseStoragePermissionDialog()`, and `initializeWebView()`.
209 private final int PERMISSION_OPEN_REQUEST_CODE = 0;
210 private final int PERMISSION_SAVE_URL_REQUEST_CODE = 1;
211 private final int PERMISSION_SAVE_AS_ARCHIVE_REQUEST_CODE = 2;
212 private final int PERMISSION_SAVE_AS_IMAGE_REQUEST_CODE = 3;
214 // The current WebView is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
215 // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, `applyProxy()`, and `applyDomainSettings()`.
216 private NestedScrollWebView currentWebView;
218 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
219 private final Map<String, String> customHeaders = new HashMap<>();
221 // The search URL is set in `applyAppSettings()` and used in `onNewIntent()`, `loadUrlFromTextBox()`, `initializeApp()`, and `initializeWebView()`.
222 private String searchURL;
224 // The options menu is set in `onCreateOptionsMenu()` and used in `onOptionsItemSelected()`, `updatePrivacyIcons()`, and `initializeWebView()`.
225 private Menu optionsMenu;
227 // The blocklists are populated in `finishedPopulatingBlocklists()` and accessed from `initializeWebView()`.
228 private ArrayList<List<String[]>> easyList;
229 private ArrayList<List<String[]>> easyPrivacy;
230 private ArrayList<List<String[]>> fanboysAnnoyanceList;
231 private ArrayList<List<String[]>> fanboysSocialList;
232 private ArrayList<List<String[]>> ultraList;
233 private ArrayList<List<String[]>> ultraPrivacy;
235 // `webViewDefaultUserAgent` is used in `onCreate()` and `onPrepareOptionsMenu()`.
236 private String webViewDefaultUserAgent;
238 // The incognito mode is set in `applyAppSettings()` and used in `initializeWebView()`.
239 private boolean incognitoModeEnabled;
241 // The full screen browsing mode tracker is set it `applyAppSettings()` and used in `initializeWebView()`.
242 private boolean fullScreenBrowsingModeEnabled;
244 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
245 private boolean inFullScreenBrowsingMode;
247 // The app bar trackers are set in `applyAppSettings()` and used in `initializeWebView()`.
248 private boolean hideAppBar;
249 private boolean scrollAppBar;
251 // The loading new intent tracker is set in `onNewIntent()` and used in `setCurrentWebView()`.
252 private boolean loadingNewIntent;
254 // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
255 private boolean reapplyDomainSettingsOnRestart;
257 // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
258 private boolean reapplyAppSettingsOnRestart;
260 // `displayingFullScreenVideo` is used in `onCreate()` and `onResume()`.
261 private boolean displayingFullScreenVideo;
263 // `orbotStatusBroadcastReceiver` is used in `onCreate()` and `onDestroy()`.
264 private BroadcastReceiver orbotStatusBroadcastReceiver;
266 // The waiting for proxy boolean is used in `onResume()`, `initializeApp()` and `applyProxy()`.
267 private boolean waitingForProxy = false;
269 // The action bar drawer toggle is initialized in `onCreate()` and used in `onResume()`.
270 private ActionBarDrawerToggle actionBarDrawerToggle;
272 // The color spans are used in `onCreate()` and `highlightUrlText()`.
273 private ForegroundColorSpan redColorSpan;
274 private ForegroundColorSpan initialGrayColorSpan;
275 private ForegroundColorSpan finalGrayColorSpan;
277 // The drawer header padding variables are used in `onCreate()` and `onConfigurationChanged()`.
278 private int drawerHeaderPaddingLeftAndRight;
279 private int drawerHeaderPaddingTop;
280 private int drawerHeaderPaddingBottom;
282 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onDestroy`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`,
283 // and `loadBookmarksFolder()`.
284 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
286 // `bookmarksCursor` is used in `onDestroy()`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
287 private Cursor bookmarksCursor;
289 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
290 private CursorAdapter bookmarksCursorAdapter;
292 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
293 private String oldFolderNameString;
295 // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
296 private ValueCallback<Uri[]> fileChooserCallback;
298 // The default progress view offsets are set in `onCreate()` and used in `initializeWebView()`.
299 private int defaultProgressViewStartOffset;
300 private int defaultProgressViewEndOffset;
302 // The swipe refresh layout top padding is used when exiting full screen browsing mode. It is used in an inner class in `initializeWebView()`.
303 private int swipeRefreshLayoutPaddingTop;
305 // The URL sanitizers are set in `applyAppSettings()` and used in `sanitizeUrl()`.
306 private boolean sanitizeGoogleAnalytics;
307 private boolean sanitizeFacebookClickIds;
308 private boolean sanitizeTwitterAmpRedirects;
310 // The file path strings are used in `onSaveWebpage()` and `onRequestPermissionResult()`
311 private String openFilePath;
312 private String saveWebpageUrl;
313 private String saveWebpageFilePath;
316 // Remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
317 @SuppressLint("ClickableViewAccessibility")
318 protected void onCreate(Bundle savedInstanceState) {
319 if (Build.VERSION.SDK_INT >= 21) {
320 WebView.enableSlowWholeDocumentDraw();
323 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
324 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
326 // Get a handle for the shared preferences.
327 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
329 // Get the theme and screenshot preferences.
330 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
331 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
333 // Disable screenshots if not allowed.
334 if (!allowScreenshots) {
335 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
338 // Set the activity theme.
340 setTheme(R.style.PrivacyBrowserDark);
342 setTheme(R.style.PrivacyBrowserLight);
345 // Run the default commands.
346 super.onCreate(savedInstanceState);
348 // Set the content view.
349 setContentView(R.layout.main_framelayout);
351 // Get handles for the views that need to be modified.
352 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
353 Toolbar toolbar = findViewById(R.id.toolbar);
354 ViewPager webViewPager = findViewById(R.id.webviewpager);
356 // Set the action bar. `SupportActionBar` must be used until the minimum API is >= 21.
357 setSupportActionBar(toolbar);
359 // Get a handle for the action bar.
360 ActionBar actionBar = getSupportActionBar();
362 // This is needed to get rid of the Android Studio warning that the action bar might be null.
363 assert actionBar != null;
365 // Add the custom layout, which shows the URL text bar.
366 actionBar.setCustomView(R.layout.url_app_bar);
367 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
369 // Initially disable the sliding drawers. They will be enabled once the blocklists are loaded.
370 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
372 // Create the hamburger icon at the start of the AppBar.
373 actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
375 // Initialize the web view pager adapter.
376 webViewPagerAdapter = new WebViewPagerAdapter(getSupportFragmentManager());
378 // Set the pager adapter on the web view pager.
379 webViewPager.setAdapter(webViewPagerAdapter);
381 // Store up to 100 tabs in memory.
382 webViewPager.setOffscreenPageLimit(100);
384 // Populate the blocklists.
385 new PopulateBlocklists(this, this).execute();
389 protected void onNewIntent(Intent intent) {
390 // Run the default commands.
391 super.onNewIntent(intent);
393 // Replace the intent that started the app with this one.
396 // Process the intent here if Privacy Browser is fully initialized. If the process has been killed by the system while sitting in the background, this will be handled in `initializeWebView()`.
397 if (ultraPrivacy != null) {
398 // Get the information from the intent.
399 String intentAction = intent.getAction();
400 Uri intentUriData = intent.getData();
402 // Determine if this is a web search.
403 boolean isWebSearch = ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH));
405 // 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.
406 if (intentUriData != null || isWebSearch) {
407 // Get the shared preferences.
408 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
410 // Create a URL string.
413 // If the intent action is a web search, perform the search.
415 // Create an encoded URL string.
416 String encodedUrlString;
418 // Sanitize the search input and convert it to a search.
420 encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
421 } catch (UnsupportedEncodingException exception) {
422 encodedUrlString = "";
425 // Add the base search URL.
426 url = searchURL + encodedUrlString;
427 } else { // The intent should contain a URL.
428 // Set the intent data as the URL.
429 url = intentUriData.toString();
432 // Add a new tab if specified in the preferences.
433 if (sharedPreferences.getBoolean("open_intents_in_new_tab", true)) { // Load the URL in a new tab.
434 // Set the loading new intent flag.
435 loadingNewIntent = true;
438 addNewTab(url, true);
439 } else { // Load the URL in the current tab.
441 loadUrl(currentWebView, url);
444 // Get a handle for the drawer layout.
445 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
447 // Close the navigation drawer if it is open.
448 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
449 drawerLayout.closeDrawer(GravityCompat.START);
452 // Close the bookmarks drawer if it is open.
453 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
454 drawerLayout.closeDrawer(GravityCompat.END);
461 public void onRestart() {
462 // Run the default commands.
465 // Apply the app settings if returning from the Settings activity.
466 if (reapplyAppSettingsOnRestart) {
467 // Reset the reapply app settings on restart tracker.
468 reapplyAppSettingsOnRestart = false;
470 // Apply the app settings.
474 // Apply the domain settings if returning from the settings or domains activity.
475 if (reapplyDomainSettingsOnRestart) {
476 // Reset the reapply domain settings on restart tracker.
477 reapplyDomainSettingsOnRestart = false;
479 // Reapply the domain settings for each tab.
480 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
481 // Get the WebView tab fragment.
482 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
484 // Get the fragment view.
485 View fragmentView = webViewTabFragment.getView();
487 // Only reload the WebViews if they exist.
488 if (fragmentView != null) {
489 // Get the nested scroll WebView from the tab fragment.
490 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
492 // Reset the current domain name so the domain settings will be reapplied.
493 nestedScrollWebView.resetCurrentDomainName();
495 // Reapply the domain settings if the URL is not null, which can happen if an empty tab is active when returning from settings.
496 if (nestedScrollWebView.getUrl() != null) {
497 applyDomainSettings(nestedScrollWebView, nestedScrollWebView.getUrl(), false, true);
503 // Load the URL on restart (used when loading a bookmark).
504 if (loadUrlOnRestart) {
505 // Load the specified URL.
506 loadUrl(currentWebView, urlToLoadOnRestart);
508 // Reset the load on restart tracker.
509 loadUrlOnRestart = false;
512 // Update the bookmarks drawer if returning from the Bookmarks activity.
513 if (restartFromBookmarksActivity) {
514 // Get a handle for the drawer layout.
515 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
517 // Close the bookmarks drawer.
518 drawerLayout.closeDrawer(GravityCompat.END);
520 // Reload the bookmarks drawer.
521 loadBookmarksFolder();
523 // Reset `restartFromBookmarksActivity`.
524 restartFromBookmarksActivity = false;
527 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
528 updatePrivacyIcons(true);
531 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
533 public void onResume() {
534 // Run the default commands.
537 // Resume any WebViews.
538 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
539 // Get the WebView tab fragment.
540 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
542 // Get the fragment view.
543 View fragmentView = webViewTabFragment.getView();
545 // Only resume the WebViews if they exist (they won't when the app is first created).
546 if (fragmentView != null) {
547 // Get the nested scroll WebView from the tab fragment.
548 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
550 // Resume the nested scroll WebView JavaScript timers.
551 nestedScrollWebView.resumeTimers();
553 // Resume the nested scroll WebView.
554 nestedScrollWebView.onResume();
558 // Reapply the proxy settings if the system is using a proxy. This redisplays the appropriate alert dialog.
559 if (!proxyMode.equals(ProxyHelper.NONE)) {
563 // Reapply any system UI flags and the ad in the free flavor.
564 if (displayingFullScreenVideo || inFullScreenBrowsingMode) { // The system is displaying a website or a video in full screen mode.
565 // Get a handle for the root frame layouts.
566 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
568 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
569 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
571 /* Hide the system bars.
572 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
573 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
574 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
575 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
577 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
578 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
579 } else if (BuildConfig.FLAVOR.contentEquals("free")) { // The system in not in full screen mode.
581 AdHelper.resumeAd(findViewById(R.id.adview));
586 public void onPause() {
587 // Run the default commands.
590 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
591 // Get the WebView tab fragment.
592 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
594 // Get the fragment view.
595 View fragmentView = webViewTabFragment.getView();
597 // Only pause the WebViews if they exist (they won't when the app is first created).
598 if (fragmentView != null) {
599 // Get the nested scroll WebView from the tab fragment.
600 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
602 // Pause the nested scroll WebView.
603 nestedScrollWebView.onPause();
605 // Pause the nested scroll WebView JavaScript timers.
606 nestedScrollWebView.pauseTimers();
610 // Pause the ad or it will continue to consume resources in the background on the free flavor.
611 if (BuildConfig.FLAVOR.contentEquals("free")) {
613 AdHelper.pauseAd(findViewById(R.id.adview));
618 public void onDestroy() {
619 // Unregister the orbot status broadcast receiver.
620 this.unregisterReceiver(orbotStatusBroadcastReceiver);
622 // Close the bookmarks cursor and database.
623 bookmarksCursor.close();
624 bookmarksDatabaseHelper.close();
626 // Run the default commands.
631 public boolean onCreateOptionsMenu(Menu menu) {
632 // Inflate the menu. This adds items to the action bar if it is present.
633 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
635 // Store a handle for the options menu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons()`.
638 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
639 updatePrivacyIcons(false);
641 // Get handles for the menu items.
642 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
643 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
644 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
645 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
646 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
647 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
648 MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
650 // Only display third-party cookies if API >= 21
651 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
653 // Only display the form data menu items if the API < 26.
654 toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
655 clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
657 // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
658 clearFormDataMenuItem.setEnabled(Build.VERSION.SDK_INT < 26);
660 // Only show Ad Consent if this is the free flavor.
661 adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
663 // Get the shared preferences.
664 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
666 // Get the dark theme and app bar preferences..
667 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
668 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
670 // 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.
671 if (displayAdditionalAppBarIcons) {
672 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
673 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
674 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
675 } else { //Do not display the additional icons.
676 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
677 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
678 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
681 // Replace Refresh with Stop if a URL is already loading.
682 if (currentWebView != null && currentWebView.getProgress() != 100) {
684 refreshMenuItem.setTitle(R.string.stop);
686 // If the icon is displayed in the AppBar, set it according to the theme.
687 if (displayAdditionalAppBarIcons) {
689 refreshMenuItem.setIcon(R.drawable.close_dark);
691 refreshMenuItem.setIcon(R.drawable.close_light);
701 public boolean onPrepareOptionsMenu(Menu menu) {
702 // Get handles for the menu items.
703 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
704 MenuItem firstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
705 MenuItem thirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
706 MenuItem domStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
707 MenuItem saveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
708 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
709 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
710 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
711 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
712 MenuItem blocklistsMenuItem = menu.findItem(R.id.blocklists);
713 MenuItem easyListMenuItem = menu.findItem(R.id.easylist);
714 MenuItem easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
715 MenuItem fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
716 MenuItem fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
717 MenuItem ultraListMenuItem = menu.findItem(R.id.ultralist);
718 MenuItem ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
719 MenuItem blockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
720 MenuItem proxyMenuItem = menu.findItem(R.id.proxy);
721 MenuItem userAgentMenuItem = menu.findItem(R.id.user_agent);
722 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
723 MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
724 MenuItem wideViewportMenuItem = menu.findItem(R.id.wide_viewport);
725 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
726 MenuItem nightModeMenuItem = menu.findItem(R.id.night_mode);
728 // Get a handle for the cookie manager.
729 CookieManager cookieManager = CookieManager.getInstance();
731 // Initialize the current user agent string and the font size.
732 String currentUserAgent = getString(R.string.user_agent_privacy_browser);
735 // 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.
736 if (currentWebView != null) {
737 // Set the add or edit domain text.
738 if (currentWebView.getDomainSettingsApplied()) {
739 addOrEditDomain.setTitle(R.string.edit_domain_settings);
741 addOrEditDomain.setTitle(R.string.add_domain_settings);
744 // Get the current user agent from the WebView.
745 currentUserAgent = currentWebView.getSettings().getUserAgentString();
747 // Get the current font size from the
748 fontSize = currentWebView.getSettings().getTextZoom();
750 // Set the status of the menu item checkboxes.
751 domStorageMenuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
752 saveFormDataMenuItem.setChecked(currentWebView.getSettings().getSaveFormData()); // Form data can be removed once the minimum API >= 26.
753 easyListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
754 easyPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
755 fanboysAnnoyanceListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
756 fanboysSocialBlockingListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
757 ultraListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
758 ultraPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
759 blockAllThirdPartyRequestsMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
760 swipeToRefreshMenuItem.setChecked(currentWebView.getSwipeToRefresh());
761 wideViewportMenuItem.setChecked(currentWebView.getSettings().getUseWideViewPort());
762 displayImagesMenuItem.setChecked(currentWebView.getSettings().getLoadsImagesAutomatically());
763 nightModeMenuItem.setChecked(currentWebView.getNightMode());
765 // Initialize the display names for the blocklists with the number of blocked requests.
766 blocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
767 easyListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYLIST) + " - " + getString(R.string.easylist));
768 easyPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYPRIVACY) + " - " + getString(R.string.easyprivacy));
769 fanboysAnnoyanceListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " + getString(R.string.fanboys_annoyance_list));
770 fanboysSocialBlockingListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " + getString(R.string.fanboys_social_blocking_list));
771 ultraListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRALIST) + " - " + getString(R.string.ultralist));
772 ultraPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRAPRIVACY) + " - " + getString(R.string.ultraprivacy));
773 blockAllThirdPartyRequestsMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " + getString(R.string.block_all_third_party_requests));
775 // Only modify third-party cookies if the API >= 21.
776 if (Build.VERSION.SDK_INT >= 21) {
777 // Set the status of the third-party cookies checkbox.
778 thirdPartyCookiesMenuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
780 // Enable third-party cookies if first-party cookies are enabled.
781 thirdPartyCookiesMenuItem.setEnabled(cookieManager.acceptCookie());
784 // Enable DOM Storage if JavaScript is enabled.
785 domStorageMenuItem.setEnabled(currentWebView.getSettings().getJavaScriptEnabled());
788 // Set the checked status of the first party cookies menu item.
789 firstPartyCookiesMenuItem.setChecked(cookieManager.acceptCookie());
791 // Enable Clear Cookies if there are any.
792 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
794 // 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`.
795 String privateDataDirectoryString = getApplicationInfo().dataDir;
797 // Get a count of the number of files in the Local Storage directory.
798 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
799 int localStorageDirectoryNumberOfFiles = 0;
800 if (localStorageDirectory.exists()) {
801 // `Objects.requireNonNull` removes a lint warning that `localStorageDirectory.list` might produce a null pointed exception if it is dereferenced.
802 localStorageDirectoryNumberOfFiles = Objects.requireNonNull(localStorageDirectory.list()).length;
805 // Get a count of the number of files in the IndexedDB directory.
806 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
807 int indexedDBDirectoryNumberOfFiles = 0;
808 if (indexedDBDirectory.exists()) {
809 // `Objects.requireNonNull` removes a lint warning that `indexedDBDirectory.list` might produce a null pointed exception if it is dereferenced.
810 indexedDBDirectoryNumberOfFiles = Objects.requireNonNull(indexedDBDirectory.list()).length;
813 // Enable Clear DOM Storage if there is any.
814 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
816 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
817 if (Build.VERSION.SDK_INT < 26) {
818 // Get the WebView database.
819 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
821 // Enable the clear form data menu item if there is anything to clear.
822 clearFormDataMenuItem.setEnabled(webViewDatabase.hasFormData());
825 // Enable Clear Data if any of the submenu items are enabled.
826 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
828 // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
829 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListMenuItem.isChecked());
831 // Set the proxy title and check the applied proxy.
833 case ProxyHelper.NONE:
834 // Set the proxy title.
835 proxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_none));
837 // Check the proxy None radio button.
838 menu.findItem(R.id.proxy_none).setChecked(true);
841 case ProxyHelper.TOR:
842 // Set the proxy title.
843 proxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_tor));
845 // Check the proxy Tor radio button.
846 menu.findItem(R.id.proxy_tor).setChecked(true);
849 case ProxyHelper.I2P:
850 // Set the proxy title.
851 proxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_i2p));
853 // Check the proxy I2P radio button.
854 menu.findItem(R.id.proxy_i2p).setChecked(true);
857 case ProxyHelper.CUSTOM:
858 // Set the proxy title.
859 proxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_custom));
861 // Check the proxy Custom radio button.
862 menu.findItem(R.id.proxy_custom).setChecked(true);
866 // Select the current user agent menu item. A switch statement cannot be used because the user agents are not compile time constants.
867 if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) { // Privacy Browser.
868 // Update the user agent menu item title.
869 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_privacy_browser));
871 // Select the Privacy Browser radio box.
872 menu.findItem(R.id.user_agent_privacy_browser).setChecked(true);
873 } else if (currentUserAgent.equals(webViewDefaultUserAgent)) { // WebView Default.
874 // Update the user agent menu item title.
875 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_webview_default));
877 // Select the WebView Default radio box.
878 menu.findItem(R.id.user_agent_webview_default).setChecked(true);
879 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) { // Firefox on Android.
880 // Update the user agent menu item title.
881 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_android));
883 // Select the Firefox on Android radio box.
884 menu.findItem(R.id.user_agent_firefox_on_android).setChecked(true);
885 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) { // Chrome on Android.
886 // Update the user agent menu item title.
887 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_android));
889 // Select the Chrome on Android radio box.
890 menu.findItem(R.id.user_agent_chrome_on_android).setChecked(true);
891 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) { // Safari on iOS.
892 // Update the user agent menu item title.
893 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_ios));
895 // Select the Safari on iOS radio box.
896 menu.findItem(R.id.user_agent_safari_on_ios).setChecked(true);
897 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) { // Firefox on Linux.
898 // Update the user agent menu item title.
899 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_linux));
901 // Select the Firefox on Linux radio box.
902 menu.findItem(R.id.user_agent_firefox_on_linux).setChecked(true);
903 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) { // Chromium on Linux.
904 // Update the user agent menu item title.
905 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chromium_on_linux));
907 // Select the Chromium on Linux radio box.
908 menu.findItem(R.id.user_agent_chromium_on_linux).setChecked(true);
909 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) { // Firefox on Windows.
910 // Update the user agent menu item title.
911 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_windows));
913 // Select the Firefox on Windows radio box.
914 menu.findItem(R.id.user_agent_firefox_on_windows).setChecked(true);
915 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) { // Chrome on Windows.
916 // Update the user agent menu item title.
917 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_windows));
919 // Select the Chrome on Windows radio box.
920 menu.findItem(R.id.user_agent_chrome_on_windows).setChecked(true);
921 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) { // Edge on Windows.
922 // Update the user agent menu item title.
923 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_edge_on_windows));
925 // Select the Edge on Windows radio box.
926 menu.findItem(R.id.user_agent_edge_on_windows).setChecked(true);
927 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) { // Internet Explorer on Windows.
928 // Update the user agent menu item title.
929 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_internet_explorer_on_windows));
931 // Select the Internet on Windows radio box.
932 menu.findItem(R.id.user_agent_internet_explorer_on_windows).setChecked(true);
933 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) { // Safari on macOS.
934 // Update the user agent menu item title.
935 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_macos));
937 // Select the Safari on macOS radio box.
938 menu.findItem(R.id.user_agent_safari_on_macos).setChecked(true);
939 } else { // Custom user agent.
940 // Update the user agent menu item title.
941 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_custom));
943 // Select the Custom radio box.
944 menu.findItem(R.id.user_agent_custom).setChecked(true);
947 // Set the font size title.
948 fontSizeMenuItem.setTitle(getString(R.string.font_size) + " - " + fontSize + "%");
950 // Run all the other default commands.
951 super.onPrepareOptionsMenu(menu);
958 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
959 @SuppressLint("SetJavaScriptEnabled")
960 public boolean onOptionsItemSelected(MenuItem menuItem) {
961 // Get the selected menu item ID.
962 int menuItemId = menuItem.getItemId();
964 // Get a handle for the shared preferences.
965 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
967 // Get a handle for the cookie manager.
968 CookieManager cookieManager = CookieManager.getInstance();
970 // Run the commands that correlate to the selected menu item.
971 switch (menuItemId) {
972 case R.id.toggle_javascript:
973 // Toggle the JavaScript status.
974 currentWebView.getSettings().setJavaScriptEnabled(!currentWebView.getSettings().getJavaScriptEnabled());
976 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
977 updatePrivacyIcons(true);
979 // Display a `Snackbar`.
980 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScrip is enabled.
981 Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
982 } else if (cookieManager.acceptCookie()) { // JavaScript is disabled, but first-party cookies are enabled.
983 Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
984 } else { // Privacy mode.
985 Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
988 // Reload the current WebView.
989 currentWebView.reload();
991 // Consume the event.
994 case R.id.add_or_edit_domain:
995 if (currentWebView.getDomainSettingsApplied()) { // Edit the current domain settings.
996 // Reapply the domain settings on returning to `MainWebViewActivity`.
997 reapplyDomainSettingsOnRestart = true;
999 // Create an intent to launch the domains activity.
1000 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1002 // Add the extra information to the intent.
1003 domainsIntent.putExtra("load_domain", currentWebView.getDomainSettingsDatabaseId());
1004 domainsIntent.putExtra("close_on_back", true);
1005 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1007 // Get the current certificate.
1008 SslCertificate sslCertificate = currentWebView.getCertificate();
1010 // Check to see if the SSL certificate is populated.
1011 if (sslCertificate != null) {
1012 // Extract the certificate to strings.
1013 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1014 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1015 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1016 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1017 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1018 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1019 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1020 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1022 // Add the certificate to the intent.
1023 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1024 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1025 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1026 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1027 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1028 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1029 domainsIntent.putExtra("ssl_start_date", startDateLong);
1030 domainsIntent.putExtra("ssl_end_date", endDateLong);
1033 // Check to see if the current IP addresses have been received.
1034 if (currentWebView.hasCurrentIpAddresses()) {
1035 // Add the current IP addresses to the intent.
1036 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1040 startActivity(domainsIntent);
1041 } else { // Add a new domain.
1042 // Apply the new domain settings on returning to `MainWebViewActivity`.
1043 reapplyDomainSettingsOnRestart = true;
1045 // Get the current domain
1046 Uri currentUri = Uri.parse(currentWebView.getUrl());
1047 String currentDomain = currentUri.getHost();
1049 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1050 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1052 // Create the domain and store the database ID.
1053 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1055 // Create an intent to launch the domains activity.
1056 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1058 // Add the extra information to the intent.
1059 domainsIntent.putExtra("load_domain", newDomainDatabaseId);
1060 domainsIntent.putExtra("close_on_back", true);
1061 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1063 // Get the current certificate.
1064 SslCertificate sslCertificate = currentWebView.getCertificate();
1066 // Check to see if the SSL certificate is populated.
1067 if (sslCertificate != null) {
1068 // Extract the certificate to strings.
1069 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1070 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1071 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1072 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1073 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1074 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1075 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1076 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1078 // Add the certificate to the intent.
1079 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1080 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1081 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1082 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1083 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1084 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1085 domainsIntent.putExtra("ssl_start_date", startDateLong);
1086 domainsIntent.putExtra("ssl_end_date", endDateLong);
1089 // Check to see if the current IP addresses have been received.
1090 if (currentWebView.hasCurrentIpAddresses()) {
1091 // Add the current IP addresses to the intent.
1092 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1096 startActivity(domainsIntent);
1099 // Consume the event.
1102 case R.id.toggle_first_party_cookies:
1103 // Switch the first-party cookie status.
1104 cookieManager.setAcceptCookie(!cookieManager.acceptCookie());
1106 // Store the first-party cookie status.
1107 currentWebView.setAcceptFirstPartyCookies(cookieManager.acceptCookie());
1109 // Update the menu checkbox.
1110 menuItem.setChecked(cookieManager.acceptCookie());
1112 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1113 updatePrivacyIcons(true);
1115 // Display a snackbar.
1116 if (cookieManager.acceptCookie()) { // First-party cookies are enabled.
1117 Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1118 } else if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is still enabled.
1119 Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1120 } else { // Privacy mode.
1121 Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1124 // Reload the current WebView.
1125 currentWebView.reload();
1127 // Consume the event.
1130 case R.id.toggle_third_party_cookies:
1131 if (Build.VERSION.SDK_INT >= 21) {
1132 // Switch the status of thirdPartyCookiesEnabled.
1133 cookieManager.setAcceptThirdPartyCookies(currentWebView, !cookieManager.acceptThirdPartyCookies(currentWebView));
1135 // Update the menu checkbox.
1136 menuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
1138 // Display a snackbar.
1139 if (cookieManager.acceptThirdPartyCookies(currentWebView)) {
1140 Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1142 Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1145 // Reload the current WebView.
1146 currentWebView.reload();
1147 } // Else do nothing because SDK < 21.
1149 // Consume the event.
1152 case R.id.toggle_dom_storage:
1153 // Toggle the status of domStorageEnabled.
1154 currentWebView.getSettings().setDomStorageEnabled(!currentWebView.getSettings().getDomStorageEnabled());
1156 // Update the menu checkbox.
1157 menuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1159 // Update the privacy icon. `true` refreshes the app bar icons.
1160 updatePrivacyIcons(true);
1162 // Display a snackbar.
1163 if (currentWebView.getSettings().getDomStorageEnabled()) {
1164 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1166 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1169 // Reload the current WebView.
1170 currentWebView.reload();
1172 // Consume the event.
1175 // Form data can be removed once the minimum API >= 26.
1176 case R.id.toggle_save_form_data:
1177 // Switch the status of saveFormDataEnabled.
1178 currentWebView.getSettings().setSaveFormData(!currentWebView.getSettings().getSaveFormData());
1180 // Update the menu checkbox.
1181 menuItem.setChecked(currentWebView.getSettings().getSaveFormData());
1183 // Display a snackbar.
1184 if (currentWebView.getSettings().getSaveFormData()) {
1185 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1187 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1190 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1191 updatePrivacyIcons(true);
1193 // Reload the current WebView.
1194 currentWebView.reload();
1196 // Consume the event.
1199 case R.id.clear_cookies:
1200 Snackbar.make(findViewById(R.id.webviewpager), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1201 .setAction(R.string.undo, v -> {
1202 // Do nothing because everything will be handled by `onDismissed()` below.
1204 .addCallback(new Snackbar.Callback() {
1205 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1207 public void onDismissed(Snackbar snackbar, int event) {
1208 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1209 // Delete the cookies, which command varies by SDK.
1210 if (Build.VERSION.SDK_INT < 21) {
1211 cookieManager.removeAllCookie();
1213 cookieManager.removeAllCookies(null);
1220 // Consume the event.
1223 case R.id.clear_dom_storage:
1224 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1225 .setAction(R.string.undo, v -> {
1226 // Do nothing because everything will be handled by `onDismissed()` below.
1228 .addCallback(new Snackbar.Callback() {
1229 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1231 public void onDismissed(Snackbar snackbar, int event) {
1232 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1233 // Delete the DOM Storage.
1234 WebStorage webStorage = WebStorage.getInstance();
1235 webStorage.deleteAllData();
1237 // Initialize a handler to manually delete the DOM storage files and directories.
1238 Handler deleteDomStorageHandler = new Handler();
1240 // Setup a runnable to manually delete the DOM storage files and directories.
1241 Runnable deleteDomStorageRunnable = () -> {
1243 // Get a handle for the runtime.
1244 Runtime runtime = Runtime.getRuntime();
1246 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1247 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1248 String privateDataDirectoryString = getApplicationInfo().dataDir;
1250 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1251 Process deleteLocalStorageProcess = runtime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1253 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1254 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1255 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1256 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1257 Process deleteDatabasesProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1259 // Wait for the processes to finish.
1260 deleteLocalStorageProcess.waitFor();
1261 deleteIndexProcess.waitFor();
1262 deleteQuotaManagerProcess.waitFor();
1263 deleteQuotaManagerJournalProcess.waitFor();
1264 deleteDatabasesProcess.waitFor();
1265 } catch (Exception exception) {
1266 // Do nothing if an error is thrown.
1270 // Manually delete the DOM storage files after 200 milliseconds.
1271 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
1277 // Consume the event.
1280 // Form data can be remove once the minimum API >= 26.
1281 case R.id.clear_form_data:
1282 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1283 .setAction(R.string.undo, v -> {
1284 // Do nothing because everything will be handled by `onDismissed()` below.
1286 .addCallback(new Snackbar.Callback() {
1287 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1289 public void onDismissed(Snackbar snackbar, int event) {
1290 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1291 // Delete the form data.
1292 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1293 mainWebViewDatabase.clearFormData();
1299 // Consume the event.
1303 // Toggle the EasyList status.
1304 currentWebView.enableBlocklist(NestedScrollWebView.EASYLIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
1306 // Update the menu checkbox.
1307 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
1309 // Reload the current WebView.
1310 currentWebView.reload();
1312 // Consume the event.
1315 case R.id.easyprivacy:
1316 // Toggle the EasyPrivacy status.
1317 currentWebView.enableBlocklist(NestedScrollWebView.EASYPRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
1319 // Update the menu checkbox.
1320 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
1322 // Reload the current WebView.
1323 currentWebView.reload();
1325 // Consume the event.
1328 case R.id.fanboys_annoyance_list:
1329 // Toggle Fanboy's Annoyance List status.
1330 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1332 // Update the menu checkbox.
1333 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1335 // Update the staus of Fanboy's Social Blocking List.
1336 MenuItem fanboysSocialBlockingListMenuItem = optionsMenu.findItem(R.id.fanboys_social_blocking_list);
1337 fanboysSocialBlockingListMenuItem.setEnabled(!currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1339 // Reload the current WebView.
1340 currentWebView.reload();
1342 // Consume the event.
1345 case R.id.fanboys_social_blocking_list:
1346 // Toggle Fanboy's Social Blocking List status.
1347 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1349 // Update the menu checkbox.
1350 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1352 // Reload the current WebView.
1353 currentWebView.reload();
1355 // Consume the event.
1358 case R.id.ultralist:
1359 // Toggle the UltraList status.
1360 currentWebView.enableBlocklist(NestedScrollWebView.ULTRALIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
1362 // Update the menu checkbox.
1363 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
1365 // Reload the current WebView.
1366 currentWebView.reload();
1368 // Consume the event.
1371 case R.id.ultraprivacy:
1372 // Toggle the UltraPrivacy status.
1373 currentWebView.enableBlocklist(NestedScrollWebView.ULTRAPRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
1375 // Update the menu checkbox.
1376 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
1378 // Reload the current WebView.
1379 currentWebView.reload();
1381 // Consume the event.
1384 case R.id.block_all_third_party_requests:
1385 //Toggle the third-party requests blocker status.
1386 currentWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, !currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1388 // Update the menu checkbox.
1389 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1391 // Reload the current WebView.
1392 currentWebView.reload();
1394 // Consume the event.
1397 case R.id.proxy_none:
1398 // Update the proxy mode.
1399 proxyMode = ProxyHelper.NONE;
1401 // Apply the proxy mode.
1404 // Consume the event.
1407 case R.id.proxy_tor:
1408 // Update the proxy mode.
1409 proxyMode = ProxyHelper.TOR;
1411 // Apply the proxy mode.
1414 // Consume the event.
1417 case R.id.proxy_i2p:
1418 // Update the proxy mode.
1419 proxyMode = ProxyHelper.I2P;
1421 // Apply the proxy mode.
1424 // Consume the event.
1427 case R.id.proxy_custom:
1428 // Update the proxy mode.
1429 proxyMode = ProxyHelper.CUSTOM;
1431 // Apply the proxy mode.
1434 // Consume the event.
1437 case R.id.user_agent_privacy_browser:
1438 // Update the user agent.
1439 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
1441 // Reload the current WebView.
1442 currentWebView.reload();
1444 // Consume the event.
1447 case R.id.user_agent_webview_default:
1448 // Update the user agent.
1449 currentWebView.getSettings().setUserAgentString("");
1451 // Reload the current WebView.
1452 currentWebView.reload();
1454 // Consume the event.
1457 case R.id.user_agent_firefox_on_android:
1458 // Update the user agent.
1459 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
1461 // Reload the current WebView.
1462 currentWebView.reload();
1464 // Consume the event.
1467 case R.id.user_agent_chrome_on_android:
1468 // Update the user agent.
1469 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
1471 // Reload the current WebView.
1472 currentWebView.reload();
1474 // Consume the event.
1477 case R.id.user_agent_safari_on_ios:
1478 // Update the user agent.
1479 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
1481 // Reload the current WebView.
1482 currentWebView.reload();
1484 // Consume the event.
1487 case R.id.user_agent_firefox_on_linux:
1488 // Update the user agent.
1489 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
1491 // Reload the current WebView.
1492 currentWebView.reload();
1494 // Consume the event.
1497 case R.id.user_agent_chromium_on_linux:
1498 // Update the user agent.
1499 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
1501 // Reload the current WebView.
1502 currentWebView.reload();
1504 // Consume the event.
1507 case R.id.user_agent_firefox_on_windows:
1508 // Update the user agent.
1509 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
1511 // Reload the current WebView.
1512 currentWebView.reload();
1514 // Consume the event.
1517 case R.id.user_agent_chrome_on_windows:
1518 // Update the user agent.
1519 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
1521 // Reload the current WebView.
1522 currentWebView.reload();
1524 // Consume the event.
1527 case R.id.user_agent_edge_on_windows:
1528 // Update the user agent.
1529 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
1531 // Reload the current WebView.
1532 currentWebView.reload();
1534 // Consume the event.
1537 case R.id.user_agent_internet_explorer_on_windows:
1538 // Update the user agent.
1539 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
1541 // Reload the current WebView.
1542 currentWebView.reload();
1544 // Consume the event.
1547 case R.id.user_agent_safari_on_macos:
1548 // Update the user agent.
1549 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
1551 // Reload the current WebView.
1552 currentWebView.reload();
1554 // Consume the event.
1557 case R.id.user_agent_custom:
1558 // Update the user agent.
1559 currentWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
1561 // Reload the current WebView.
1562 currentWebView.reload();
1564 // Consume the event.
1567 case R.id.font_size:
1568 // Instantiate the font size dialog.
1569 DialogFragment fontSizeDialogFragment = FontSizeDialog.displayDialog(currentWebView.getSettings().getTextZoom());
1571 // Show the font size dialog.
1572 fontSizeDialogFragment.show(getSupportFragmentManager(), getString(R.string.font_size));
1574 // Consume the event.
1577 case R.id.swipe_to_refresh:
1578 // Toggle the stored status of swipe to refresh.
1579 currentWebView.setSwipeToRefresh(!currentWebView.getSwipeToRefresh());
1581 // Get a handle for the swipe refresh layout.
1582 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
1584 // Update the swipe refresh layout.
1585 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
1586 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
1587 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
1588 } else { // Swipe to refresh is disabled.
1589 // Disable the swipe refresh layout.
1590 swipeRefreshLayout.setEnabled(false);
1593 // Consume the event.
1596 case R.id.wide_viewport:
1597 // Toggle the viewport.
1598 currentWebView.getSettings().setUseWideViewPort(!currentWebView.getSettings().getUseWideViewPort());
1600 // Consume the event.
1603 case R.id.display_images:
1604 if (currentWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1605 // Disable loading of images.
1606 currentWebView.getSettings().setLoadsImagesAutomatically(false);
1608 // Reload the website to remove existing images.
1609 currentWebView.reload();
1610 } else { // Images are not currently loaded automatically.
1611 // Enable loading of images. Missing images will be loaded without the need for a reload.
1612 currentWebView.getSettings().setLoadsImagesAutomatically(true);
1615 // Consume the event.
1618 case R.id.night_mode:
1619 // Toggle night mode.
1620 currentWebView.setNightMode(!currentWebView.getNightMode());
1622 // Enable or disable JavaScript according to night mode, the global preference, and any domain settings.
1623 if (currentWebView.getNightMode()) { // Night mode is enabled, which requires JavaScript.
1624 // Enable JavaScript.
1625 currentWebView.getSettings().setJavaScriptEnabled(true);
1626 } else if (currentWebView.getDomainSettingsApplied()) { // Night mode is disabled and domain settings are applied. Set JavaScript according to the domain settings.
1627 // Apply the JavaScript preference that was stored the last time domain settings were loaded.
1628 currentWebView.getSettings().setJavaScriptEnabled(currentWebView.getDomainSettingsJavaScriptEnabled());
1629 } else { // Night mode is disabled and domain settings are not applied. Set JavaScript according to the global preference.
1630 // Apply the JavaScript preference.
1631 currentWebView.getSettings().setJavaScriptEnabled(sharedPreferences.getBoolean("javascript", false));
1634 // Update the privacy icons.
1635 updatePrivacyIcons(false);
1637 // Reload the website.
1638 currentWebView.reload();
1640 // Consume the event.
1643 case R.id.find_on_page:
1644 // Get a handle for the views.
1645 Toolbar toolbar = findViewById(R.id.toolbar);
1646 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
1647 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
1649 // Set the minimum height of the find on page linear layout to match the toolbar.
1650 findOnPageLinearLayout.setMinimumHeight(toolbar.getHeight());
1652 // Hide the toolbar.
1653 toolbar.setVisibility(View.GONE);
1655 // Show the find on page linear layout.
1656 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1658 // Display the keyboard. The app must wait 200 ms before running the command to work around a bug in Android.
1659 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1660 findOnPageEditText.postDelayed(() -> {
1661 // Set the focus on `findOnPageEditText`.
1662 findOnPageEditText.requestFocus();
1664 // Get a handle for the input method manager.
1665 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1667 // Remove the lint warning below that the input method manager might be null.
1668 assert inputMethodManager != null;
1670 // Display the keyboard. `0` sets no input flags.
1671 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1674 // Consume the event.
1678 // Get a print manager instance.
1679 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1681 // Remove the lint error below that print manager might be null.
1682 assert printManager != null;
1684 // Create a print document adapter from the current WebView.
1685 PrintDocumentAdapter printDocumentAdapter = currentWebView.createPrintDocumentAdapter();
1687 // Print the document.
1688 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1690 // Consume the event.
1694 // Instantiate the save dialog.
1695 DialogFragment saveDialogFragment = SaveDialog.saveUrl(StoragePermissionDialog.SAVE_URL, currentWebView.getCurrentUrl(), currentWebView.getSettings().getUserAgentString(),
1696 currentWebView.getAcceptFirstPartyCookies());
1698 // Show the save dialog. It must be named `save_dialog` so that the file picked can update the file name.
1699 saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
1701 // Consume the event.
1704 case R.id.save_as_archive:
1705 // Instantiate the save webpage archive dialog.
1706 DialogFragment saveWebpageArchiveDialogFragment = SaveDialog.saveUrl(StoragePermissionDialog.SAVE_AS_ARCHIVE, currentWebView.getCurrentUrl(), currentWebView.getSettings().getUserAgentString(),
1707 currentWebView.getAcceptFirstPartyCookies());
1709 // Show the save webpage archive dialog. It must be named `save_dialog` so that the file picked can update the file name.
1710 saveWebpageArchiveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
1712 // Consume the event.
1715 case R.id.save_as_image:
1716 // Instantiate the save webpage image dialog. It must be named `save_webpage` so that the file picked can update the file name.
1717 DialogFragment saveWebpageImageDialogFragment = SaveDialog.saveUrl(StoragePermissionDialog.SAVE_AS_IMAGE, currentWebView.getCurrentUrl(), currentWebView.getSettings().getUserAgentString(),
1718 currentWebView.getAcceptFirstPartyCookies());
1720 // Show the save webpage image dialog. It must be named `save_dialog` so that the file picked can update the file name.
1721 saveWebpageImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
1723 // Consume the event.
1726 case R.id.add_to_homescreen:
1727 // Instantiate the create home screen shortcut dialog.
1728 DialogFragment createHomeScreenShortcutDialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView.getTitle(), currentWebView.getUrl(),
1729 currentWebView.getFavoriteOrDefaultIcon());
1731 // Show the create home screen shortcut dialog.
1732 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
1734 // Consume the event.
1737 case R.id.view_source:
1738 // Create an intent to launch the view source activity.
1739 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
1741 // Add the variables to the intent.
1742 viewSourceIntent.putExtra("user_agent", currentWebView.getSettings().getUserAgentString());
1743 viewSourceIntent.putExtra("current_url", currentWebView.getUrl());
1746 startActivity(viewSourceIntent);
1748 // Consume the event.
1751 case R.id.share_url:
1752 // Setup the share string.
1753 String shareString = currentWebView.getTitle() + " – " + currentWebView.getUrl();
1755 // Create the share intent.
1756 Intent shareIntent = new Intent(Intent.ACTION_SEND);
1757 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1758 shareIntent.setType("text/plain");
1761 startActivity(Intent.createChooser(shareIntent, getString(R.string.share_url)));
1763 // Consume the event.
1766 case R.id.open_with_app:
1767 // Open the URL with an outside app.
1768 openWithApp(currentWebView.getUrl());
1770 // Consume the event.
1773 case R.id.open_with_browser:
1774 // Open the URL with an outside browser.
1775 openWithBrowser(currentWebView.getUrl());
1777 // Consume the event.
1781 if (menuItem.getTitle().equals(getString(R.string.refresh))) { // The refresh button was pushed.
1782 // Reload the current WebView.
1783 currentWebView.reload();
1784 } else { // The stop button was pushed.
1785 // Stop the loading of the WebView.
1786 currentWebView.stopLoading();
1789 // Consume the event.
1792 case R.id.ad_consent:
1793 // Instantiate the ad consent dialog.
1794 DialogFragment adConsentDialogFragment = new AdConsentDialog();
1796 // Display the ad consent dialog.
1797 adConsentDialogFragment.show(getSupportFragmentManager(), getString(R.string.ad_consent));
1799 // Consume the event.
1803 // Don't consume the event.
1804 return super.onOptionsItemSelected(menuItem);
1808 // removeAllCookies is deprecated, but it is required for API < 21.
1810 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1811 // Get the menu item ID.
1812 int menuItemId = menuItem.getItemId();
1814 // Get a handle for the shared preferences.
1815 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1817 // Run the commands that correspond to the selected menu item.
1818 switch (menuItemId) {
1819 case R.id.clear_and_exit:
1820 // Clear and exit Privacy Browser.
1825 // Load the homepage.
1826 loadUrl(currentWebView, sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
1830 if (currentWebView.canGoBack()) {
1831 // Get the current web back forward list.
1832 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
1834 // Get the previous entry URL.
1835 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
1837 // Apply the domain settings.
1838 applyDomainSettings(currentWebView, previousUrl, false, false);
1840 // Load the previous website in the history.
1841 currentWebView.goBack();
1846 if (currentWebView.canGoForward()) {
1847 // Get the current web back forward list.
1848 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
1850 // Get the next entry URL.
1851 String nextUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() + 1).getUrl();
1853 // Apply the domain settings.
1854 applyDomainSettings(currentWebView, nextUrl, false, false);
1856 // Load the next website in the history.
1857 currentWebView.goForward();
1862 // Instantiate the URL history dialog.
1863 DialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView.getWebViewFragmentId());
1865 // Show the URL history dialog.
1866 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
1870 // Instantiate the open file dialog.
1871 DialogFragment openDialogFragment = new OpenDialog();
1873 // Show the open file dialog.
1874 openDialogFragment.show(getSupportFragmentManager(), getString(R.string.open));
1878 // Populate the resource requests.
1879 RequestsActivity.resourceRequests = currentWebView.getResourceRequests();
1881 // Create an intent to launch the Requests activity.
1882 Intent requestsIntent = new Intent(this, RequestsActivity.class);
1884 // Add the block third-party requests status to the intent.
1885 requestsIntent.putExtra("block_all_third_party_requests", currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1888 startActivity(requestsIntent);
1891 case R.id.downloads:
1892 // Launch the system Download Manager.
1893 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1895 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1896 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1898 startActivity(downloadManagerIntent);
1902 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
1903 reapplyDomainSettingsOnRestart = true;
1905 // Launch the domains activity.
1906 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1908 // Add the extra information to the intent.
1909 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1911 // Get the current certificate.
1912 SslCertificate sslCertificate = currentWebView.getCertificate();
1914 // Check to see if the SSL certificate is populated.
1915 if (sslCertificate != null) {
1916 // Extract the certificate to strings.
1917 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1918 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1919 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1920 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1921 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1922 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1923 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1924 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1926 // Add the certificate to the intent.
1927 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1928 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1929 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1930 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1931 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1932 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1933 domainsIntent.putExtra("ssl_start_date", startDateLong);
1934 domainsIntent.putExtra("ssl_end_date", endDateLong);
1937 // Check to see if the current IP addresses have been received.
1938 if (currentWebView.hasCurrentIpAddresses()) {
1939 // Add the current IP addresses to the intent.
1940 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1944 startActivity(domainsIntent);
1948 // Set the flag to reapply app settings on restart when returning from Settings.
1949 reapplyAppSettingsOnRestart = true;
1951 // Set the flag to reapply the domain settings on restart when returning from Settings.
1952 reapplyDomainSettingsOnRestart = true;
1954 // Launch the settings activity.
1955 Intent settingsIntent = new Intent(this, SettingsActivity.class);
1956 startActivity(settingsIntent);
1959 case R.id.import_export:
1960 // Launch the import/export activity.
1961 Intent importExportIntent = new Intent (this, ImportExportActivity.class);
1962 startActivity(importExportIntent);
1966 // Launch the logcat activity.
1967 Intent logcatIntent = new Intent(this, LogcatActivity.class);
1968 startActivity(logcatIntent);
1972 // Launch `GuideActivity`.
1973 Intent guideIntent = new Intent(this, GuideActivity.class);
1974 startActivity(guideIntent);
1978 // Create an intent to launch the about activity.
1979 Intent aboutIntent = new Intent(this, AboutActivity.class);
1981 // Create a string array for the blocklist versions.
1982 String[] blocklistVersions = new String[] {easyList.get(0).get(0)[0], easyPrivacy.get(0).get(0)[0], fanboysAnnoyanceList.get(0).get(0)[0], fanboysSocialList.get(0).get(0)[0],
1983 ultraList.get(0).get(0)[0], ultraPrivacy.get(0).get(0)[0]};
1985 // Add the blocklist versions to the intent.
1986 aboutIntent.putExtra("blocklist_versions", blocklistVersions);
1989 startActivity(aboutIntent);
1993 // Get a handle for the drawer layout.
1994 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
1996 // Close the navigation drawer.
1997 drawerLayout.closeDrawer(GravityCompat.START);
2002 public void onPostCreate(Bundle savedInstanceState) {
2003 // Run the default commands.
2004 super.onPostCreate(savedInstanceState);
2006 // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished. This creates the navigation drawer icon.
2007 actionBarDrawerToggle.syncState();
2011 public void onConfigurationChanged(@NonNull Configuration newConfig) {
2012 // Run the default commands.
2013 super.onConfigurationChanged(newConfig);
2015 // Get the status bar pixel size.
2016 int statusBarResourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
2017 int statusBarPixelSize = getResources().getDimensionPixelSize(statusBarResourceId);
2019 // Get the resource density.
2020 float screenDensity = getResources().getDisplayMetrics().density;
2022 // Recalculate the drawer header padding.
2023 drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
2024 drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
2025 drawerHeaderPaddingBottom = (int) (8 * screenDensity);
2027 // Reload the ad for the free flavor if not in full screen mode.
2028 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2029 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2030 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
2033 // `invalidateOptionsMenu` should recalculate the number of action buttons from the menu to display on the app bar, but it doesn't because of the this bug:
2034 // https://code.google.com/p/android/issues/detail?id=20493#c8
2035 // ActivityCompat.invalidateOptionsMenu(this);
2039 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2040 // Store the hit test result.
2041 final WebView.HitTestResult hitTestResult = currentWebView.getHitTestResult();
2043 // Define the URL strings.
2044 final String imageUrl;
2045 final String linkUrl;
2047 // Get handles for the system managers.
2048 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2050 // Remove the lint errors below that the clipboard manager might be null.
2051 assert clipboardManager != null;
2053 // Process the link according to the type.
2054 switch (hitTestResult.getType()) {
2055 // `SRC_ANCHOR_TYPE` is a link.
2056 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2057 // Get the target URL.
2058 linkUrl = hitTestResult.getExtra();
2060 // Set the target URL as the title of the `ContextMenu`.
2061 menu.setHeaderTitle(linkUrl);
2063 // Add an Open in New Tab entry.
2064 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2065 // Load the link URL in a new tab and move to it.
2066 addNewTab(linkUrl, true);
2068 // Consume the event.
2072 // Add an Open in Background entry.
2073 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2074 // Load the link URL in a new tab but do not move to it.
2075 addNewTab(linkUrl, false);
2077 // Consume the event.
2081 // Add an Open with App entry.
2082 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2083 openWithApp(linkUrl);
2085 // Consume the event.
2089 // Add an Open with Browser entry.
2090 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2091 openWithBrowser(linkUrl);
2093 // Consume the event.
2097 // Add a Copy URL entry.
2098 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2099 // Save the link URL in a `ClipData`.
2100 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2102 // Set the `ClipData` as the clipboard's primary clip.
2103 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2105 // Consume the event.
2109 // Add a Save URL entry.
2110 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2111 // Instantiate the save dialog.
2112 DialogFragment saveDialogFragment = SaveDialog.saveUrl(StoragePermissionDialog.SAVE_URL, linkUrl, currentWebView.getSettings().getUserAgentString(),
2113 currentWebView.getAcceptFirstPartyCookies());
2115 // Show the save dialog. It must be named `save_dialog` so that the file picker can update the file name.
2116 saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
2118 // Consume the event.
2122 // Add a Cancel entry, which by default closes the context menu.
2123 menu.add(R.string.cancel);
2126 case WebView.HitTestResult.EMAIL_TYPE:
2127 // Get the target URL.
2128 linkUrl = hitTestResult.getExtra();
2130 // Set the target URL as the title of the `ContextMenu`.
2131 menu.setHeaderTitle(linkUrl);
2133 // Add a Write Email entry.
2134 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2135 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2136 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2138 // Parse the url and set it as the data for the `Intent`.
2139 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2141 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2142 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2145 startActivity(emailIntent);
2147 // Consume the event.
2151 // Add a Copy Email Address entry.
2152 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2153 // Save the email address in a `ClipData`.
2154 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2156 // Set the `ClipData` as the clipboard's primary clip.
2157 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2159 // Consume the event.
2163 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2164 menu.add(R.string.cancel);
2167 // `IMAGE_TYPE` is an image.
2168 case WebView.HitTestResult.IMAGE_TYPE:
2169 // Get the image URL.
2170 imageUrl = hitTestResult.getExtra();
2172 // Set the image URL as the title of the context menu.
2173 menu.setHeaderTitle(imageUrl);
2175 // Add an Open in New Tab entry.
2176 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2177 // Load the image in a new tab.
2178 addNewTab(imageUrl, true);
2180 // Consume the event.
2184 // Add a View Image entry.
2185 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2186 // Load the image in the current tab.
2187 loadUrl(currentWebView, imageUrl);
2189 // Consume the event.
2193 // Add a Save Image entry.
2194 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2195 // Instantiate the save dialog.
2196 DialogFragment saveDialogFragment = SaveDialog.saveUrl(StoragePermissionDialog.SAVE_URL, imageUrl, currentWebView.getSettings().getUserAgentString(),
2197 currentWebView.getAcceptFirstPartyCookies());
2199 // Show the save dialog. It must be named `save_dialog` so that the file picked can update the file name.
2200 saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
2202 // Consume the event.
2206 // Add a Copy URL entry.
2207 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2208 // Save the image URL in a clip data.
2209 ClipData imageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2211 // Set the clip data as the clipboard's primary clip.
2212 clipboardManager.setPrimaryClip(imageTypeClipData);
2214 // Consume the event.
2218 // Add an Open with App entry.
2219 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2220 // Open the image URL with an external app.
2221 openWithApp(imageUrl);
2223 // Consume the event.
2227 // Add an Open with Browser entry.
2228 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2229 // Open the image URL with an external browser.
2230 openWithBrowser(imageUrl);
2232 // Consume the event.
2236 // Add a Cancel entry, which by default closes the context menu.
2237 menu.add(R.string.cancel);
2240 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2241 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2242 // Get the image URL.
2243 imageUrl = hitTestResult.getExtra();
2245 // Instantiate a handler.
2246 Handler handler = new Handler();
2248 // Get a message from the handler.
2249 Message message = handler.obtainMessage();
2251 // Request the image details from the last touched node be returned in the message.
2252 currentWebView.requestFocusNodeHref(message);
2254 // Get the link URL from the message data.
2255 linkUrl = message.getData().getString("url");
2257 // Set the link URL as the title of the context menu.
2258 menu.setHeaderTitle(linkUrl);
2260 // Add an Open in New Tab entry.
2261 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2262 // Load the link URL in a new tab and move to it.
2263 addNewTab(linkUrl, true);
2265 // Consume the event.
2269 // Add an Open in Background entry.
2270 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2271 // Lod the link URL in a new tab but do not move to it.
2272 addNewTab(linkUrl, false);
2274 // Consume the event.
2278 // Add an Open Image in New Tab entry.
2279 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2280 // Load the image in a new tab and move to it.
2281 addNewTab(imageUrl, true);
2283 // Consume the event.
2287 // Add a View Image entry.
2288 menu.add(R.string.view_image).setOnMenuItemClickListener((MenuItem item) -> {
2289 // View the image in the current tab.
2290 loadUrl(currentWebView, imageUrl);
2292 // Consume the event.
2296 // Add a Copy URL entry.
2297 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2298 // Save the link URL in a clip data.
2299 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2301 // Set the clip data as the clipboard's primary clip.
2302 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2304 // Consume the event.
2308 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2309 // Instantiate the save dialog.
2310 DialogFragment saveDialogFragment = SaveDialog.saveUrl(StoragePermissionDialog.SAVE_URL, imageUrl, currentWebView.getSettings().getUserAgentString(),
2311 currentWebView.getAcceptFirstPartyCookies());
2313 // Show the save raw dialog. It must be named `save_dialog` so that the file picked can update the file name.
2314 saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
2316 // Consume the event.
2320 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2321 // Instantiate the save dialog.
2322 DialogFragment saveDialogFragment = SaveDialog.saveUrl(StoragePermissionDialog.SAVE_URL, linkUrl, currentWebView.getSettings().getUserAgentString(),
2323 currentWebView.getAcceptFirstPartyCookies());
2325 // Show the save raw dialog. It must be named `save_dialog` so that the file picked can update the file name.
2326 saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
2328 // Consume the event.
2332 // Add an Open with App entry.
2333 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2334 // Open the link URL with an external app.
2335 openWithApp(linkUrl);
2337 // Consume the event.
2341 // Add an Open with Browser entry.
2342 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2343 // Open the link URL with an external browser.
2344 openWithBrowser(linkUrl);
2346 // Consume the event.
2350 // Add a cancel entry, which by default closes the context menu.
2351 menu.add(R.string.cancel);
2357 public void onCreateBookmark(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2358 // Get a handle for the bookmarks list view.
2359 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2362 Dialog dialog = dialogFragment.getDialog();
2364 // Remove the incorrect lint warning below that the dialog might be null.
2365 assert dialog != null;
2367 // Get the views from the dialog fragment.
2368 EditText createBookmarkNameEditText = dialog.findViewById(R.id.create_bookmark_name_edittext);
2369 EditText createBookmarkUrlEditText = dialog.findViewById(R.id.create_bookmark_url_edittext);
2371 // Extract the strings from the edit texts.
2372 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2373 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2375 // Create a favorite icon byte array output stream.
2376 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2378 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2379 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2381 // Convert the favorite icon byte array stream to a byte array.
2382 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2384 // Display the new bookmark below the current items in the (0 indexed) list.
2385 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2387 // Create the bookmark.
2388 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2390 // Update the bookmarks cursor with the current contents of this folder.
2391 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2393 // Update the list view.
2394 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2396 // Scroll to the new bookmark.
2397 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2401 public void onCreateBookmarkFolder(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2402 // Get a handle for the bookmarks list view.
2403 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2406 Dialog dialog = dialogFragment.getDialog();
2408 // Remove the incorrect lint warning below that the dialog might be null.
2409 assert dialog != null;
2411 // Get handles for the views in the dialog fragment.
2412 EditText createFolderNameEditText = dialog.findViewById(R.id.create_folder_name_edittext);
2413 RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.create_folder_default_icon_radiobutton);
2414 ImageView folderIconImageView = dialog.findViewById(R.id.create_folder_default_icon);
2416 // Get new folder name string.
2417 String folderNameString = createFolderNameEditText.getText().toString();
2419 // Create a folder icon bitmap.
2420 Bitmap folderIconBitmap;
2422 // Set the folder icon bitmap according to the dialog.
2423 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
2424 // Get the default folder icon drawable.
2425 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2427 // Convert the folder icon drawable to a bitmap drawable.
2428 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2430 // Convert the folder icon bitmap drawable to a bitmap.
2431 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2432 } else { // Use the WebView favorite icon.
2433 // Copy the favorite icon bitmap to the folder icon bitmap.
2434 folderIconBitmap = favoriteIconBitmap;
2437 // Create a folder icon byte array output stream.
2438 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2440 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2441 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2443 // Convert the folder icon byte array stream to a byte array.
2444 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2446 // Move all the bookmarks down one in the display order.
2447 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2448 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2449 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2452 // Create the folder, which will be placed at the top of the `ListView`.
2453 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2455 // Update the bookmarks cursor with the current contents of this folder.
2456 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2458 // Update the `ListView`.
2459 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2461 // Scroll to the new folder.
2462 bookmarksListView.setSelection(0);
2466 public void onSaveBookmark(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, Bitmap favoriteIconBitmap) {
2468 Dialog dialog = dialogFragment.getDialog();
2470 // Remove the incorrect lint warning below that the dialog might be null.
2471 assert dialog != null;
2473 // Get handles for the views from the dialog.
2474 EditText editBookmarkNameEditText = dialog.findViewById(R.id.edit_bookmark_name_edittext);
2475 EditText editBookmarkUrlEditText = dialog.findViewById(R.id.edit_bookmark_url_edittext);
2476 RadioButton currentBookmarkIconRadioButton = dialog.findViewById(R.id.edit_bookmark_current_icon_radiobutton);
2478 // Store the bookmark strings.
2479 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
2480 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
2482 // Update the bookmark.
2483 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
2484 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
2485 } else { // Update the bookmark using the `WebView` favorite icon.
2486 // Create a favorite icon byte array output stream.
2487 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2489 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2490 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
2492 // Convert the favorite icon byte array stream to a byte array.
2493 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
2495 // Update the bookmark and the favorite icon.
2496 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
2499 // Update the bookmarks cursor with the current contents of this folder.
2500 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2502 // Update the list view.
2503 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2507 public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, Bitmap favoriteIconBitmap) {
2509 Dialog dialog = dialogFragment.getDialog();
2511 // Remove the incorrect lint warning below that the dialog might be null.
2512 assert dialog != null;
2514 // Get handles for the views from `dialogFragment`.
2515 EditText editFolderNameEditText = dialog.findViewById(R.id.edit_folder_name_edittext);
2516 RadioButton currentFolderIconRadioButton = dialog.findViewById(R.id.edit_folder_current_icon_radiobutton);
2517 RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.edit_folder_default_icon_radiobutton);
2518 ImageView defaultFolderIconImageView = dialog.findViewById(R.id.edit_folder_default_icon_imageview);
2520 // Get the new folder name.
2521 String newFolderNameString = editFolderNameEditText.getText().toString();
2523 // Check if the favorite icon has changed.
2524 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
2525 // Update the name in the database.
2526 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2527 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
2528 // Create the new folder icon Bitmap.
2529 Bitmap folderIconBitmap;
2531 // Populate the new folder icon bitmap.
2532 if (defaultFolderIconRadioButton.isChecked()) {
2533 // Get the default folder icon drawable.
2534 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2536 // Convert the folder icon drawable to a bitmap drawable.
2537 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2539 // Convert the folder icon bitmap drawable to a bitmap.
2540 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2541 } else { // Use the `WebView` favorite icon.
2542 // Copy the favorite icon bitmap to the folder icon bitmap.
2543 folderIconBitmap = favoriteIconBitmap;
2546 // Create a folder icon byte array output stream.
2547 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2549 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2550 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2552 // Convert the folder icon byte array stream to a byte array.
2553 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2555 // Update the folder icon in the database.
2556 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, newFolderIconByteArray);
2557 } else { // The folder icon and the name have changed.
2558 // Get the new folder icon `Bitmap`.
2559 Bitmap folderIconBitmap;
2560 if (defaultFolderIconRadioButton.isChecked()) {
2561 // Get the default folder icon drawable.
2562 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2564 // Convert the folder icon drawable to a bitmap drawable.
2565 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2567 // Convert the folder icon bitmap drawable to a bitmap.
2568 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2569 } else { // Use the `WebView` favorite icon.
2570 // Copy the favorite icon bitmap to the folder icon bitmap.
2571 folderIconBitmap = favoriteIconBitmap;
2574 // Create a folder icon byte array output stream.
2575 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2577 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2578 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2580 // Convert the folder icon byte array stream to a byte array.
2581 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2583 // Update the folder name and icon in the database.
2584 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, newFolderIconByteArray);
2587 // Update the bookmarks cursor with the current contents of this folder.
2588 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2590 // Update the `ListView`.
2591 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2594 // Override `onBackPressed` to handle the navigation drawer and and the WebViews.
2596 public void onBackPressed() {
2597 // Get a handle for the drawer layout and the tab layout.
2598 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
2599 TabLayout tabLayout = findViewById(R.id.tablayout);
2601 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
2602 // Close the navigation drawer.
2603 drawerLayout.closeDrawer(GravityCompat.START);
2604 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
2605 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
2606 // close the bookmarks drawer.
2607 drawerLayout.closeDrawer(GravityCompat.END);
2608 } else { // A subfolder is displayed.
2609 // Place the former parent folder in `currentFolder`.
2610 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolderName(currentBookmarksFolder);
2612 // Load the new folder.
2613 loadBookmarksFolder();
2615 } else if (displayingFullScreenVideo) { // A full screen video is shown.
2616 // Get a handle for the layouts.
2617 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
2618 RelativeLayout mainContentRelativeLayout = findViewById(R.id.main_content_relativelayout);
2619 FrameLayout fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
2621 // Re-enable the screen timeout.
2622 fullScreenVideoFrameLayout.setKeepScreenOn(false);
2624 // Unset the full screen video flag.
2625 displayingFullScreenVideo = false;
2627 // Remove all the views from the full screen video frame layout.
2628 fullScreenVideoFrameLayout.removeAllViews();
2630 // Hide the full screen video frame layout.
2631 fullScreenVideoFrameLayout.setVisibility(View.GONE);
2633 // Enable the sliding drawers.
2634 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
2636 // Show the main content relative layout.
2637 mainContentRelativeLayout.setVisibility(View.VISIBLE);
2639 // Apply the appropriate full screen mode flags.
2640 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
2641 // Hide the app bar if specified.
2643 // Get handles for the views.
2644 LinearLayout tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
2645 ActionBar actionBar = getSupportActionBar();
2647 // Remove the incorrect lint warning below that the action bar might be null.
2648 assert actionBar != null;
2650 // Hide the tab linear layout.
2651 tabsLinearLayout.setVisibility(View.GONE);
2653 // Hide the action bar.
2657 // Hide the banner ad in the free flavor.
2658 if (BuildConfig.FLAVOR.contentEquals("free")) {
2659 AdHelper.hideAd(findViewById(R.id.adview));
2662 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
2663 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2665 /* Hide the system bars.
2666 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2667 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
2668 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2669 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
2671 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
2672 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
2673 } else { // Switch to normal viewing mode.
2674 // Remove the `SYSTEM_UI` flags from the root frame layout.
2675 rootFrameLayout.setSystemUiVisibility(0);
2677 // Add the translucent status flag.
2678 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2681 // Reload the ad for the free flavor if not in full screen mode.
2682 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2684 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
2686 } else if (currentWebView.canGoBack()) { // There is at least one item in the current WebView history.
2687 // Get the current web back forward list.
2688 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
2690 // Get the previous entry URL.
2691 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
2693 // Apply the domain settings.
2694 applyDomainSettings(currentWebView, previousUrl, false, false);
2697 currentWebView.goBack();
2698 } else if (tabLayout.getTabCount() > 1) { // There are at least two tabs.
2699 // Close the current tab.
2701 } else { // There isn't anything to do in Privacy Browser.
2702 // Close Privacy Browser. `finishAndRemoveTask()` also removes Privacy Browser from the recent app list.
2703 if (Build.VERSION.SDK_INT >= 21) {
2704 finishAndRemoveTask();
2709 // Manually kill Privacy Browser. Otherwise, it is glitchy when restarted.
2714 // Process the results of a file browse.
2716 public void onActivityResult(int requestCode, int resultCode, Intent returnedIntent) {
2717 // Run the default commands.
2718 super.onActivityResult(requestCode, resultCode, returnedIntent);
2720 // Run the commands that correlate to the specified request code.
2721 switch (requestCode) {
2722 case BROWSE_FILE_UPLOAD_REQUEST_CODE:
2723 // File uploads only work on API >= 21.
2724 if (Build.VERSION.SDK_INT >= 21) {
2725 // Pass the file to the WebView.
2726 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, returnedIntent));
2730 case BROWSE_SAVE_WEBPAGE_REQUEST_CODE:
2731 // Don't do anything if the user pressed back from the file picker.
2732 if (resultCode == Activity.RESULT_OK) {
2733 // Get a handle for the save dialog fragment.
2734 DialogFragment saveWebpageDialogFragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.save_dialog));
2736 // Only update the file name if the dialog still exists.
2737 if (saveWebpageDialogFragment != null) {
2738 // Get a handle for the save webpage dialog.
2739 Dialog saveWebpageDialog = saveWebpageDialogFragment.getDialog();
2741 // Remove the incorrect lint warning below that the dialog might be null.
2742 assert saveWebpageDialog != null;
2744 // Get a handle for the file name edit text.
2745 EditText fileNameEditText = saveWebpageDialog.findViewById(R.id.file_name_edittext);
2746 TextView fileExistsWarningTextView = saveWebpageDialog.findViewById(R.id.file_exists_warning_textview);
2748 // Instantiate the file name helper.
2749 FileNameHelper fileNameHelper = new FileNameHelper();
2751 // Get the file path if it isn't null.
2752 if (returnedIntent.getData() != null) {
2753 // Convert the file name URI to a file name path.
2754 String fileNamePath = fileNameHelper.convertUriToFileNamePath(returnedIntent.getData());
2756 // Set the file name path as the text of the file name edit text.
2757 fileNameEditText.setText(fileNamePath);
2759 // Move the cursor to the end of the file name edit text.
2760 fileNameEditText.setSelection(fileNamePath.length());
2762 // Hide the file exists warning.
2763 fileExistsWarningTextView.setVisibility(View.GONE);
2769 case BROWSE_OPEN_REQUEST_CODE:
2770 // Don't do anything if the user pressed back from the file picker.
2771 if (resultCode == Activity.RESULT_OK) {
2772 // Get a handle for the open dialog fragment.
2773 DialogFragment openDialogFragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.open));
2775 // Only update the file name if the dialog still exists.
2776 if (openDialogFragment != null) {
2777 // Get a handle for the open dialog.
2778 Dialog openDialog = openDialogFragment.getDialog();
2780 // Remove the incorrect lint warning below that the dialog might be null.
2781 assert openDialog != null;
2783 // Get a handle for the file name edit text.
2784 EditText fileNameEditText = openDialog.findViewById(R.id.file_name_edittext);
2786 // Instantiate the file name helper.
2787 FileNameHelper fileNameHelper = new FileNameHelper();
2789 // Get the file path if it isn't null.
2790 if (returnedIntent.getData() != null) {
2791 // Convert the file name URI to a file name path.
2792 String fileNamePath = fileNameHelper.convertUriToFileNamePath(returnedIntent.getData());
2794 // Set the file name path as the text of the file name edit text.
2795 fileNameEditText.setText(fileNamePath);
2797 // Move the cursor to the end of the file name edit text.
2798 fileNameEditText.setSelection(fileNamePath.length());
2806 private void loadUrlFromTextBox() {
2807 // Get a handle for the URL edit text.
2808 EditText urlEditText = findViewById(R.id.url_edittext);
2810 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2811 String unformattedUrlString = urlEditText.getText().toString().trim();
2813 // Initialize the formatted URL string.
2816 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
2817 if (unformattedUrlString.startsWith("content://")) { // This is a Content URL.
2818 // Load the entire content URL.
2819 url = unformattedUrlString;
2820 } else if (Patterns.WEB_URL.matcher(unformattedUrlString).matches() || unformattedUrlString.startsWith("http://") || unformattedUrlString.startsWith("https://") ||
2821 unformattedUrlString.startsWith("file://")) { // This is a standard URL.
2822 // Add `https://` at the beginning if there is no protocol. Otherwise the app will segfault.
2823 if (!unformattedUrlString.startsWith("http") && !unformattedUrlString.startsWith("file://") && !unformattedUrlString.startsWith("content://")) {
2824 unformattedUrlString = "https://" + unformattedUrlString;
2827 // Initialize `unformattedUrl`.
2828 URL unformattedUrl = null;
2830 // Convert `unformattedUrlString` to a `URL`, then to a `URI`, and then back to a `String`, which sanitizes the input and adds in any missing components.
2832 unformattedUrl = new URL(unformattedUrlString);
2833 } catch (MalformedURLException e) {
2834 e.printStackTrace();
2837 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2838 String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2839 String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2840 String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2841 String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2842 String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2845 Uri.Builder uri = new Uri.Builder();
2846 uri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2848 // Decode the URI as a UTF-8 string in.
2850 url = URLDecoder.decode(uri.build().toString(), "UTF-8");
2851 } catch (UnsupportedEncodingException exception) {
2852 // Do nothing. The formatted URL string will remain blank.
2854 } else if (!unformattedUrlString.isEmpty()){ // This is not a URL, but rather a search string.
2855 // Create an encoded URL String.
2856 String encodedUrlString;
2858 // Sanitize the search input.
2860 encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2861 } catch (UnsupportedEncodingException exception) {
2862 encodedUrlString = "";
2865 // Add the base search URL.
2866 url = searchURL + encodedUrlString;
2869 // 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.
2870 urlEditText.clearFocus();
2873 loadUrl(currentWebView, url);
2876 private void loadUrl(NestedScrollWebView nestedScrollWebView, String url) {
2877 // Sanitize the URL.
2878 url = sanitizeUrl(url);
2880 // Apply the domain settings.
2881 applyDomainSettings(nestedScrollWebView, url, true, false);
2884 nestedScrollWebView.loadUrl(url, customHeaders);
2887 public void findPreviousOnPage(View view) {
2888 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
2889 currentWebView.findNext(false);
2892 public void findNextOnPage(View view) {
2893 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2894 currentWebView.findNext(true);
2897 public void closeFindOnPage(View view) {
2898 // Get a handle for the views.
2899 Toolbar toolbar = findViewById(R.id.toolbar);
2900 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
2901 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
2903 // Delete the contents of `find_on_page_edittext`.
2904 findOnPageEditText.setText(null);
2906 // Clear the highlighted phrases if the WebView is not null.
2907 if (currentWebView != null) {
2908 currentWebView.clearMatches();
2911 // Hide the find on page linear layout.
2912 findOnPageLinearLayout.setVisibility(View.GONE);
2914 // Show the toolbar.
2915 toolbar.setVisibility(View.VISIBLE);
2917 // Get a handle for the input method manager.
2918 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
2920 // Remove the lint warning below that the input method manager might be null.
2921 assert inputMethodManager != null;
2923 // Hide the keyboard.
2924 inputMethodManager.hideSoftInputFromWindow(toolbar.getWindowToken(), 0);
2928 public void onApplyNewFontSize(DialogFragment dialogFragment) {
2930 Dialog dialog = dialogFragment.getDialog();
2932 // Remove the incorrect lint warning below tha the dialog might be null.
2933 assert dialog != null;
2935 // Get a handle for the font size edit text.
2936 EditText fontSizeEditText = dialog.findViewById(R.id.font_size_edittext);
2938 // Initialize the new font size variable with the current font size.
2939 int newFontSize = currentWebView.getSettings().getTextZoom();
2941 // Get the font size from the edit text.
2943 newFontSize = Integer.parseInt(fontSizeEditText.getText().toString());
2944 } catch (Exception exception) {
2945 // If the edit text does not contain a valid font size do nothing.
2948 // Apply the new font size.
2949 currentWebView.getSettings().setTextZoom(newFontSize);
2953 public void onOpen(DialogFragment dialogFragment) {
2955 Dialog dialog = dialogFragment.getDialog();
2957 // Remove the incorrect lint warning below that the dialog might be null.
2958 assert dialog != null;
2960 // Get a handle for the file name edit text.
2961 EditText fileNameEditText = dialog.findViewById(R.id.file_name_edittext);
2963 // Get the file path string.
2964 openFilePath = fileNameEditText.getText().toString();
2966 // Check to see if the storage permission is needed.
2967 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // The storage permission has been granted.
2969 currentWebView.loadUrl("file://" + openFilePath);
2970 } else { // The storage permission has not been granted.
2971 // Get the external private directory file.
2972 File externalPrivateDirectoryFile = getExternalFilesDir(null);
2974 // Remove the incorrect lint error below that the file might be null.
2975 assert externalPrivateDirectoryFile != null;
2977 // Get the external private directory string.
2978 String externalPrivateDirectory = externalPrivateDirectoryFile.toString();
2980 // Check to see if the file path is in the external private directory.
2981 if (openFilePath.startsWith(externalPrivateDirectory)) { // the file path is in the external private directory.
2983 currentWebView.loadUrl("file://" + openFilePath);
2984 } else { // The file path is in a public directory.
2985 // Check if the user has previously denied the storage permission.
2986 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2987 // Instantiate the storage permission alert dialog.
2988 DialogFragment storagePermissionDialogFragment = StoragePermissionDialog.displayDialog(StoragePermissionDialog.OPEN);
2990 // Show the storage permission alert dialog. The permission will be requested the the dialog is closed.
2991 storagePermissionDialogFragment.show(getSupportFragmentManager(), getString(R.string.storage_permission));
2992 } else { // Show the permission request directly.
2993 // Request the write external storage permission. The file will be opened when it finishes.
2994 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_OPEN_REQUEST_CODE);
3001 public void onSaveWebpage(int saveType, DialogFragment dialogFragment) {
3003 Dialog dialog = dialogFragment.getDialog();
3005 // Remove the incorrect lint warning below that the dialog might be null.
3006 assert dialog != null;
3008 // Get a handle for the edit texts.
3009 EditText urlEditText = dialog.findViewById(R.id.url_edittext);
3010 EditText fileNameEditText = dialog.findViewById(R.id.file_name_edittext);
3012 // Get the strings from the edit texts.
3013 saveWebpageUrl = urlEditText.getText().toString();
3014 saveWebpageFilePath = fileNameEditText.getText().toString();
3016 // Check to see if the storage permission is needed.
3017 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // The storage permission has been granted.
3018 //Save the webpage according to the save type.
3020 case StoragePermissionDialog.SAVE_URL:
3022 new SaveUrl(this, this, saveWebpageFilePath, currentWebView.getSettings().getUserAgentString(), currentWebView.getAcceptFirstPartyCookies()).execute(saveWebpageUrl);
3025 case StoragePermissionDialog.SAVE_AS_ARCHIVE:
3026 // Save the webpage archive.
3027 currentWebView.saveWebArchive(saveWebpageFilePath);
3030 case StoragePermissionDialog.SAVE_AS_IMAGE:
3031 // Save the webpage image.
3032 new SaveWebpageImage(this, currentWebView).execute(saveWebpageFilePath);
3035 } else { // The storage permission has not been granted.
3036 // Get the external private directory file.
3037 File externalPrivateDirectoryFile = getExternalFilesDir(null);
3039 // Remove the incorrect lint error below that the file might be null.
3040 assert externalPrivateDirectoryFile != null;
3042 // Get the external private directory string.
3043 String externalPrivateDirectory = externalPrivateDirectoryFile.toString();
3045 // Check to see if the file path is in the external private directory.
3046 if (saveWebpageFilePath.startsWith(externalPrivateDirectory)) { // The file path is in the external private directory.
3047 // Save the webpage according to the save type.
3049 case StoragePermissionDialog.SAVE_URL:
3051 new SaveUrl(this, this, saveWebpageFilePath, currentWebView.getSettings().getUserAgentString(), currentWebView.getAcceptFirstPartyCookies()).execute(saveWebpageUrl);
3054 case StoragePermissionDialog.SAVE_AS_ARCHIVE:
3055 // Save the webpage archive.
3056 currentWebView.saveWebArchive(saveWebpageFilePath);
3059 case StoragePermissionDialog.SAVE_AS_IMAGE:
3060 // Save the webpage image.
3061 new SaveWebpageImage(this, currentWebView).execute(saveWebpageFilePath);
3064 } else { // The file path is in a public directory.
3065 // Check if the user has previously denied the storage permission.
3066 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
3067 // Instantiate the storage permission alert dialog.
3068 DialogFragment storagePermissionDialogFragment = StoragePermissionDialog.displayDialog(saveType);
3070 // Show the storage permission alert dialog. The permission will be requested when the dialog is closed.
3071 storagePermissionDialogFragment.show(getSupportFragmentManager(), getString(R.string.storage_permission));
3072 } else { // Show the permission request directly.
3074 case StoragePermissionDialog.SAVE_URL:
3075 // Request the write external storage permission. The URL will be saved when it finishes.
3076 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_SAVE_URL_REQUEST_CODE);
3078 case StoragePermissionDialog.SAVE_AS_ARCHIVE:
3079 // Request the write external storage permission. The webpage archive will be saved when it finishes.
3080 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_SAVE_AS_ARCHIVE_REQUEST_CODE);
3083 case StoragePermissionDialog.SAVE_AS_IMAGE:
3084 // Request the write external storage permission. The webpage image will be saved when it finishes.
3085 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_SAVE_AS_IMAGE_REQUEST_CODE);
3094 public void onCloseStoragePermissionDialog(int requestType) {
3095 switch (requestType) {
3096 case StoragePermissionDialog.OPEN:
3097 // Request the write external storage permission. The file will be opened when it finishes.
3098 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_OPEN_REQUEST_CODE);
3101 case StoragePermissionDialog.SAVE_URL:
3102 // Request the write external storage permission. The URL will be saved when it finishes.
3103 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_SAVE_URL_REQUEST_CODE);
3106 case StoragePermissionDialog.SAVE_AS_ARCHIVE:
3107 // Request the write external storage permission. The webpage archive will be saved when it finishes.
3108 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_SAVE_AS_ARCHIVE_REQUEST_CODE);
3111 case StoragePermissionDialog.SAVE_AS_IMAGE:
3112 // Request the write external storage permission. The webpage image will be saved when it finishes.
3113 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_SAVE_AS_IMAGE_REQUEST_CODE);
3119 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
3120 //Only process the results if they exist (this method is triggered when a dialog is presented the first time for an app, but no grant results are included).
3121 if (grantResults.length > 0) {
3122 switch (requestCode) {
3123 case PERMISSION_OPEN_REQUEST_CODE:
3124 // Check to see if the storage permission was granted. If the dialog was canceled the grant results will be empty.
3125 if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // The storage permission was granted.
3127 currentWebView.loadUrl("file://" + openFilePath);
3128 } else { // The storage permission was not granted.
3129 // Display an error snackbar.
3130 Snackbar.make(currentWebView, getString(R.string.cannot_use_location), Snackbar.LENGTH_LONG).show();
3133 // Reset the open file path.
3137 case PERMISSION_SAVE_URL_REQUEST_CODE:
3138 // Check to see if the storage permission was granted. If the dialog was canceled the grant results will be empty.
3139 if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // The storage permission was granted.
3140 // Save the raw URL.
3141 new SaveUrl(this, this, saveWebpageFilePath, currentWebView.getSettings().getUserAgentString(), currentWebView.getAcceptFirstPartyCookies()).execute(saveWebpageUrl);
3142 } else { // The storage permission was not granted.
3143 // Display an error snackbar.
3144 Snackbar.make(currentWebView, getString(R.string.cannot_use_location), Snackbar.LENGTH_LONG).show();
3147 // Reset the save strings.
3148 saveWebpageUrl = "";
3149 saveWebpageFilePath = "";
3152 case PERMISSION_SAVE_AS_ARCHIVE_REQUEST_CODE:
3153 // Check to see if the storage permission was granted. If the dialog was canceled the grant results will be empty.
3154 if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // The storage permission was granted.
3155 // Save the webpage archive.
3156 currentWebView.saveWebArchive(saveWebpageFilePath);
3157 } else { // The storage permission was not granted.
3158 // Display an error snackbar.
3159 Snackbar.make(currentWebView, getString(R.string.cannot_use_location), Snackbar.LENGTH_LONG).show();
3162 // Reset the save webpage file path.
3163 saveWebpageFilePath = "";
3166 case PERMISSION_SAVE_AS_IMAGE_REQUEST_CODE:
3167 // Check to see if the storage permission was granted. If the dialog was canceled the grant results will be empty.
3168 if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // The storage permission was granted.
3169 // Save the webpage image.
3170 new SaveWebpageImage(this, currentWebView).execute(saveWebpageFilePath);
3171 } else { // The storage permission was not granted.
3172 // Display an error snackbar.
3173 Snackbar.make(currentWebView, getString(R.string.cannot_use_location), Snackbar.LENGTH_LONG).show();
3176 // Reset the save webpage file path.
3177 saveWebpageFilePath = "";
3183 private void applyAppSettings() {
3184 // Initialize the app if this is the first run. This is done here instead of in `onCreate()` to shorten the time that an unthemed background is displayed on app startup.
3185 if (webViewDefaultUserAgent == null) {
3189 // Get a handle for the shared preferences.
3190 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3192 // Store the values from the shared preferences in variables.
3193 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3194 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3195 sanitizeGoogleAnalytics = sharedPreferences.getBoolean("google_analytics", true);
3196 sanitizeFacebookClickIds = sharedPreferences.getBoolean("facebook_click_ids", true);
3197 sanitizeTwitterAmpRedirects = sharedPreferences.getBoolean("twitter_amp_redirects", true);
3198 proxyMode = sharedPreferences.getString("proxy", getString(R.string.proxy_default_value));
3199 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3200 hideAppBar = sharedPreferences.getBoolean("hide_app_bar", true);
3201 scrollAppBar = sharedPreferences.getBoolean("scroll_app_bar", true);
3203 // Get the search string.
3204 String searchString = sharedPreferences.getString("search", getString(R.string.search_default_value));
3206 // Set the search string.
3207 if (searchString.equals("Custom URL")) { // A custom search string is used.
3208 searchURL = sharedPreferences.getString("search_custom_url", getString(R.string.search_custom_url_default_value));
3209 } else { // A custom search string is not used.
3210 searchURL = searchString;
3213 // Get handles for the views that need to be modified.
3214 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
3215 AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
3216 ActionBar actionBar = getSupportActionBar();
3217 Toolbar toolbar = findViewById(R.id.toolbar);
3218 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
3219 LinearLayout tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
3220 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
3222 // Remove the incorrect lint warning below that the action bar might be null.
3223 assert actionBar != null;
3228 // Set Do Not Track status.
3229 if (doNotTrackEnabled) {
3230 customHeaders.put("DNT", "1");
3232 customHeaders.remove("DNT");
3235 // Get the current layout parameters. Using coordinator layout parameters allows the `setBehavior()` command and using app bar layout parameters allows the `setScrollFlags()` command.
3236 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
3237 AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) toolbar.getLayoutParams();
3238 AppBarLayout.LayoutParams findOnPageLayoutParams = (AppBarLayout.LayoutParams) findOnPageLinearLayout.getLayoutParams();
3239 AppBarLayout.LayoutParams tabsLayoutParams = (AppBarLayout.LayoutParams) tabsLinearLayout.getLayoutParams();
3241 // Add the scrolling behavior to the layout parameters.
3243 // Enable scrolling of the app bar.
3244 swipeRefreshLayoutParams.setBehavior(new AppBarLayout.ScrollingViewBehavior());
3245 toolbarLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3246 findOnPageLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3247 tabsLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3249 // Disable scrolling of the app bar.
3250 swipeRefreshLayoutParams.setBehavior(null);
3251 toolbarLayoutParams.setScrollFlags(0);
3252 findOnPageLayoutParams.setScrollFlags(0);
3253 tabsLayoutParams.setScrollFlags(0);
3255 // Expand the app bar if it is currently collapsed.
3256 appBarLayout.setExpanded(true);
3259 // Apply the modified layout parameters.
3260 swipeRefreshLayout.setLayoutParams(swipeRefreshLayoutParams);
3261 toolbar.setLayoutParams(toolbarLayoutParams);
3262 findOnPageLinearLayout.setLayoutParams(findOnPageLayoutParams);
3263 tabsLinearLayout.setLayoutParams(tabsLayoutParams);
3265 // Set the app bar scrolling for each WebView.
3266 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3267 // Get the WebView tab fragment.
3268 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3270 // Get the fragment view.
3271 View fragmentView = webViewTabFragment.getView();
3273 // Only modify the WebViews if they exist.
3274 if (fragmentView != null) {
3275 // Get the nested scroll WebView from the tab fragment.
3276 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3278 // Set the app bar scrolling.
3279 nestedScrollWebView.setNestedScrollingEnabled(scrollAppBar);
3283 // Update the full screen browsing mode settings.
3284 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
3285 // Update the visibility of the app bar, which might have changed in the settings.
3287 // Hide the tab linear layout.
3288 tabsLinearLayout.setVisibility(View.GONE);
3290 // Hide the action bar.
3293 // Show the tab linear layout.
3294 tabsLinearLayout.setVisibility(View.VISIBLE);
3296 // Show the action bar.
3300 // Hide the banner ad in the free flavor.
3301 if (BuildConfig.FLAVOR.contentEquals("free")) {
3302 AdHelper.hideAd(findViewById(R.id.adview));
3305 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
3306 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3308 /* Hide the system bars.
3309 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3310 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
3311 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3312 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3314 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
3315 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3316 } else { // Privacy Browser is not in full screen browsing mode.
3317 // 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.
3318 inFullScreenBrowsingMode = false;
3320 // Show the tab linear layout.
3321 tabsLinearLayout.setVisibility(View.VISIBLE);
3323 // Show the action bar.
3326 // Show the banner ad in the free flavor.
3327 if (BuildConfig.FLAVOR.contentEquals("free")) {
3328 // Initialize the ads. If this isn't the first run, `loadAd()` will be automatically called instead.
3329 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getSupportFragmentManager(), getString(R.string.google_app_id), getString(R.string.ad_unit_id));
3332 // Remove the `SYSTEM_UI` flags from the root frame layout.
3333 rootFrameLayout.setSystemUiVisibility(0);
3335 // Add the translucent status flag.
3336 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3340 private void initializeApp() {
3341 // Get a handle for the shared preferences.
3342 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3344 // Get the theme preference.
3345 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
3347 // Get a handle for the input method.
3348 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
3350 // Remove the lint warning below that the input method manager might be null.
3351 assert inputMethodManager != null;
3353 // Initialize the foreground color spans for highlighting the URLs. We have to use the deprecated `getColor()` until API >= 23.
3354 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
3355 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
3356 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
3358 // Get handles for the URL views.
3359 EditText urlEditText = findViewById(R.id.url_edittext);
3361 // Remove the formatting from the URL edit text when the user is editing the text.
3362 urlEditText.setOnFocusChangeListener((View v, boolean hasFocus) -> {
3363 if (hasFocus) { // The user is editing the URL text box.
3364 // Remove the highlighting.
3365 urlEditText.getText().removeSpan(redColorSpan);
3366 urlEditText.getText().removeSpan(initialGrayColorSpan);
3367 urlEditText.getText().removeSpan(finalGrayColorSpan);
3368 } else { // The user has stopped editing the URL text box.
3369 // Move to the beginning of the string.
3370 urlEditText.setSelection(0);
3372 // Reapply the highlighting.
3377 // Set the go button on the keyboard to load the URL in `urlTextBox`.
3378 urlEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
3379 // If the event is a key-down event on the `enter` button, load the URL.
3380 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
3381 // Load the URL into the mainWebView and consume the event.
3382 loadUrlFromTextBox();
3384 // If the enter key was pressed, consume the event.
3387 // If any other key was pressed, do not consume the event.
3392 // Create an Orbot status broadcast receiver.
3393 orbotStatusBroadcastReceiver = new BroadcastReceiver() {
3395 public void onReceive(Context context, Intent intent) {
3396 // Store the content of the status message in `orbotStatus`.
3397 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
3399 // If Privacy Browser is waiting on the proxy, load the website now that Orbot is connected.
3400 if ((orbotStatus != null) && orbotStatus.equals("ON") && waitingForProxy) {
3401 // Reset the waiting for proxy status.
3402 waitingForProxy = false;
3404 // Get a handle for the waiting for proxy dialog.
3405 DialogFragment waitingForProxyDialogFragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.waiting_for_proxy_dialog));
3407 // Dismiss the waiting for proxy dialog if it is displayed.
3408 if (waitingForProxyDialogFragment != null) {
3409 waitingForProxyDialogFragment.dismiss();
3412 // Reload existing URLs and load any URLs that are waiting for the proxy.
3413 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3414 // Get the WebView tab fragment.
3415 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3417 // Get the fragment view.
3418 View fragmentView = webViewTabFragment.getView();
3420 // Only process the WebViews if they exist.
3421 if (fragmentView != null) {
3422 // Get the nested scroll WebView from the tab fragment.
3423 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3425 // Get the waiting for proxy URL string.
3426 String waitingForProxyUrlString = nestedScrollWebView.getWaitingForProxyUrlString();
3428 // Load the pending URL if it exists.
3429 if (!waitingForProxyUrlString.isEmpty()) { // A URL is waiting to be loaded.
3431 loadUrl(nestedScrollWebView, waitingForProxyUrlString);
3433 // Reset the waiting for proxy URL string.
3434 nestedScrollWebView.resetWaitingForProxyUrlString();
3435 } else { // No URL is waiting to be loaded.
3436 // Reload the existing URL.
3437 nestedScrollWebView.reload();
3445 // Register the Orbot status broadcast receiver on `this` context.
3446 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
3448 // Get handles for views that need to be modified.
3449 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
3450 NavigationView navigationView = findViewById(R.id.navigationview);
3451 TabLayout tabLayout = findViewById(R.id.tablayout);
3452 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
3453 ViewPager webViewPager = findViewById(R.id.webviewpager);
3454 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
3455 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
3456 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
3457 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
3458 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
3460 // Listen for touches on the navigation menu.
3461 navigationView.setNavigationItemSelectedListener(this);
3463 // Get handles for the navigation menu and the back and forward menu items. The menu is 0 based.
3464 Menu navigationMenu = navigationView.getMenu();
3465 MenuItem navigationBackMenuItem = navigationMenu.getItem(2);
3466 MenuItem navigationForwardMenuItem = navigationMenu.getItem(3);
3467 MenuItem navigationHistoryMenuItem = navigationMenu.getItem(4);
3468 MenuItem navigationRequestsMenuItem = navigationMenu.getItem(6);
3470 // Update the web view pager every time a tab is modified.
3471 webViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
3473 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
3478 public void onPageSelected(int position) {
3479 // Close the find on page bar if it is open.
3480 closeFindOnPage(null);
3482 // Set the current WebView.
3483 setCurrentWebView(position);
3485 // Select the corresponding tab if it does not match the currently selected page. This will happen if the page was scrolled via swiping in the view pager or by creating a new tab.
3486 if (tabLayout.getSelectedTabPosition() != position) {
3487 // Create a handler to select the tab.
3488 Handler selectTabHandler = new Handler();
3490 // Create a runnable to select the tab.
3491 Runnable selectTabRunnable = () -> {
3492 // Get a handle for the tab.
3493 TabLayout.Tab tab = tabLayout.getTabAt(position);
3495 // Assert that the tab is not null.
3502 // Select the tab layout after 150 milliseconds, which leaves enough time for a new tab to be inflated.
3503 selectTabHandler.postDelayed(selectTabRunnable, 150);
3508 public void onPageScrollStateChanged(int state) {
3513 // Display the View SSL Certificate dialog when the currently selected tab is reselected.
3514 tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
3516 public void onTabSelected(TabLayout.Tab tab) {
3517 // Select the same page in the view pager.
3518 webViewPager.setCurrentItem(tab.getPosition());
3522 public void onTabUnselected(TabLayout.Tab tab) {
3527 public void onTabReselected(TabLayout.Tab tab) {
3528 // Instantiate the View SSL Certificate dialog.
3529 DialogFragment viewSslCertificateDialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView.getWebViewFragmentId());
3531 // Display the View SSL Certificate dialog.
3532 viewSslCertificateDialogFragment.show(getSupportFragmentManager(), getString(R.string.view_ssl_certificate));
3536 // Set the bookmarks drawer resources according to the theme. This can't be done in the layout due to compatibility issues with the `DrawerLayout` support widget.
3537 // The deprecated `getResources().getDrawable()` must be used until the minimum API >= 21 and and `getResources().getColor()` must be used until the minimum API >= 23.
3539 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
3540 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
3541 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
3542 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
3544 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
3545 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
3546 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
3547 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
3550 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
3551 launchBookmarksActivityFab.setOnClickListener(v -> {
3552 // Get a copy of the favorite icon bitmap.
3553 Bitmap favoriteIconBitmap = currentWebView.getFavoriteOrDefaultIcon();
3555 // Create a favorite icon byte array output stream.
3556 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3558 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
3559 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
3561 // Convert the favorite icon byte array stream to a byte array.
3562 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
3564 // Create an intent to launch the bookmarks activity.
3565 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
3567 // Add the extra information to the intent.
3568 bookmarksIntent.putExtra("current_url", currentWebView.getUrl());
3569 bookmarksIntent.putExtra("current_title", currentWebView.getTitle());
3570 bookmarksIntent.putExtra("current_folder", currentBookmarksFolder);
3571 bookmarksIntent.putExtra("favorite_icon_byte_array", favoriteIconByteArray);
3574 startActivity(bookmarksIntent);
3577 // Set the create new bookmark folder FAB to display an alert dialog.
3578 createBookmarkFolderFab.setOnClickListener(v -> {
3579 // Create a create bookmark folder dialog.
3580 DialogFragment createBookmarkFolderDialog = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView.getFavoriteOrDefaultIcon());
3582 // Show the create bookmark folder dialog.
3583 createBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.create_folder));
3586 // Set the create new bookmark FAB to display an alert dialog.
3587 createBookmarkFab.setOnClickListener(view -> {
3588 // Instantiate the create bookmark dialog.
3589 DialogFragment createBookmarkDialog = CreateBookmarkDialog.createBookmark(currentWebView.getUrl(), currentWebView.getTitle(), currentWebView.getFavoriteOrDefaultIcon());
3591 // Display the create bookmark dialog.
3592 createBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.create_bookmark));
3595 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
3596 findOnPageEditText.addTextChangedListener(new TextWatcher() {
3598 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
3603 public void onTextChanged(CharSequence s, int start, int before, int count) {
3608 public void afterTextChanged(Editable s) {
3609 // 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.
3610 if (currentWebView != null) {
3611 currentWebView.findAllAsync(findOnPageEditText.getText().toString());
3616 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
3617 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
3618 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
3619 // Hide the soft keyboard.
3620 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3622 // Consume the event.
3624 } else { // A different key was pressed.
3625 // Do not consume the event.
3630 // Implement swipe to refresh.
3631 swipeRefreshLayout.setOnRefreshListener(() -> currentWebView.reload());
3633 // Store the default progress view offsets for use later in `initializeWebView()`.
3634 defaultProgressViewStartOffset = swipeRefreshLayout.getProgressViewStartOffset();
3635 defaultProgressViewEndOffset = swipeRefreshLayout.getProgressViewEndOffset();
3637 // Set the swipe to refresh color according to the theme.
3639 swipeRefreshLayout.setColorSchemeResources(R.color.blue_800);
3640 swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.gray_850);
3642 swipeRefreshLayout.setColorSchemeResources(R.color.blue_500);
3645 // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
3646 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
3647 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
3649 // Initialize the bookmarks database helper. The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
3650 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
3652 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
3653 currentBookmarksFolder = "";
3655 // Load the home folder, which is `""` in the database.
3656 loadBookmarksFolder();
3658 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
3659 // Convert the id from long to int to match the format of the bookmarks database.
3660 int databaseId = (int) id;
3662 // Get the bookmark cursor for this ID.
3663 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseId);
3665 // Move the bookmark cursor to the first row.
3666 bookmarkCursor.moveToFirst();
3668 // Act upon the bookmark according to the type.
3669 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
3670 // Store the new folder name in `currentBookmarksFolder`.
3671 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3673 // Load the new folder.
3674 loadBookmarksFolder();
3675 } else { // The selected bookmark is not a folder.
3676 // Load the bookmark URL.
3677 loadUrl(currentWebView, bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
3679 // Close the bookmarks drawer.
3680 drawerLayout.closeDrawer(GravityCompat.END);
3683 // Close the `Cursor`.
3684 bookmarkCursor.close();
3687 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
3688 // Convert the database ID from `long` to `int`.
3689 int databaseId = (int) id;
3691 // Find out if the selected bookmark is a folder.
3692 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
3695 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
3696 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3698 // Instantiate the edit folder bookmark dialog.
3699 DialogFragment editBookmarkFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
3701 // Show the edit folder bookmark dialog.
3702 editBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.edit_folder));
3704 // Get the bookmark cursor for this ID.
3705 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseId);
3707 // Move the bookmark cursor to the first row.
3708 bookmarkCursor.moveToFirst();
3710 // Load the bookmark in a new tab but do not switch to the tab or close the drawer.
3711 addNewTab(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)), false);
3714 // Consume the event.
3718 // Get the status bar pixel size.
3719 int statusBarResourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
3720 int statusBarPixelSize = getResources().getDimensionPixelSize(statusBarResourceId);
3722 // Get the resource density.
3723 float screenDensity = getResources().getDisplayMetrics().density;
3725 // Calculate the drawer header padding. This is used to move the text in the drawer headers below any cutouts.
3726 drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
3727 drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
3728 drawerHeaderPaddingBottom = (int) (8 * screenDensity);
3730 // The drawer listener is used to update the navigation menu.
3731 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
3733 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
3737 public void onDrawerOpened(@NonNull View drawerView) {
3741 public void onDrawerClosed(@NonNull View drawerView) {
3745 public void onDrawerStateChanged(int newState) {
3746 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // A drawer is opening or closing.
3747 // Get handles for the drawer headers.
3748 TextView navigationHeaderTextView = findViewById(R.id.navigationText);
3749 TextView bookmarksHeaderTextView = findViewById(R.id.bookmarks_title_textview);
3751 // Apply the navigation header paddings if the view is not null (sometimes it is null if another activity has already started). This moves the text in the header below any cutouts.
3752 if (navigationHeaderTextView != null) {
3753 navigationHeaderTextView.setPadding(drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingTop, drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingBottom);
3756 // Apply the bookmarks header paddings if the view is not null (sometimes it is null if another activity has already started). This moves the text in the header below any cutouts.
3757 if (bookmarksHeaderTextView != null) {
3758 bookmarksHeaderTextView.setPadding(drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingTop, drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingBottom);
3761 // Update the navigation menu items if the WebView is not null.
3762 if (currentWebView != null) {
3763 navigationBackMenuItem.setEnabled(currentWebView.canGoBack());
3764 navigationForwardMenuItem.setEnabled(currentWebView.canGoForward());
3765 navigationHistoryMenuItem.setEnabled((currentWebView.canGoBack() || currentWebView.canGoForward()));
3766 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
3768 // Hide the keyboard (if displayed).
3769 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3772 // Clear the focus from from the URL text box and the WebView. This removes any text selection markers and context menus, which otherwise draw above the open drawers.
3773 urlEditText.clearFocus();
3774 currentWebView.clearFocus();
3779 // Replace the header that `WebView` creates for `X-Requested-With` with a null value. The default value is the application ID (com.stoutner.privacybrowser.standard).
3780 customHeaders.put("X-Requested-With", "");
3782 // Inflate a bare WebView to get the default user agent. It is not used to render content on the screen.
3783 @SuppressLint("InflateParams") View webViewLayout = getLayoutInflater().inflate(R.layout.bare_webview, null, false);
3785 // Get a handle for the WebView.
3786 WebView bareWebView = webViewLayout.findViewById(R.id.bare_webview);
3788 // Store the default user agent.
3789 webViewDefaultUserAgent = bareWebView.getSettings().getUserAgentString();
3791 // Destroy the bare WebView.
3792 bareWebView.destroy();
3796 public void navigateHistory(String url, int steps) {
3797 // Apply the domain settings.
3798 applyDomainSettings(currentWebView, url, false, false);
3800 // Load the history entry.
3801 currentWebView.goBackOrForward(steps);
3805 public void pinnedErrorGoBack() {
3806 // Get the current web back forward list.
3807 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
3809 // Get the previous entry URL.
3810 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
3812 // Apply the domain settings.
3813 applyDomainSettings(currentWebView, previousUrl, false, false);
3816 currentWebView.goBack();
3819 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
3820 @SuppressLint("SetJavaScriptEnabled")
3821 private boolean applyDomainSettings(NestedScrollWebView nestedScrollWebView, String url, boolean resetTab, boolean reloadWebsite) {
3822 // Store a copy of the current user agent to track changes for the return boolean.
3823 String initialUserAgent = nestedScrollWebView.getSettings().getUserAgentString();
3825 // Store the current URL.
3826 nestedScrollWebView.setCurrentUrl(url);
3828 // Parse the URL into a URI.
3829 Uri uri = Uri.parse(url);
3831 // Extract the domain from `uri`.
3832 String newHostName = uri.getHost();
3834 // Strings don't like to be null.
3835 if (newHostName == null) {
3839 // 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.
3840 if (!nestedScrollWebView.getCurrentDomainName().equals(newHostName) || newHostName.equals("")) {
3841 // Set the new host name as the current domain name.
3842 nestedScrollWebView.setCurrentDomainName(newHostName);
3844 // Reset the ignoring of pinned domain information.
3845 nestedScrollWebView.setIgnorePinnedDomainInformation(false);
3847 // Clear any pinned SSL certificate or IP addresses.
3848 nestedScrollWebView.clearPinnedSslCertificate();
3849 nestedScrollWebView.clearPinnedIpAddresses();
3851 // Reset the favorite icon if specified.
3853 // Initialize the favorite icon.
3854 nestedScrollWebView.initializeFavoriteIcon();
3856 // Get the current page position.
3857 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
3859 // Get a handle for the tab layout.
3860 TabLayout tabLayout = findViewById(R.id.tablayout);
3862 // Get the corresponding tab.
3863 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
3865 // Update the tab if it isn't null, which sometimes happens when restarting from the background.
3867 // Get the tab custom view.
3868 View tabCustomView = tab.getCustomView();
3870 // Remove the warning below that the tab custom view might be null.
3871 assert tabCustomView != null;
3873 // Get the tab views.
3874 ImageView tabFavoriteIconImageView = tabCustomView.findViewById(R.id.favorite_icon_imageview);
3875 TextView tabTitleTextView = tabCustomView.findViewById(R.id.title_textview);
3877 // Set the default favorite icon as the favorite icon for this tab.
3878 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nestedScrollWebView.getFavoriteOrDefaultIcon(), 64, 64, true));
3880 // Set the loading title text.
3881 tabTitleTextView.setText(R.string.loading);
3885 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3886 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3888 // Get a full cursor from `domainsDatabaseHelper`.
3889 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3891 // Initialize `domainSettingsSet`.
3892 Set<String> domainSettingsSet = new HashSet<>();
3894 // Get the domain name column index.
3895 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3897 // Populate `domainSettingsSet`.
3898 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3899 // Move `domainsCursor` to the current row.
3900 domainNameCursor.moveToPosition(i);
3902 // Store the domain name in `domainSettingsSet`.
3903 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3906 // Close `domainNameCursor.
3907 domainNameCursor.close();
3909 // Initialize the domain name in database variable.
3910 String domainNameInDatabase = null;
3912 // Check the hostname against the domain settings set.
3913 if (domainSettingsSet.contains(newHostName)) { // The hostname is contained in the domain settings set.
3914 // Record the domain name in the database.
3915 domainNameInDatabase = newHostName;
3917 // Set the domain settings applied tracker to true.
3918 nestedScrollWebView.setDomainSettingsApplied(true);
3919 } else { // The hostname is not contained in the domain settings set.
3920 // Set the domain settings applied tracker to false.
3921 nestedScrollWebView.setDomainSettingsApplied(false);
3924 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3925 while (!nestedScrollWebView.getDomainSettingsApplied() && newHostName.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the host name.
3926 if (domainSettingsSet.contains("*." + newHostName)) { // Check the host name prepended by `*.`.
3927 // Set the domain settings applied tracker to true.
3928 nestedScrollWebView.setDomainSettingsApplied(true);
3930 // Store the applied domain names as it appears in the database.
3931 domainNameInDatabase = "*." + newHostName;
3934 // Strip out the lowest subdomain of of the host name.
3935 newHostName = newHostName.substring(newHostName.indexOf(".") + 1);
3939 // Get a handle for the shared preferences.
3940 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3942 // Store the general preference information.
3943 String defaultFontSizeString = sharedPreferences.getString("font_size", getString(R.string.font_size_default_value));
3944 String defaultUserAgentName = sharedPreferences.getString("user_agent", getString(R.string.user_agent_default_value));
3945 boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
3946 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
3947 boolean wideViewport = sharedPreferences.getBoolean("wide_viewport", true);
3948 boolean displayWebpageImages = sharedPreferences.getBoolean("display_webpage_images", true);
3950 // Get a handle for the cookie manager.
3951 CookieManager cookieManager = CookieManager.getInstance();
3953 // Get handles for the views.
3954 RelativeLayout urlRelativeLayout = findViewById(R.id.url_relativelayout);
3955 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
3957 // Initialize the user agent array adapter and string array.
3958 ArrayAdapter<CharSequence> userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item);
3959 String[] userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
3961 if (nestedScrollWebView.getDomainSettingsApplied()) { // The url has custom domain settings.
3962 // Get a cursor for the current host and move it to the first position.
3963 Cursor currentDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3964 currentDomainSettingsCursor.moveToFirst();
3966 // Get the settings from the cursor.
3967 nestedScrollWebView.setDomainSettingsDatabaseId(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3968 nestedScrollWebView.setDomainSettingsJavaScriptEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3969 nestedScrollWebView.setAcceptFirstPartyCookies(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3970 boolean domainThirdPartyCookiesEnabled = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3971 nestedScrollWebView.getSettings().setDomStorageEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3972 // Form data can be removed once the minimum API >= 26.
3973 boolean saveFormData = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3974 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASYLIST,
3975 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3976 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASYPRIVACY,
3977 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3978 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST,
3979 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3980 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST,
3981 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3982 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRALIST, currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ULTRALIST)) == 1);
3983 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRAPRIVACY,
3984 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1);
3985 nestedScrollWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS,
3986 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
3987 String userAgentName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3988 int fontSize = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3989 int swipeToRefreshInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
3990 int nightModeInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
3991 int wideViewportInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.WIDE_VIEWPORT));
3992 int displayWebpageImagesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3993 boolean pinnedSslCertificate = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3994 String pinnedSslIssuedToCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3995 String pinnedSslIssuedToOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3996 String pinnedSslIssuedToUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3997 String pinnedSslIssuedByCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3998 String pinnedSslIssuedByOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3999 String pinnedSslIssuedByUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
4000 boolean pinnedIpAddresses = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_IP_ADDRESSES)) == 1);
4001 String pinnedHostIpAddresses = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.IP_ADDRESSES));
4003 // Create the pinned SSL date variables.
4004 Date pinnedSslStartDate;
4005 Date pinnedSslEndDate;
4007 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0 because creating a new Date results in an error if the input is 0.
4008 if (currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
4009 pinnedSslStartDate = null;
4011 pinnedSslStartDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
4014 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0 because creating a new Date results in an error if the input is 0.
4015 if (currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
4016 pinnedSslEndDate = null;
4018 pinnedSslEndDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
4021 // If there is a pinned SSL certificate, store it in the WebView.
4022 if (pinnedSslCertificate) {
4023 nestedScrollWebView.setPinnedSslCertificate(pinnedSslIssuedToCName, pinnedSslIssuedToOName, pinnedSslIssuedToUName, pinnedSslIssuedByCName, pinnedSslIssuedByOName, pinnedSslIssuedByUName,
4024 pinnedSslStartDate, pinnedSslEndDate);
4027 // If there is a pinned IP address, store it in the WebView.
4028 if (pinnedIpAddresses) {
4029 nestedScrollWebView.setPinnedIpAddresses(pinnedHostIpAddresses);
4032 // Set night mode according to the night mode int.
4033 switch (nightModeInt) {
4034 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4035 // Set night mode according to the current default.
4036 nestedScrollWebView.setNightMode(sharedPreferences.getBoolean("night_mode", false));
4039 case DomainsDatabaseHelper.ENABLED:
4040 // Enable night mode.
4041 nestedScrollWebView.setNightMode(true);
4044 case DomainsDatabaseHelper.DISABLED:
4045 // Disable night mode.
4046 nestedScrollWebView.setNightMode(false);
4050 // Enable JavaScript if night mode is enabled.
4051 if (nestedScrollWebView.getNightMode()) {
4052 // Enable JavaScript.
4053 nestedScrollWebView.getSettings().setJavaScriptEnabled(true);
4055 // Set JavaScript according to the domain settings.
4056 nestedScrollWebView.getSettings().setJavaScriptEnabled(nestedScrollWebView.getDomainSettingsJavaScriptEnabled());
4059 // Close the current host domain settings cursor.
4060 currentDomainSettingsCursor.close();
4062 // Apply the domain settings.
4063 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptFirstPartyCookies());
4065 // Set third-party cookies status if API >= 21.
4066 if (Build.VERSION.SDK_INT >= 21) {
4067 cookieManager.setAcceptThirdPartyCookies(nestedScrollWebView, domainThirdPartyCookiesEnabled);
4070 // Apply the form data setting if the API < 26.
4071 if (Build.VERSION.SDK_INT < 26) {
4072 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
4075 // Apply the font size.
4076 try { // Try the specified font size to see if it is valid.
4077 if (fontSize == 0) { // Apply the default font size.
4078 // Try to set the font size from the value in the app settings.
4079 nestedScrollWebView.getSettings().setTextZoom(Integer.parseInt(defaultFontSizeString));
4080 } else { // Apply the font size from domain settings.
4081 nestedScrollWebView.getSettings().setTextZoom(fontSize);
4083 } catch (Exception exception) { // The specified font size is invalid
4084 // Set the font size to be 100%
4085 nestedScrollWebView.getSettings().setTextZoom(100);
4088 // Set the user agent.
4089 if (userAgentName.equals(getString(R.string.system_default_user_agent))) { // Use the system default user agent.
4090 // Get the array position of the default user agent name.
4091 int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4093 // Set the user agent according to the system default.
4094 switch (defaultUserAgentArrayPosition) {
4095 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
4096 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4097 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
4100 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4101 // Set the user agent to `""`, which uses the default value.
4102 nestedScrollWebView.getSettings().setUserAgentString("");
4105 case SETTINGS_CUSTOM_USER_AGENT:
4106 // Set the default custom user agent.
4107 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
4111 // Get the user agent string from the user agent data array
4112 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
4114 } else { // Set the user agent according to the stored name.
4115 // Get the array position of the user agent name.
4116 int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
4118 switch (userAgentArrayPosition) {
4119 case UNRECOGNIZED_USER_AGENT: // The user agent name contains a custom user agent.
4120 nestedScrollWebView.getSettings().setUserAgentString(userAgentName);
4123 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4124 // Set the user agent to `""`, which uses the default value.
4125 nestedScrollWebView.getSettings().setUserAgentString("");
4129 // Get the user agent string from the user agent data array.
4130 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4134 // Set swipe to refresh.
4135 switch (swipeToRefreshInt) {
4136 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4137 // Store the swipe to refresh status in the nested scroll WebView.
4138 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
4140 // Apply swipe to refresh according to the default. This can be removed once the minimum API >= 23 because it is continuously set by an on scroll change listener.
4141 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
4144 case DomainsDatabaseHelper.ENABLED:
4145 // Store the swipe to refresh status in the nested scroll WebView.
4146 nestedScrollWebView.setSwipeToRefresh(true);
4148 // Enable swipe to refresh. This can be removed once the minimum API >= 23 because it is continuously set by an on scroll change listener.
4149 swipeRefreshLayout.setEnabled(true);
4152 case DomainsDatabaseHelper.DISABLED:
4153 // Store the swipe to refresh status in the nested scroll WebView.
4154 nestedScrollWebView.setSwipeToRefresh(false);
4156 // Disable swipe to refresh. This can be removed once the minimum API >= 23 because it is continuously set by an on scroll change listener.
4157 swipeRefreshLayout.setEnabled(false);
4160 // Set the viewport.
4161 switch (wideViewportInt) {
4162 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4163 nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
4166 case DomainsDatabaseHelper.ENABLED:
4167 nestedScrollWebView.getSettings().setUseWideViewPort(true);
4170 case DomainsDatabaseHelper.DISABLED:
4171 nestedScrollWebView.getSettings().setUseWideViewPort(false);
4175 // Set the loading of webpage images.
4176 switch (displayWebpageImagesInt) {
4177 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4178 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4181 case DomainsDatabaseHelper.ENABLED:
4182 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(true);
4185 case DomainsDatabaseHelper.DISABLED:
4186 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(false);
4190 // Set a green background on the URL relative layout to indicate that custom domain settings are being used. The deprecated `.getDrawable()` must be used until the minimum API >= 21.
4192 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
4194 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
4196 } else { // The new URL does not have custom domain settings. Load the defaults.
4197 // Store the values from the shared preferences.
4198 boolean defaultJavaScriptEnabled = sharedPreferences.getBoolean("javascript", false);
4199 nestedScrollWebView.setAcceptFirstPartyCookies(sharedPreferences.getBoolean("first_party_cookies", false));
4200 boolean defaultThirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies", false);
4201 nestedScrollWebView.getSettings().setDomStorageEnabled(sharedPreferences.getBoolean("dom_storage", false));
4202 boolean saveFormData = sharedPreferences.getBoolean("save_form_data", false); // Form data can be removed once the minimum API >= 26.
4203 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASYLIST, sharedPreferences.getBoolean("easylist", true));
4204 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASYPRIVACY, sharedPreferences.getBoolean("easyprivacy", true));
4205 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, sharedPreferences.getBoolean("fanboys_annoyance_list", true));
4206 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, sharedPreferences.getBoolean("fanboys_social_blocking_list", true));
4207 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRALIST, sharedPreferences.getBoolean("ultralist", true));
4208 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRAPRIVACY, sharedPreferences.getBoolean("ultraprivacy", true));
4209 nestedScrollWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, sharedPreferences.getBoolean("block_all_third_party_requests", false));
4210 nestedScrollWebView.setNightMode(sharedPreferences.getBoolean("night_mode", false));
4212 // Enable JavaScript if night mode is enabled.
4213 if (nestedScrollWebView.getNightMode()) {
4214 // Enable JavaScript.
4215 nestedScrollWebView.getSettings().setJavaScriptEnabled(true);
4217 // Set JavaScript according to the domain settings.
4218 nestedScrollWebView.getSettings().setJavaScriptEnabled(defaultJavaScriptEnabled);
4221 // Apply the default first-party cookie setting.
4222 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptFirstPartyCookies());
4224 // Apply the default font size setting.
4226 // Try to set the font size from the value in the app settings.
4227 nestedScrollWebView.getSettings().setTextZoom(Integer.parseInt(defaultFontSizeString));
4228 } catch (Exception exception) {
4229 // If the app settings value is invalid, set the font size to 100%.
4230 nestedScrollWebView.getSettings().setTextZoom(100);
4233 // Apply the form data setting if the API < 26.
4234 if (Build.VERSION.SDK_INT < 26) {
4235 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
4238 // Store the swipe to refresh status in the nested scroll WebView.
4239 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
4241 // Apply swipe to refresh according to the default.
4242 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
4244 // Reset the pinned variables.
4245 nestedScrollWebView.setDomainSettingsDatabaseId(-1);
4247 // Set third-party cookies status if API >= 21.
4248 if (Build.VERSION.SDK_INT >= 21) {
4249 cookieManager.setAcceptThirdPartyCookies(nestedScrollWebView, defaultThirdPartyCookiesEnabled);
4252 // Get the array position of the user agent name.
4253 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4255 // Set the user agent.
4256 switch (userAgentArrayPosition) {
4257 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
4258 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4259 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
4262 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4263 // Set the user agent to `""`, which uses the default value.
4264 nestedScrollWebView.getSettings().setUserAgentString("");
4267 case SETTINGS_CUSTOM_USER_AGENT:
4268 // Set the default custom user agent.
4269 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
4273 // Get the user agent string from the user agent data array
4274 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4277 // Set the viewport.
4278 nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
4280 // Set the loading of webpage images.
4281 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4283 // Set a transparent background on URL edit text. The deprecated `getResources().getDrawable()` must be used until the minimum API >= 21.
4284 urlRelativeLayout.setBackground(getResources().getDrawable(R.color.transparent));
4287 // Close the domains database helper.
4288 domainsDatabaseHelper.close();
4290 // Update the privacy icons.
4291 updatePrivacyIcons(true);
4294 // Reload the website if returning from the Domains activity.
4295 if (reloadWebsite) {
4296 nestedScrollWebView.reload();
4299 // Return the user agent changed status.
4300 return !nestedScrollWebView.getSettings().getUserAgentString().equals(initialUserAgent);
4303 private void applyProxy(boolean reloadWebViews) {
4304 // Get a handle for the shared preferences.
4305 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4307 // Get the theme preferences.
4308 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
4310 // Get a handle for the app bar layout.
4311 AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
4313 // Set the proxy according to the mode. `this` refers to the current activity where an alert dialog might be displayed.
4314 ProxyHelper.setProxy(getApplicationContext(), appBarLayout, proxyMode);
4316 // Reset the waiting for proxy tracker.
4317 waitingForProxy = false;
4319 // Update the user interface and reload the WebViews if requested.
4320 switch (proxyMode) {
4321 case ProxyHelper.NONE:
4322 // Set the default app bar layout background.
4324 appBarLayout.setBackgroundResource(R.color.gray_900);
4326 appBarLayout.setBackgroundResource(R.color.gray_100);
4330 case ProxyHelper.TOR:
4331 // Set the app bar background to indicate proxying through Orbot is enabled.
4333 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4335 appBarLayout.setBackgroundResource(R.color.blue_50);
4338 // Check to see if Orbot is installed.
4340 // Get the package manager.
4341 PackageManager packageManager = getPackageManager();
4343 // 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.
4344 packageManager.getPackageInfo("org.torproject.android", 0);
4346 // Check to see if the proxy is ready.
4347 if (!orbotStatus.equals("ON")) { // Orbot is not ready.
4348 // Set the waiting for proxy status.
4349 waitingForProxy = true;
4351 // Show the waiting for proxy dialog if it isn't already displayed.
4352 if (getSupportFragmentManager().findFragmentByTag(getString(R.string.waiting_for_proxy_dialog)) == null) {
4353 // Get a handle for the waiting for proxy alert dialog.
4354 DialogFragment waitingForProxyDialogFragment = new WaitingForProxyDialog();
4356 // Display the waiting for proxy alert dialog.
4357 waitingForProxyDialogFragment.show(getSupportFragmentManager(), getString(R.string.waiting_for_proxy_dialog));
4360 } catch (PackageManager.NameNotFoundException exception) { // Orbot is not installed.
4361 // Show the Orbot not installed dialog if it is not already displayed.
4362 if (getSupportFragmentManager().findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
4363 // Get a handle for the Orbot not installed alert dialog.
4364 DialogFragment orbotNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode);
4366 // Display the Orbot not installed alert dialog.
4367 orbotNotInstalledDialogFragment.show(getSupportFragmentManager(), getString(R.string.proxy_not_installed_dialog));
4372 case ProxyHelper.I2P:
4373 // Set the app bar background to indicate proxying through Orbot is enabled.
4375 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4377 appBarLayout.setBackgroundResource(R.color.blue_50);
4380 // Check to see if I2P is installed.
4382 // Get the package manager.
4383 PackageManager packageManager = getPackageManager();
4385 // Check to see if I2P is in the list. This will throw an error and drop to the catch section if it isn't installed.
4386 packageManager.getPackageInfo("org.torproject.android", 0);
4387 } catch (PackageManager.NameNotFoundException exception) { // I2P is not installed.
4388 // Sow the I2P not installed dialog if it is not already displayed.
4389 if (getSupportFragmentManager().findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
4390 // Get a handle for the waiting for proxy alert dialog.
4391 DialogFragment i2pNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode);
4393 // Display the I2P not installed alert dialog.
4394 i2pNotInstalledDialogFragment.show(getSupportFragmentManager(), getString(R.string.proxy_not_installed_dialog));
4399 case ProxyHelper.CUSTOM:
4400 // Set the app bar background to indicate proxying through Orbot is enabled.
4402 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4404 appBarLayout.setBackgroundResource(R.color.blue_50);
4409 // Reload the WebViews if requested and not waiting for the proxy.
4410 if (reloadWebViews && !waitingForProxy) {
4411 // Reload the WebViews.
4412 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4413 // Get the WebView tab fragment.
4414 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4416 // Get the fragment view.
4417 View fragmentView = webViewTabFragment.getView();
4419 // Only reload the WebViews if they exist.
4420 if (fragmentView != null) {
4421 // Get the nested scroll WebView from the tab fragment.
4422 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4424 // Reload the WebView.
4425 nestedScrollWebView.reload();
4431 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
4432 // Only update the privacy icons if the options menu and the current WebView have already been populated.
4433 if ((optionsMenu != null) && (currentWebView != null)) {
4434 // Get a handle for the shared preferences.
4435 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4437 // Get the theme and screenshot preferences.
4438 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
4440 // Get handles for the menu items.
4441 MenuItem privacyMenuItem = optionsMenu.findItem(R.id.toggle_javascript);
4442 MenuItem firstPartyCookiesMenuItem = optionsMenu.findItem(R.id.toggle_first_party_cookies);
4443 MenuItem domStorageMenuItem = optionsMenu.findItem(R.id.toggle_dom_storage);
4444 MenuItem refreshMenuItem = optionsMenu.findItem(R.id.refresh);
4446 // Update the privacy icon.
4447 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is enabled.
4448 privacyMenuItem.setIcon(R.drawable.javascript_enabled);
4449 } else if (currentWebView.getAcceptFirstPartyCookies()) { // JavaScript is disabled but cookies are enabled.
4450 privacyMenuItem.setIcon(R.drawable.warning);
4451 } else { // All the dangerous features are disabled.
4452 privacyMenuItem.setIcon(R.drawable.privacy_mode);
4455 // Update the first-party cookies icon.
4456 if (currentWebView.getAcceptFirstPartyCookies()) { // First-party cookies are enabled.
4457 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
4458 } else { // First-party cookies are disabled.
4460 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_dark);
4462 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_light);
4466 // Update the DOM storage icon.
4467 if (currentWebView.getSettings().getJavaScriptEnabled() && currentWebView.getSettings().getDomStorageEnabled()) { // Both JavaScript and DOM storage are enabled.
4468 domStorageMenuItem.setIcon(R.drawable.dom_storage_enabled);
4469 } else if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is enabled but DOM storage is disabled.
4471 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
4473 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
4475 } else { // JavaScript is disabled, so DOM storage is ghosted.
4477 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
4479 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
4483 // Update the refresh icon.
4485 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
4487 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
4490 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
4491 if (runInvalidateOptionsMenu) {
4492 invalidateOptionsMenu();
4497 private void highlightUrlText() {
4498 // Get a handle for the URL edit text.
4499 EditText urlEditText = findViewById(R.id.url_edittext);
4501 // Only highlight the URL text if the box is not currently selected.
4502 if (!urlEditText.hasFocus()) {
4503 // Get the URL string.
4504 String urlString = urlEditText.getText().toString();
4506 // Highlight the URL according to the protocol.
4507 if (urlString.startsWith("file://") || urlString.startsWith("content://")) { // This is a file or content URL.
4508 // De-emphasize everything before the file name.
4509 urlEditText.getText().setSpan(initialGrayColorSpan, 0, urlString.lastIndexOf("/") + 1,Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4510 } else { // This is a web URL.
4511 // Get the index of the `/` immediately after the domain name.
4512 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
4514 // Create a base URL string.
4517 // Get the base URL.
4518 if (endOfDomainName > 0) { // There is at least one character after the base URL.
4519 // Get the base URL.
4520 baseUrl = urlString.substring(0, endOfDomainName);
4521 } else { // There are no characters after the base URL.
4522 // Set the base URL to be the entire URL string.
4523 baseUrl = urlString;
4526 // Get the index of the last `.` in the domain.
4527 int lastDotIndex = baseUrl.lastIndexOf(".");
4529 // Get the index of the penultimate `.` in the domain.
4530 int penultimateDotIndex = baseUrl.lastIndexOf(".", lastDotIndex - 1);
4532 // Markup the beginning of the URL.
4533 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
4534 urlEditText.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4536 // De-emphasize subdomains.
4537 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
4538 urlEditText.getText().setSpan(initialGrayColorSpan, 7, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4540 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
4541 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
4542 // De-emphasize the protocol and the additional subdomains.
4543 urlEditText.getText().setSpan(initialGrayColorSpan, 0, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4544 } else { // There is only one subdomain in the domain name.
4545 // De-emphasize only the protocol.
4546 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4550 // De-emphasize the text after the domain name.
4551 if (endOfDomainName > 0) {
4552 urlEditText.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4558 private void loadBookmarksFolder() {
4559 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
4560 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
4562 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
4563 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
4565 public View newView(Context context, Cursor cursor, ViewGroup parent) {
4566 // Inflate the individual item layout. `false` does not attach it to the root.
4567 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
4571 public void bindView(View view, Context context, Cursor cursor) {
4572 // Get handles for the views.
4573 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
4574 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
4576 // Get the favorite icon byte array from the cursor.
4577 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
4579 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
4580 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
4582 // Display the bitmap in `bookmarkFavoriteIcon`.
4583 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4585 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4586 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
4587 bookmarkNameTextView.setText(bookmarkNameString);
4589 // Make the font bold for folders.
4590 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4591 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4592 } else { // Reset the font to default for normal bookmarks.
4593 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4598 // Get a handle for the bookmarks list view.
4599 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
4601 // Populate the list view with the adapter.
4602 bookmarksListView.setAdapter(bookmarksCursorAdapter);
4604 // Get a handle for the bookmarks title text view.
4605 TextView bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
4607 // Set the bookmarks drawer title.
4608 if (currentBookmarksFolder.isEmpty()) {
4609 bookmarksTitleTextView.setText(R.string.bookmarks);
4611 bookmarksTitleTextView.setText(currentBookmarksFolder);
4615 private void openWithApp(String url) {
4616 // Create an open with app intent with `ACTION_VIEW`.
4617 Intent openWithAppIntent = new Intent(Intent.ACTION_VIEW);
4619 // Set the URI but not the MIME type. This should open all available apps.
4620 openWithAppIntent.setData(Uri.parse(url));
4622 // Flag the intent to open in a new task.
4623 openWithAppIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4627 // Show the chooser.
4628 startActivity(openWithAppIntent);
4629 } catch (ActivityNotFoundException exception) { // There are no apps available to open the URL.
4630 // Show a snackbar with the error.
4631 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
4635 private void openWithBrowser(String url) {
4636 // Create an open with browser intent with `ACTION_VIEW`.
4637 Intent openWithBrowserIntent = new Intent(Intent.ACTION_VIEW);
4639 // Set the URI and the MIME type. `"text/html"` should load browser options.
4640 openWithBrowserIntent.setDataAndType(Uri.parse(url), "text/html");
4642 // Flag the intent to open in a new task.
4643 openWithBrowserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4647 // Show the chooser.
4648 startActivity(openWithBrowserIntent);
4649 } catch (ActivityNotFoundException exception) { // There are no browsers available to open the URL.
4650 // Show a snackbar with the error.
4651 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
4655 private String sanitizeUrl(String url) {
4656 // Sanitize Google Analytics.
4657 if (sanitizeGoogleAnalytics) {
4659 if (url.contains("?utm_")) {
4660 url = url.substring(0, url.indexOf("?utm_"));
4664 if (url.contains("&utm_")) {
4665 url = url.substring(0, url.indexOf("&utm_"));
4669 // Sanitize Facebook Click IDs.
4670 if (sanitizeFacebookClickIds) {
4671 // Remove `?fbclid=`.
4672 if (url.contains("?fbclid=")) {
4673 url = url.substring(0, url.indexOf("?fbclid="));
4676 // Remove `&fbclid=`.
4677 if (url.contains("&fbclid=")) {
4678 url = url.substring(0, url.indexOf("&fbclid="));
4681 // Remove `?fbadid=`.
4682 if (url.contains("?fbadid=")) {
4683 url = url.substring(0, url.indexOf("?fbadid="));
4686 // Remove `&fbadid=`.
4687 if (url.contains("&fbadid=")) {
4688 url = url.substring(0, url.indexOf("&fbadid="));
4692 // Sanitize Twitter AMP redirects.
4693 if (sanitizeTwitterAmpRedirects) {
4695 if (url.contains("?amp=1")) {
4696 url = url.substring(0, url.indexOf("?amp=1"));
4700 // Return the sanitized URL.
4704 public void finishedPopulatingBlocklists(ArrayList<ArrayList<List<String[]>>> combinedBlocklists) {
4705 // Store the blocklists.
4706 easyList = combinedBlocklists.get(0);
4707 easyPrivacy = combinedBlocklists.get(1);
4708 fanboysAnnoyanceList = combinedBlocklists.get(2);
4709 fanboysSocialList = combinedBlocklists.get(3);
4710 ultraList = combinedBlocklists.get(4);
4711 ultraPrivacy = combinedBlocklists.get(5);
4713 // Add the first tab.
4714 addNewTab("", true);
4717 public void addTab(View view) {
4718 // Add a new tab with a blank URL.
4719 addNewTab("", true);
4722 private void addNewTab(String url, boolean moveToTab) {
4723 // Sanitize the URL.
4724 url = sanitizeUrl(url);
4726 // Get a handle for the tab layout and the view pager.
4727 TabLayout tabLayout = findViewById(R.id.tablayout);
4728 ViewPager webViewPager = findViewById(R.id.webviewpager);
4730 // Get the new page number. The page numbers are 0 indexed, so the new page number will match the current count.
4731 int newTabNumber = tabLayout.getTabCount();
4734 tabLayout.addTab(tabLayout.newTab());
4737 TabLayout.Tab newTab = tabLayout.getTabAt(newTabNumber);
4739 // Remove the lint warning below that the current tab might be null.
4740 assert newTab != null;
4742 // Set a custom view on the new tab.
4743 newTab.setCustomView(R.layout.tab_custom_view);
4745 // Add the new WebView page.
4746 webViewPagerAdapter.addPage(newTabNumber, webViewPager, url, moveToTab);
4749 public void closeTab(View view) {
4750 // Get a handle for the tab layout.
4751 TabLayout tabLayout = findViewById(R.id.tablayout);
4753 // Run the command according to the number of tabs.
4754 if (tabLayout.getTabCount() > 1) { // There is more than one tab open.
4755 // Close the current tab.
4757 } else { // There is only one tab open.
4762 private void closeCurrentTab() {
4763 // Get handles for the views.
4764 AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
4765 TabLayout tabLayout = findViewById(R.id.tablayout);
4766 ViewPager webViewPager = findViewById(R.id.webviewpager);
4768 // Get the current tab number.
4769 int currentTabNumber = tabLayout.getSelectedTabPosition();
4771 // Delete the current tab.
4772 tabLayout.removeTabAt(currentTabNumber);
4774 // Delete the current page. If the selected page number did not change during the delete, it will return true, meaning that the current WebView must be reset.
4775 if (webViewPagerAdapter.deletePage(currentTabNumber, webViewPager)) {
4776 setCurrentWebView(currentTabNumber);
4779 // Expand the app bar if it is currently collapsed.
4780 appBarLayout.setExpanded(true);
4783 private void clearAndExit() {
4784 // Get a handle for the shared preferences.
4785 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4787 // Close the bookmarks cursor and database.
4788 bookmarksCursor.close();
4789 bookmarksDatabaseHelper.close();
4791 // Get the status of the clear everything preference.
4792 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
4794 // Get a handle for the runtime.
4795 Runtime runtime = Runtime.getRuntime();
4797 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
4798 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
4799 String privateDataDirectoryString = getApplicationInfo().dataDir;
4802 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
4803 // The command to remove cookies changed slightly in API 21.
4804 if (Build.VERSION.SDK_INT >= 21) {
4805 CookieManager.getInstance().removeAllCookies(null);
4807 CookieManager.getInstance().removeAllCookie();
4810 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4812 // Two commands must be used because `Runtime.exec()` does not like `*`.
4813 Process deleteCookiesProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
4814 Process deleteCookiesJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
4816 // Wait until the processes have finished.
4817 deleteCookiesProcess.waitFor();
4818 deleteCookiesJournalProcess.waitFor();
4819 } catch (Exception exception) {
4820 // Do nothing if an error is thrown.
4824 // Clear DOM storage.
4825 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
4826 // Ask `WebStorage` to clear the DOM storage.
4827 WebStorage webStorage = WebStorage.getInstance();
4828 webStorage.deleteAllData();
4830 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4832 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4833 Process deleteLocalStorageProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
4835 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
4836 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
4837 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
4838 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
4839 Process deleteDatabaseProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
4841 // Wait until the processes have finished.
4842 deleteLocalStorageProcess.waitFor();
4843 deleteIndexProcess.waitFor();
4844 deleteQuotaManagerProcess.waitFor();
4845 deleteQuotaManagerJournalProcess.waitFor();
4846 deleteDatabaseProcess.waitFor();
4847 } catch (Exception exception) {
4848 // Do nothing if an error is thrown.
4852 // Clear form data if the API < 26.
4853 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
4854 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
4855 webViewDatabase.clearFormData();
4857 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4859 // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
4860 Process deleteWebDataProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
4861 Process deleteWebDataJournalProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
4863 // Wait until the processes have finished.
4864 deleteWebDataProcess.waitFor();
4865 deleteWebDataJournalProcess.waitFor();
4866 } catch (Exception exception) {
4867 // Do nothing if an error is thrown.
4872 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
4873 // Clear the cache from each WebView.
4874 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4875 // Get the WebView tab fragment.
4876 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4878 // Get the fragment view.
4879 View fragmentView = webViewTabFragment.getView();
4881 // Only clear the cache if the WebView exists.
4882 if (fragmentView != null) {
4883 // Get the nested scroll WebView from the tab fragment.
4884 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4886 // Clear the cache for this WebView.
4887 nestedScrollWebView.clearCache(true);
4891 // Manually delete the cache directories.
4893 // Delete the main cache directory.
4894 Process deleteCacheProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/cache");
4896 // Delete the secondary `Service Worker` cache directory.
4897 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4898 Process deleteServiceWorkerProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
4900 // Wait until the processes have finished.
4901 deleteCacheProcess.waitFor();
4902 deleteServiceWorkerProcess.waitFor();
4903 } catch (Exception exception) {
4904 // Do nothing if an error is thrown.
4908 // Wipe out each WebView.
4909 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4910 // Get the WebView tab fragment.
4911 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4913 // Get the fragment view.
4914 View fragmentView = webViewTabFragment.getView();
4916 // Only wipe out the WebView if it exists.
4917 if (fragmentView != null) {
4918 // Get the nested scroll WebView from the tab fragment.
4919 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4921 // Clear SSL certificate preferences for this WebView.
4922 nestedScrollWebView.clearSslPreferences();
4924 // Clear the back/forward history for this WebView.
4925 nestedScrollWebView.clearHistory();
4927 // Destroy the internal state of `mainWebView`.
4928 nestedScrollWebView.destroy();
4932 // Clear the custom headers.
4933 customHeaders.clear();
4935 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
4936 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
4937 if (clearEverything) {
4939 // Delete the folder.
4940 Process deleteAppWebviewProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
4942 // Wait until the process has finished.
4943 deleteAppWebviewProcess.waitFor();
4944 } catch (Exception exception) {
4945 // Do nothing if an error is thrown.
4949 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
4950 if (Build.VERSION.SDK_INT >= 21) {
4951 finishAndRemoveTask();
4956 // Remove the terminated program from RAM. The status code is `0`.
4960 private void setCurrentWebView(int pageNumber) {
4961 // Get a handle for the shared preferences.
4962 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4964 // Get the theme preference.
4965 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
4967 // Get handles for the URL views.
4968 RelativeLayout urlRelativeLayout = findViewById(R.id.url_relativelayout);
4969 EditText urlEditText = findViewById(R.id.url_edittext);
4970 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
4972 // Stop the swipe to refresh indicator if it is running
4973 swipeRefreshLayout.setRefreshing(false);
4975 // Get the WebView tab fragment.
4976 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(pageNumber);
4978 // Get the fragment view.
4979 View fragmentView = webViewTabFragment.getView();
4981 // Set the current WebView if the fragment view is not null.
4982 if (fragmentView != null) { // The fragment has been populated.
4983 // Store the current WebView.
4984 currentWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4986 // Update the status of swipe to refresh.
4987 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
4988 // Enable the swipe refresh layout if the WebView is scrolled all the way to the top. It is updated every time the scroll changes.
4989 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
4990 } else { // Swipe to refresh is disabled.
4991 // Disable the swipe refresh layout.
4992 swipeRefreshLayout.setEnabled(false);
4995 // Get a handle for the cookie manager.
4996 CookieManager cookieManager = CookieManager.getInstance();
4998 // Set the first-party cookie status.
4999 cookieManager.setAcceptCookie(currentWebView.getAcceptFirstPartyCookies());
5001 // Update the privacy icons. `true` redraws the icons in the app bar.
5002 updatePrivacyIcons(true);
5004 // Get a handle for the input method manager.
5005 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
5007 // Remove the lint warning below that the input method manager might be null.
5008 assert inputMethodManager != null;
5010 // Get the current URL.
5011 String url = currentWebView.getUrl();
5013 // Update the URL edit text if not loading a new intent. Otherwise, this will be handled by `onPageStarted()` (if called) and `onPageFinished()`.
5014 if (!loadingNewIntent) { // A new intent is not being loaded.
5015 if ((url == null) || url.equals("about:blank")) { // The WebView is blank.
5016 // Display the hint in the URL edit text.
5017 urlEditText.setText("");
5019 // Request focus for the URL text box.
5020 urlEditText.requestFocus();
5022 // Display the keyboard.
5023 inputMethodManager.showSoftInput(urlEditText, 0);
5024 } else { // The WebView has a loaded URL.
5025 // Clear the focus from the URL text box.
5026 urlEditText.clearFocus();
5028 // Hide the soft keyboard.
5029 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
5031 // Display the current URL in the URL text box.
5032 urlEditText.setText(url);
5034 // Highlight the URL text.
5037 } else { // A new intent is being loaded.
5038 // Reset the loading new intent tracker.
5039 loadingNewIntent = false;
5042 // Set the background to indicate the domain settings status.
5043 if (currentWebView.getDomainSettingsApplied()) {
5044 // Set a green background on the URL relative layout to indicate that custom domain settings are being used. The deprecated `.getDrawable()` must be used until the minimum API >= 21.
5046 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
5048 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
5051 urlRelativeLayout.setBackground(getResources().getDrawable(R.color.transparent));
5053 } else { // The fragment has not been populated. Try again in 100 milliseconds.
5054 // Create a handler to set the current WebView.
5055 Handler setCurrentWebViewHandler = new Handler();
5057 // Create a runnable to set the current WebView.
5058 Runnable setCurrentWebWebRunnable = () -> {
5059 // Set the current WebView.
5060 setCurrentWebView(pageNumber);
5063 // Try setting the current WebView again after 100 milliseconds.
5064 setCurrentWebViewHandler.postDelayed(setCurrentWebWebRunnable, 100);
5069 public void initializeWebView(NestedScrollWebView nestedScrollWebView, int pageNumber, ProgressBar progressBar, String url) {
5070 // Get handles for the activity views.
5071 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
5072 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
5073 RelativeLayout mainContentRelativeLayout = findViewById(R.id.main_content_relativelayout);
5074 ActionBar actionBar = getSupportActionBar();
5075 LinearLayout tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
5076 EditText urlEditText = findViewById(R.id.url_edittext);
5077 TabLayout tabLayout = findViewById(R.id.tablayout);
5078 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
5080 // Remove the incorrect lint warning below that the action bar might be null.
5081 assert actionBar != null;
5083 // Get a handle for the activity
5084 Activity activity = this;
5086 // Get a handle for the input method manager.
5087 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
5089 // Instantiate the blocklist helper.
5090 BlocklistHelper blocklistHelper = new BlocklistHelper();
5092 // Remove the lint warning below that the input method manager might be null.
5093 assert inputMethodManager != null;
5095 // Get a handle for the shared preferences.
5096 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
5098 // Initialize the favorite icon.
5099 nestedScrollWebView.initializeFavoriteIcon();
5101 // Set the app bar scrolling.
5102 nestedScrollWebView.setNestedScrollingEnabled(sharedPreferences.getBoolean("scroll_app_bar", true));
5104 // Allow pinch to zoom.
5105 nestedScrollWebView.getSettings().setBuiltInZoomControls(true);
5107 // Hide zoom controls.
5108 nestedScrollWebView.getSettings().setDisplayZoomControls(false);
5110 // Don't allow mixed content (HTTP and HTTPS) on the same website.
5111 if (Build.VERSION.SDK_INT >= 21) {
5112 nestedScrollWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);
5115 // Set the WebView to load in overview mode (zoomed out to the maximum width).
5116 nestedScrollWebView.getSettings().setLoadWithOverviewMode(true);
5118 // Explicitly disable geolocation.
5119 nestedScrollWebView.getSettings().setGeolocationEnabled(false);
5121 // Create a double-tap gesture detector to toggle full-screen mode.
5122 GestureDetector doubleTapGestureDetector = new GestureDetector(getApplicationContext(), new GestureDetector.SimpleOnGestureListener() {
5123 // Override `onDoubleTap()`. All other events are handled using the default settings.
5125 public boolean onDoubleTap(MotionEvent event) {
5126 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
5127 // Toggle the full screen browsing mode tracker.
5128 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
5130 // Toggle the full screen browsing mode.
5131 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
5132 // Store the swipe refresh layout top padding.
5133 swipeRefreshLayoutPaddingTop = swipeRefreshLayout.getPaddingTop();
5135 // Hide the app bar if specified.
5137 // Close the find on page bar if it is visible.
5138 closeFindOnPage(null);
5140 // Hide the tab linear layout.
5141 tabsLinearLayout.setVisibility(View.GONE);
5143 // Hide the action bar.
5146 // Check to see if app bar scrolling is disabled.
5147 if (!scrollAppBar) {
5148 // Remove the padding from the top of the swipe refresh layout.
5149 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5153 // Hide the banner ad in the free flavor.
5154 if (BuildConfig.FLAVOR.contentEquals("free")) {
5155 AdHelper.hideAd(findViewById(R.id.adview));
5158 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
5159 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
5161 /* Hide the system bars.
5162 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5163 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5164 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5165 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5167 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5168 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5169 } else { // Switch to normal viewing mode.
5170 // Show the tab linear layout.
5171 tabsLinearLayout.setVisibility(View.VISIBLE);
5173 // Show the action bar.
5176 // Check to see if app bar scrolling is disabled.
5177 if (!scrollAppBar) {
5178 // Add the padding from the top of the swipe refresh layout.
5179 swipeRefreshLayout.setPadding(0, swipeRefreshLayoutPaddingTop, 0, 0);
5182 // Show the banner ad in the free flavor.
5183 if (BuildConfig.FLAVOR.contentEquals("free")) {
5185 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
5188 // Remove the `SYSTEM_UI` flags from the root frame layout.
5189 rootFrameLayout.setSystemUiVisibility(0);
5191 // Add the translucent status flag.
5192 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
5195 // Consume the double-tap.
5197 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
5203 // Pass all touch events on the WebView through the double-tap gesture detector.
5204 nestedScrollWebView.setOnTouchListener((View view, MotionEvent event) -> {
5205 // Call `performClick()` on the view, which is required for accessibility.
5206 view.performClick();
5208 // Send the event to the gesture detector.
5209 return doubleTapGestureDetector.onTouchEvent(event);
5212 // Register the WebView for a context menu. This is used to see link targets and download images.
5213 registerForContextMenu(nestedScrollWebView);
5215 // Allow the downloading of files.
5216 nestedScrollWebView.setDownloadListener((String downloadUrl, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
5217 // Instantiate the save dialog.
5218 DialogFragment saveDialogFragment = SaveDialog.saveUrl(StoragePermissionDialog.SAVE_URL, downloadUrl, userAgent, nestedScrollWebView.getAcceptFirstPartyCookies());
5220 // Show the save dialog. It must be named `save_dialog` so that the file picker can update the file name.
5221 saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
5224 // Update the find on page count.
5225 nestedScrollWebView.setFindListener(new WebView.FindListener() {
5226 // Get a handle for `findOnPageCountTextView`.
5227 final TextView findOnPageCountTextView = findViewById(R.id.find_on_page_count_textview);
5230 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
5231 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
5232 // Set `findOnPageCountTextView` to `0/0`.
5233 findOnPageCountTextView.setText(R.string.zero_of_zero);
5234 } else if (isDoneCounting) { // There are matches.
5235 // `activeMatchOrdinal` is zero-based.
5236 int activeMatch = activeMatchOrdinal + 1;
5238 // Build the match string.
5239 String matchString = activeMatch + "/" + numberOfMatches;
5241 // Set `findOnPageCountTextView`.
5242 findOnPageCountTextView.setText(matchString);
5247 // Update the status of swipe to refresh based on the scroll position of the nested scroll WebView. Also reinforce full screen browsing mode.
5248 // Once the minimum API >= 23 this can be replaced with `nestedScrollWebView.setOnScrollChangeListener()`.
5249 nestedScrollWebView.getViewTreeObserver().addOnScrollChangedListener(() -> {
5250 if (nestedScrollWebView.getSwipeToRefresh()) {
5251 // Only enable swipe to refresh if the WebView is scrolled to the top.
5252 swipeRefreshLayout.setEnabled(nestedScrollWebView.getScrollY() == 0);
5255 // Reinforce the system UI visibility flags if in full screen browsing mode.
5256 // This hides the status and navigation bars, which are displayed if other elements are shown, like dialog boxes, the options menu, or the keyboard.
5257 if (inFullScreenBrowsingMode) {
5258 /* Hide the system bars.
5259 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5260 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5261 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5262 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5264 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5265 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5269 // Set the web chrome client.
5270 nestedScrollWebView.setWebChromeClient(new WebChromeClient() {
5271 // Update the progress bar when a page is loading.
5273 public void onProgressChanged(WebView view, int progress) {
5274 // Inject the night mode CSS if night mode is enabled.
5275 if (nestedScrollWebView.getNightMode()) { // Night mode is enabled.
5276 // `background-color: #212121` sets the background to be dark gray. `color: #BDBDBD` sets the text color to be light gray. `box-shadow: none` removes a lower underline on links
5277 // used by WordPress. `text-decoration: none` removes all text underlines. `text-shadow: none` removes text shadows, which usually have a hard coded color.
5278 // `border: none` removes all borders, which can also be used to underline text. `a {color: #1565C0}` sets links to be a dark blue.
5279 // `::selection {background: #0D47A1}' sets the text selection highlight color to be a dark blue. `!important` takes precedent over any existing sub-settings.
5280 nestedScrollWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
5281 "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
5282 "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;} ::selection {background: #0D47A1 !important;}'; parent.appendChild(style)})()", value -> {
5283 // Initialize a handler to display `mainWebView`.
5284 Handler displayWebViewHandler = new Handler();
5286 // Setup a runnable to display `mainWebView` after a delay to allow the CSS to be applied.
5287 Runnable displayWebViewRunnable = () -> {
5288 // Only display `mainWebView` if the progress bar is gone. This prevents the display of the `WebView` while it is still loading.
5289 if (progressBar.getVisibility() == View.GONE) {
5290 nestedScrollWebView.setVisibility(View.VISIBLE);
5294 // Display the WebView after 500 milliseconds.
5295 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
5297 } else { // Night mode is disabled.
5298 // Display the nested scroll WebView if night mode is disabled.
5299 // Because of a race condition between `applyDomainSettings` and `onPageStarted`,
5300 // when night mode is set by domain settings the WebView may be hidden even if night mode is not currently enabled.
5301 nestedScrollWebView.setVisibility(View.VISIBLE);
5304 // Update the progress bar.
5305 progressBar.setProgress(progress);
5307 // Set the visibility of the progress bar.
5308 if (progress < 100) {
5309 // Show the progress bar.
5310 progressBar.setVisibility(View.VISIBLE);
5312 // Hide the progress bar.
5313 progressBar.setVisibility(View.GONE);
5315 //Stop the swipe to refresh indicator if it is running
5316 swipeRefreshLayout.setRefreshing(false);
5320 // Set the favorite icon when it changes.
5322 public void onReceivedIcon(WebView view, Bitmap icon) {
5323 // Only update the favorite icon if the website has finished loading.
5324 if (progressBar.getVisibility() == View.GONE) {
5325 // Store the new favorite icon.
5326 nestedScrollWebView.setFavoriteOrDefaultIcon(icon);
5328 // Get the current page position.
5329 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5331 // Get the current tab.
5332 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
5334 // Check to see if the tab has been populated.
5336 // Get the custom view from the tab.
5337 View tabView = tab.getCustomView();
5339 // Check to see if the custom tab view has been populated.
5340 if (tabView != null) {
5341 // Get the favorite icon image view from the tab.
5342 ImageView tabFavoriteIconImageView = tabView.findViewById(R.id.favorite_icon_imageview);
5344 // Display the favorite icon in the tab.
5345 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
5351 // Save a copy of the title when it changes.
5353 public void onReceivedTitle(WebView view, String title) {
5354 // Get the current page position.
5355 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5357 // Get the current tab.
5358 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
5360 // Only populate the title text view if the tab has been fully created.
5362 // Get the custom view from the tab.
5363 View tabView = tab.getCustomView();
5365 // Remove the incorrect warning below that the current tab view might be null.
5366 assert tabView != null;
5368 // Get the title text view from the tab.
5369 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
5371 // Set the title according to the URL.
5372 if (title.equals("about:blank")) {
5373 // Set the title to indicate a new tab.
5374 tabTitleTextView.setText(R.string.new_tab);
5376 // Set the title as the tab text.
5377 tabTitleTextView.setText(title);
5382 // Enter full screen video.
5384 public void onShowCustomView(View video, CustomViewCallback callback) {
5385 // Get a handle for the full screen video frame layout.
5386 FrameLayout fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
5388 // Set the full screen video flag.
5389 displayingFullScreenVideo = true;
5391 // Pause the ad if this is the free flavor.
5392 if (BuildConfig.FLAVOR.contentEquals("free")) {
5393 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
5394 AdHelper.pauseAd(findViewById(R.id.adview));
5397 // Hide the keyboard.
5398 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
5400 // Hide the main content relative layout.
5401 mainContentRelativeLayout.setVisibility(View.GONE);
5403 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
5404 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
5406 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
5407 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
5409 /* Hide the system bars.
5410 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5411 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5412 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5413 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5415 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5416 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5418 // Disable the sliding drawers.
5419 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
5421 // Add the video view to the full screen video frame layout.
5422 fullScreenVideoFrameLayout.addView(video);
5424 // Show the full screen video frame layout.
5425 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
5427 // Disable the screen timeout while the video is playing. YouTube does this automatically, but not all other videos do.
5428 fullScreenVideoFrameLayout.setKeepScreenOn(true);
5431 // Exit full screen video.
5433 public void onHideCustomView() {
5434 // Get a handle for the full screen video frame layout.
5435 FrameLayout fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
5437 // Re-enable the screen timeout.
5438 fullScreenVideoFrameLayout.setKeepScreenOn(false);
5440 // Unset the full screen video flag.
5441 displayingFullScreenVideo = false;
5443 // Remove all the views from the full screen video frame layout.
5444 fullScreenVideoFrameLayout.removeAllViews();
5446 // Hide the full screen video frame layout.
5447 fullScreenVideoFrameLayout.setVisibility(View.GONE);
5449 // Enable the sliding drawers.
5450 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
5452 // Show the main content relative layout.
5453 mainContentRelativeLayout.setVisibility(View.VISIBLE);
5455 // Apply the appropriate full screen mode flags.
5456 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
5457 // Hide the app bar if specified.
5459 // Hide the tab linear layout.
5460 tabsLinearLayout.setVisibility(View.GONE);
5462 // Hide the action bar.
5466 // Hide the banner ad in the free flavor.
5467 if (BuildConfig.FLAVOR.contentEquals("free")) {
5468 AdHelper.hideAd(findViewById(R.id.adview));
5471 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
5472 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
5474 /* Hide the system bars.
5475 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5476 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5477 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5478 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5480 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5481 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5482 } else { // Switch to normal viewing mode.
5483 // Remove the `SYSTEM_UI` flags from the root frame layout.
5484 rootFrameLayout.setSystemUiVisibility(0);
5486 // Add the translucent status flag.
5487 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
5490 // Reload the ad for the free flavor if not in full screen mode.
5491 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
5493 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
5499 public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
5500 // Show the file chooser if the device is running API >= 21.
5501 if (Build.VERSION.SDK_INT >= 21) {
5502 // Store the file path callback.
5503 fileChooserCallback = filePathCallback;
5505 // Create an intent to open a chooser based ont the file chooser parameters.
5506 Intent fileChooserIntent = fileChooserParams.createIntent();
5508 // Open the file chooser.
5509 startActivityForResult(fileChooserIntent, BROWSE_FILE_UPLOAD_REQUEST_CODE);
5515 nestedScrollWebView.setWebViewClient(new WebViewClient() {
5516 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
5517 // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
5519 public boolean shouldOverrideUrlLoading(WebView view, String url) {
5520 // Sanitize the url.
5521 url = sanitizeUrl(url);
5523 if (url.startsWith("http")) { // Load the URL in Privacy Browser.
5524 // Apply the domain settings for the new URL. This doesn't do anything if the domain has not changed.
5525 boolean userAgentChanged = applyDomainSettings(nestedScrollWebView, url, true, false);
5527 // Check if the user agent has changed.
5528 if (userAgentChanged) {
5529 // Manually load the URL. The changing of the user agent will cause WebView to reload the previous URL.
5530 nestedScrollWebView.loadUrl(url, customHeaders);
5532 // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
5535 // Returning false causes the current WebView to handle the URL and prevents it from adding redirects to the history list.
5538 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
5539 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
5540 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
5542 // Parse the url and set it as the data for the intent.
5543 emailIntent.setData(Uri.parse(url));
5545 // Open the email program in a new task instead of as part of Privacy Browser.
5546 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5549 startActivity(emailIntent);
5551 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5553 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
5554 // Open the dialer and load the phone number, but wait for the user to place the call.
5555 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
5557 // Add the phone number to the intent.
5558 dialIntent.setData(Uri.parse(url));
5560 // Open the dialer in a new task instead of as part of Privacy Browser.
5561 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5564 startActivity(dialIntent);
5566 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5568 } else { // Load a system chooser to select an app that can handle the URL.
5569 // Open an app that can handle the URL.
5570 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
5572 // Add the URL to the intent.
5573 genericIntent.setData(Uri.parse(url));
5575 // List all apps that can handle the URL instead of just opening the first one.
5576 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
5578 // Open the app in a new task instead of as part of Privacy Browser.
5579 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5581 // Start the app or display a snackbar if no app is available to handle the URL.
5583 startActivity(genericIntent);
5584 } catch (ActivityNotFoundException exception) {
5585 Snackbar.make(nestedScrollWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
5588 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5593 // Check requests against the block lists. The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
5595 public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
5596 // Check to see if the resource request is for the main URL.
5597 if (url.equals(nestedScrollWebView.getCurrentUrl())) {
5598 // `return null` loads the resource request, which should never be blocked if it is the main URL.
5602 // Wait until the blocklists 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.
5603 while (ultraPrivacy == null) {
5604 // The wait must be synchronized, which only lets one thread run on it at a time, or `java.lang.IllegalMonitorStateException` is thrown.
5605 synchronized (this) {
5607 // Check to see if the blocklists have been populated after 100 ms.
5609 } catch (InterruptedException exception) {
5615 // Sanitize the URL.
5616 url = sanitizeUrl(url);
5618 // Get a handle for the navigation view.
5619 NavigationView navigationView = findViewById(R.id.navigationview);
5621 // Get a handle for the navigation menu.
5622 Menu navigationMenu = navigationView.getMenu();
5624 // Get a handle for the navigation requests menu item. The menu is 0 based.
5625 MenuItem navigationRequestsMenuItem = navigationMenu.getItem(6);
5627 // Create an empty web resource response to be used if the resource request is blocked.
5628 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
5630 // Reset the whitelist results tracker.
5631 String[] whitelistResultStringArray = null;
5633 // Initialize the third party request tracker.
5634 boolean isThirdPartyRequest = false;
5636 // Get the current URL. `.getUrl()` throws an error because operations on the WebView cannot be made from this thread.
5637 String currentBaseDomain = nestedScrollWebView.getCurrentDomainName();
5639 // Store a copy of the current domain for use in later requests.
5640 String currentDomain = currentBaseDomain;
5642 // Nobody is happy when comparing null strings.
5643 if ((currentBaseDomain != null) && (url != null)) {
5644 // Convert the request URL to a URI.
5645 Uri requestUri = Uri.parse(url);
5647 // Get the request host name.
5648 String requestBaseDomain = requestUri.getHost();
5650 // Only check for third-party requests if the current base domain is not empty and the request domain is not null.
5651 if (!currentBaseDomain.isEmpty() && (requestBaseDomain != null)) {
5652 // Determine the current base domain.
5653 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5654 // Remove the first subdomain.
5655 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
5658 // Determine the request base domain.
5659 while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5660 // Remove the first subdomain.
5661 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
5664 // Update the third party request tracker.
5665 isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
5669 // Get the current WebView page position.
5670 int webViewPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5672 // Determine if the WebView is currently displayed.
5673 boolean webViewDisplayed = (webViewPagePosition == tabLayout.getSelectedTabPosition());
5675 // Block third-party requests if enabled.
5676 if (isThirdPartyRequest && nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS)) {
5677 // Add the result to the resource requests.
5678 nestedScrollWebView.addResourceRequest(new String[]{BlocklistHelper.REQUEST_THIRD_PARTY, url});
5680 // Increment the blocked requests counters.
5681 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5682 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS);
5684 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5685 if (webViewDisplayed) {
5686 // Updating the UI must be run from the UI thread.
5687 activity.runOnUiThread(() -> {
5688 // Update the menu item titles.
5689 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5691 // Update the options menu if it has been populated.
5692 if (optionsMenu != null) {
5693 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5694 optionsMenu.findItem(R.id.block_all_third_party_requests).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " +
5695 getString(R.string.block_all_third_party_requests));
5700 // Return an empty web resource response.
5701 return emptyWebResourceResponse;
5704 // Check UltraList if it is enabled.
5705 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST)) {
5706 // Check the URL against UltraList.
5707 String[] ultraListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraList);
5709 // Process the UltraList results.
5710 if (ultraListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched UltraLists's blacklist.
5711 // Add the result to the resource requests.
5712 nestedScrollWebView.addResourceRequest(new String[] {ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]});
5714 // Increment the blocked requests counters.
5715 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5716 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRALIST);
5718 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5719 if (webViewDisplayed) {
5720 // Updating the UI must be run from the UI thread.
5721 activity.runOnUiThread(() -> {
5722 // Update the menu item titles.
5723 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5725 // Update the options menu if it has been populated.
5726 if (optionsMenu != null) {
5727 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5728 optionsMenu.findItem(R.id.ultralist).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRALIST) + " - " + getString(R.string.ultralist));
5733 // The resource request was blocked. Return an empty web resource response.
5734 return emptyWebResourceResponse;
5735 } else if (ultraListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched UltraList's whitelist.
5736 // Add a whitelist entry to the resource requests array.
5737 nestedScrollWebView.addResourceRequest(new String[] {ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]});
5739 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
5744 // Check UltraPrivacy if it is enabled.
5745 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY)) {
5746 // Check the URL against UltraPrivacy.
5747 String[] ultraPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraPrivacy);
5749 // Process the UltraPrivacy results.
5750 if (ultraPrivacyResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched UltraPrivacy's blacklist.
5751 // Add the result to the resource requests.
5752 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5753 ultraPrivacyResults[5]});
5755 // Increment the blocked requests counters.
5756 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5757 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRAPRIVACY);
5759 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5760 if (webViewDisplayed) {
5761 // Updating the UI must be run from the UI thread.
5762 activity.runOnUiThread(() -> {
5763 // Update the menu item titles.
5764 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5766 // Update the options menu if it has been populated.
5767 if (optionsMenu != null) {
5768 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5769 optionsMenu.findItem(R.id.ultraprivacy).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRAPRIVACY) + " - " + getString(R.string.ultraprivacy));
5774 // The resource request was blocked. Return an empty web resource response.
5775 return emptyWebResourceResponse;
5776 } else if (ultraPrivacyResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched UltraPrivacy's whitelist.
5777 // Add a whitelist entry to the resource requests array.
5778 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5779 ultraPrivacyResults[5]});
5781 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
5786 // Check EasyList if it is enabled.
5787 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST)) {
5788 // Check the URL against EasyList.
5789 String[] easyListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyList);
5791 // Process the EasyList results.
5792 if (easyListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched EasyList's blacklist.
5793 // Add the result to the resource requests.
5794 nestedScrollWebView.addResourceRequest(new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]});
5796 // Increment the blocked requests counters.
5797 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5798 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASYLIST);
5800 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5801 if (webViewDisplayed) {
5802 // Updating the UI must be run from the UI thread.
5803 activity.runOnUiThread(() -> {
5804 // Update the menu item titles.
5805 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5807 // Update the options menu if it has been populated.
5808 if (optionsMenu != null) {
5809 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5810 optionsMenu.findItem(R.id.easylist).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASYLIST) + " - " + getString(R.string.easylist));
5815 // The resource request was blocked. Return an empty web resource response.
5816 return emptyWebResourceResponse;
5817 } else if (easyListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched EasyList's whitelist.
5818 // Update the whitelist result string array tracker.
5819 whitelistResultStringArray = new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]};
5823 // Check EasyPrivacy if it is enabled.
5824 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY)) {
5825 // Check the URL against EasyPrivacy.
5826 String[] easyPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyPrivacy);
5828 // Process the EasyPrivacy results.
5829 if (easyPrivacyResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched EasyPrivacy's blacklist.
5830 // Add the result to the resource requests.
5831 nestedScrollWebView.addResourceRequest(new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4],
5832 easyPrivacyResults[5]});
5834 // Increment the blocked requests counters.
5835 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5836 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASYPRIVACY);
5838 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5839 if (webViewDisplayed) {
5840 // Updating the UI must be run from the UI thread.
5841 activity.runOnUiThread(() -> {
5842 // Update the menu item titles.
5843 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5845 // Update the options menu if it has been populated.
5846 if (optionsMenu != null) {
5847 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5848 optionsMenu.findItem(R.id.easyprivacy).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASYPRIVACY) + " - " + getString(R.string.easyprivacy));
5853 // The resource request was blocked. Return an empty web resource response.
5854 return emptyWebResourceResponse;
5855 } else if (easyPrivacyResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched EasyPrivacy's whitelist.
5856 // Update the whitelist result string array tracker.
5857 whitelistResultStringArray = new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5]};
5861 // Check Fanboy’s Annoyance List if it is enabled.
5862 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST)) {
5863 // Check the URL against Fanboy's Annoyance List.
5864 String[] fanboysAnnoyanceListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList);
5866 // Process the Fanboy's Annoyance List results.
5867 if (fanboysAnnoyanceListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Annoyance List's blacklist.
5868 // Add the result to the resource requests.
5869 nestedScrollWebView.addResourceRequest(new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5870 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]});
5872 // Increment the blocked requests counters.
5873 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5874 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST);
5876 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5877 if (webViewDisplayed) {
5878 // Updating the UI must be run from the UI thread.
5879 activity.runOnUiThread(() -> {
5880 // Update the menu item titles.
5881 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5883 // Update the options menu if it has been populated.
5884 if (optionsMenu != null) {
5885 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5886 optionsMenu.findItem(R.id.fanboys_annoyance_list).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " +
5887 getString(R.string.fanboys_annoyance_list));
5892 // The resource request was blocked. Return an empty web resource response.
5893 return emptyWebResourceResponse;
5894 } else if (fanboysAnnoyanceListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)){ // The resource request matched Fanboy's Annoyance List's whitelist.
5895 // Update the whitelist result string array tracker.
5896 whitelistResultStringArray = new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5897 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]};
5899 } else if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST)) { // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
5900 // Check the URL against Fanboy's Annoyance List.
5901 String[] fanboysSocialListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysSocialList);
5903 // Process the Fanboy's Social Blocking List results.
5904 if (fanboysSocialListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Social Blocking List's blacklist.
5905 // Add the result to the resource requests.
5906 nestedScrollWebView.addResourceRequest(new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5907 fanboysSocialListResults[4], fanboysSocialListResults[5]});
5909 // Increment the blocked requests counters.
5910 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5911 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST);
5913 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5914 if (webViewDisplayed) {
5915 // Updating the UI must be run from the UI thread.
5916 activity.runOnUiThread(() -> {
5917 // Update the menu item titles.
5918 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5920 // Update the options menu if it has been populated.
5921 if (optionsMenu != null) {
5922 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5923 optionsMenu.findItem(R.id.fanboys_social_blocking_list).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " +
5924 getString(R.string.fanboys_social_blocking_list));
5929 // The resource request was blocked. Return an empty web resource response.
5930 return emptyWebResourceResponse;
5931 } else if (fanboysSocialListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched Fanboy's Social Blocking List's whitelist.
5932 // Update the whitelist result string array tracker.
5933 whitelistResultStringArray = new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5934 fanboysSocialListResults[4], fanboysSocialListResults[5]};
5938 // Add the request to the log because it hasn't been processed by any of the previous checks.
5939 if (whitelistResultStringArray != null) { // The request was processed by a whitelist.
5940 nestedScrollWebView.addResourceRequest(whitelistResultStringArray);
5941 } else { // The request didn't match any blocklist entry. Log it as a default request.
5942 nestedScrollWebView.addResourceRequest(new String[]{BlocklistHelper.REQUEST_DEFAULT, url});
5945 // The resource request has not been blocked. `return null` loads the requested resource.
5949 // Handle HTTP authentication requests.
5951 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
5952 // Store the handler.
5953 nestedScrollWebView.setHttpAuthHandler(handler);
5955 // Instantiate an HTTP authentication dialog.
5956 DialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm, nestedScrollWebView.getWebViewFragmentId());
5958 // Show the HTTP authentication dialog.
5959 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
5963 public void onPageStarted(WebView view, String url, Bitmap favicon) {
5964 // Get the preferences.
5965 boolean scrollAppBar = sharedPreferences.getBoolean("scroll_app_bar", true);
5966 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
5968 // Get a handler for the app bar layout.
5969 AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
5971 // Set the top padding of the swipe refresh layout according to the app bar scrolling preference.
5973 // No padding is needed because it will automatically be placed below the app bar layout due to the scrolling layout behavior.
5974 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5976 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5977 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10, defaultProgressViewEndOffset);
5979 // Get the app bar layout height. This can't be done in `applyAppSettings()` because the app bar is not yet populated.
5980 int appBarHeight = appBarLayout.getHeight();
5982 // The swipe refresh layout must be manually moved below the app bar layout.
5983 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0);
5985 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5986 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight);
5989 // Reset the list of resource requests.
5990 nestedScrollWebView.clearResourceRequests();
5992 // Reset the requests counters.
5993 nestedScrollWebView.resetRequestsCounters();
5995 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
5996 if (nestedScrollWebView.getNightMode()) {
5997 nestedScrollWebView.setVisibility(View.INVISIBLE);
5999 nestedScrollWebView.setVisibility(View.VISIBLE);
6002 // Hide the keyboard.
6003 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
6005 // Get the current page position.
6006 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
6008 // Update the URL text bar if the page is currently selected.
6009 if (tabLayout.getSelectedTabPosition() == currentPagePosition) {
6010 // Clear the focus from the URL edit text.
6011 urlEditText.clearFocus();
6013 // Display the formatted URL text.
6014 urlEditText.setText(url);
6016 // Apply text highlighting to `urlTextBox`.
6020 // Reset the list of host IP addresses.
6021 nestedScrollWebView.clearCurrentIpAddresses();
6023 // Get a URI for the current URL.
6024 Uri currentUri = Uri.parse(url);
6026 // Get the IP addresses for the host.
6027 new GetHostIpAddresses(activity, getSupportFragmentManager(), nestedScrollWebView).execute(currentUri.getHost());
6029 // Replace Refresh with Stop if the options menu has been created. (The first WebView typically begins loading before the menu items are instantiated.)
6030 if (optionsMenu != null) {
6031 // Get a handle for the refresh menu item.
6032 MenuItem refreshMenuItem = optionsMenu.findItem(R.id.refresh);
6035 refreshMenuItem.setTitle(R.string.stop);
6037 // Get the app bar and theme preferences.
6038 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
6040 // If the icon is displayed in the AppBar, set it according to the theme.
6041 if (displayAdditionalAppBarIcons) {
6043 refreshMenuItem.setIcon(R.drawable.close_dark);
6045 refreshMenuItem.setIcon(R.drawable.close_light);
6052 public void onPageFinished(WebView view, String url) {
6053 // Flush any cookies to persistent storage. The cookie manager has become very lazy about flushing cookies in recent versions.
6054 if (nestedScrollWebView.getAcceptFirstPartyCookies() && Build.VERSION.SDK_INT >= 21) {
6055 CookieManager.getInstance().flush();
6058 // Update the Refresh menu item if the options menu has been created.
6059 if (optionsMenu != null) {
6060 // Get a handle for the refresh menu item.
6061 MenuItem refreshMenuItem = optionsMenu.findItem(R.id.refresh);
6063 // Reset the Refresh title.
6064 refreshMenuItem.setTitle(R.string.refresh);
6066 // Get the app bar and theme preferences.
6067 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
6068 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
6070 // If the icon is displayed in the AppBar, reset it according to the theme.
6071 if (displayAdditionalAppBarIcons) {
6073 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
6075 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
6080 // Clear the cache and history if Incognito Mode is enabled.
6081 if (incognitoModeEnabled) {
6082 // Clear the cache. `true` includes disk files.
6083 nestedScrollWebView.clearCache(true);
6085 // Clear the back/forward history.
6086 nestedScrollWebView.clearHistory();
6088 // Manually delete cache folders.
6090 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
6091 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
6092 String privateDataDirectoryString = getApplicationInfo().dataDir;
6094 // Delete the main cache directory.
6095 Runtime.getRuntime().exec("rm -rf " + privateDataDirectoryString + "/cache");
6097 // Delete the secondary `Service Worker` cache directory.
6098 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
6099 Runtime.getRuntime().exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
6100 } catch (IOException e) {
6101 // Do nothing if an error is thrown.
6105 // Get the current page position.
6106 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
6108 // Check the current website information against any pinned domain information if the current IP addresses have been loaded.
6109 if ((nestedScrollWebView.hasPinnedSslCertificate() || nestedScrollWebView.hasPinnedIpAddresses()) && nestedScrollWebView.hasCurrentIpAddresses() &&
6110 !nestedScrollWebView.ignorePinnedDomainInformation()) {
6111 CheckPinnedMismatchHelper.checkPinnedMismatch(getSupportFragmentManager(), nestedScrollWebView);
6114 // 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.
6115 String currentUrl = nestedScrollWebView.getUrl();
6117 // Get the current tab.
6118 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
6120 // Update the URL text bar if the page is currently selected and the user is not currently typing in the URL edit text.
6121 // Crash records show that, in some crazy way, it is possible for the current URL to be blank at this point.
6122 // Probably some sort of race condition when Privacy Browser is being resumed.
6123 if ((tabLayout.getSelectedTabPosition() == currentPagePosition) && !urlEditText.hasFocus() && (currentUrl != null)) {
6124 // Check to see if the URL is `about:blank`.
6125 if (currentUrl.equals("about:blank")) { // The WebView is blank.
6126 // Display the hint in the URL edit text.
6127 urlEditText.setText("");
6129 // Request focus for the URL text box.
6130 urlEditText.requestFocus();
6132 // Display the keyboard.
6133 inputMethodManager.showSoftInput(urlEditText, 0);
6135 // Apply the domain settings. This clears any settings from the previous domain.
6136 applyDomainSettings(nestedScrollWebView, "", true, false);
6138 // Only populate the title text view if the tab has been fully created.
6140 // Get the custom view from the tab.
6141 View tabView = tab.getCustomView();
6143 // Remove the incorrect warning below that the current tab view might be null.
6144 assert tabView != null;
6146 // Get the title text view from the tab.
6147 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
6149 // Set the title as the tab text.
6150 tabTitleTextView.setText(R.string.new_tab);
6152 } else { // The WebView has loaded a webpage.
6153 // Update the URL edit text if it is not currently being edited.
6154 if (!urlEditText.hasFocus()) {
6155 // 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.
6156 String sanitizedUrl = sanitizeUrl(currentUrl);
6158 // Display the final URL. Getting the URL from the WebView instead of using the one provided by `onPageFinished()` makes websites like YouTube function correctly.
6159 urlEditText.setText(sanitizedUrl);
6161 // Apply text highlighting to the URL.
6165 // Only populate the title text view if the tab has been fully created.
6167 // Get the custom view from the tab.
6168 View tabView = tab.getCustomView();
6170 // Remove the incorrect warning below that the current tab view might be null.
6171 assert tabView != null;
6173 // Get the title text view from the tab.
6174 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
6176 // Set the title as the tab text. Sometimes `onReceivedTitle()` is not called, especially when navigating history.
6177 tabTitleTextView.setText(nestedScrollWebView.getTitle());
6183 // Handle SSL Certificate errors.
6185 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
6186 // Get the current website SSL certificate.
6187 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
6189 // Extract the individual pieces of information from the current website SSL certificate.
6190 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
6191 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
6192 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
6193 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
6194 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
6195 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
6196 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
6197 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
6199 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
6200 if (nestedScrollWebView.hasPinnedSslCertificate()) {
6201 // Get the pinned SSL certificate.
6202 ArrayList<Object> pinnedSslCertificateArrayList = nestedScrollWebView.getPinnedSslCertificate();
6204 // Extract the arrays from the array list.
6205 String[] pinnedSslCertificateStringArray = (String[]) pinnedSslCertificateArrayList.get(0);
6206 Date[] pinnedSslCertificateDateArray = (Date[]) pinnedSslCertificateArrayList.get(1);
6208 // Check if the current SSL certificate matches the pinned certificate.
6209 if (currentWebsiteIssuedToCName.equals(pinnedSslCertificateStringArray[0]) && currentWebsiteIssuedToOName.equals(pinnedSslCertificateStringArray[1]) &&
6210 currentWebsiteIssuedToUName.equals(pinnedSslCertificateStringArray[2]) && currentWebsiteIssuedByCName.equals(pinnedSslCertificateStringArray[3]) &&
6211 currentWebsiteIssuedByOName.equals(pinnedSslCertificateStringArray[4]) && currentWebsiteIssuedByUName.equals(pinnedSslCertificateStringArray[5]) &&
6212 currentWebsiteSslStartDate.equals(pinnedSslCertificateDateArray[0]) && currentWebsiteSslEndDate.equals(pinnedSslCertificateDateArray[1])) {
6214 // An SSL certificate is pinned and matches the current domain certificate. Proceed to the website without displaying an error.
6217 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
6218 // Store the SSL error handler.
6219 nestedScrollWebView.setSslErrorHandler(handler);
6221 // Instantiate an SSL certificate error alert dialog.
6222 DialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error, nestedScrollWebView.getWebViewFragmentId());
6224 // Show the SSL certificate error dialog.
6225 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
6230 // Check to see if this is the first page.
6231 if (pageNumber == 0) {
6232 // Set this nested scroll WebView as the current WebView.
6233 currentWebView = nestedScrollWebView;
6235 // Apply the app settings from the shared preferences.
6238 // Initialize the URL to load string.
6239 String urlToLoadString;
6241 // Get the intent that started the app.
6242 Intent launchingIntent = getIntent();
6244 // Get the information from the intent.
6245 String launchingIntentAction = launchingIntent.getAction();
6246 Uri launchingIntentUriData = launchingIntent.getData();
6248 // Parse the launching intent URL.
6249 if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) { // The intent contains a search string.
6250 // Create an encoded URL string.
6251 String encodedUrlString;
6253 // Sanitize the search input and convert it to a search.
6255 encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
6256 } catch (UnsupportedEncodingException exception) {
6257 encodedUrlString = "";
6260 // Store the web search as the URL to load.
6261 urlToLoadString = searchURL + encodedUrlString;
6262 } else if (launchingIntentUriData != null){ // The intent contains a URL.
6264 urlToLoadString = launchingIntentUriData.toString();
6265 } else { // The is no URL in the intent.
6266 // Store the homepage to be loaded.
6267 urlToLoadString = sharedPreferences.getString("homepage", getString(R.string.homepage_default_value));
6270 // Load the website if not waiting for the proxy.
6271 if (waitingForProxy) { // Store the URL to be loaded in the Nested Scroll WebView.
6272 nestedScrollWebView.setWaitingForProxyUrlString(urlToLoadString);
6273 } else { // Load the URL.
6274 loadUrl(nestedScrollWebView, urlToLoadString);
6276 } else { // This is not the first tab.
6277 // Apply the domain settings.
6278 applyDomainSettings(nestedScrollWebView, url, false, false);
6281 nestedScrollWebView.loadUrl(url, customHeaders);
6283 // Set the focus and display the keyboard if the URL is blank.
6284 if (url.equals("")) {
6285 // Request focus for the URL text box.
6286 urlEditText.requestFocus();
6288 // Create a display keyboard handler.
6289 Handler displayKeyboardHandler = new Handler();
6291 // Create a display keyboard runnable.
6292 Runnable displayKeyboardRunnable = () -> {
6293 // Display the keyboard.
6294 inputMethodManager.showSoftInput(urlEditText, 0);
6297 // Display the keyboard after 100 milliseconds, which leaves enough time for the tab to transition.
6298 displayKeyboardHandler.postDelayed(displayKeyboardRunnable, 100);