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.
995 if (menuItem.getTitle().equals(getString(R.string.refresh))) { // The refresh button was pushed.
996 // Reload the current WebView.
997 currentWebView.reload();
998 } else { // The stop button was pushed.
999 // Stop the loading of the WebView.
1000 currentWebView.stopLoading();
1003 // Consume the event.
1006 case R.id.toggle_first_party_cookies:
1007 // Switch the first-party cookie status.
1008 cookieManager.setAcceptCookie(!cookieManager.acceptCookie());
1010 // Store the first-party cookie status.
1011 currentWebView.setAcceptFirstPartyCookies(cookieManager.acceptCookie());
1013 // Update the menu checkbox.
1014 menuItem.setChecked(cookieManager.acceptCookie());
1016 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1017 updatePrivacyIcons(true);
1019 // Display a snackbar.
1020 if (cookieManager.acceptCookie()) { // First-party cookies are enabled.
1021 Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1022 } else if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is still enabled.
1023 Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1024 } else { // Privacy mode.
1025 Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1028 // Reload the current WebView.
1029 currentWebView.reload();
1031 // Consume the event.
1034 case R.id.toggle_third_party_cookies:
1035 if (Build.VERSION.SDK_INT >= 21) {
1036 // Switch the status of thirdPartyCookiesEnabled.
1037 cookieManager.setAcceptThirdPartyCookies(currentWebView, !cookieManager.acceptThirdPartyCookies(currentWebView));
1039 // Update the menu checkbox.
1040 menuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
1042 // Display a snackbar.
1043 if (cookieManager.acceptThirdPartyCookies(currentWebView)) {
1044 Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1046 Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1049 // Reload the current WebView.
1050 currentWebView.reload();
1051 } // Else do nothing because SDK < 21.
1053 // Consume the event.
1056 case R.id.toggle_dom_storage:
1057 // Toggle the status of domStorageEnabled.
1058 currentWebView.getSettings().setDomStorageEnabled(!currentWebView.getSettings().getDomStorageEnabled());
1060 // Update the menu checkbox.
1061 menuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1063 // Update the privacy icon. `true` refreshes the app bar icons.
1064 updatePrivacyIcons(true);
1066 // Display a snackbar.
1067 if (currentWebView.getSettings().getDomStorageEnabled()) {
1068 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1070 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1073 // Reload the current WebView.
1074 currentWebView.reload();
1076 // Consume the event.
1079 // Form data can be removed once the minimum API >= 26.
1080 case R.id.toggle_save_form_data:
1081 // Switch the status of saveFormDataEnabled.
1082 currentWebView.getSettings().setSaveFormData(!currentWebView.getSettings().getSaveFormData());
1084 // Update the menu checkbox.
1085 menuItem.setChecked(currentWebView.getSettings().getSaveFormData());
1087 // Display a snackbar.
1088 if (currentWebView.getSettings().getSaveFormData()) {
1089 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1091 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1094 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1095 updatePrivacyIcons(true);
1097 // Reload the current WebView.
1098 currentWebView.reload();
1100 // Consume the event.
1103 case R.id.clear_cookies:
1104 Snackbar.make(findViewById(R.id.webviewpager), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1105 .setAction(R.string.undo, v -> {
1106 // Do nothing because everything will be handled by `onDismissed()` below.
1108 .addCallback(new Snackbar.Callback() {
1109 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1111 public void onDismissed(Snackbar snackbar, int event) {
1112 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1113 // Delete the cookies, which command varies by SDK.
1114 if (Build.VERSION.SDK_INT < 21) {
1115 cookieManager.removeAllCookie();
1117 cookieManager.removeAllCookies(null);
1124 // Consume the event.
1127 case R.id.clear_dom_storage:
1128 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1129 .setAction(R.string.undo, v -> {
1130 // Do nothing because everything will be handled by `onDismissed()` below.
1132 .addCallback(new Snackbar.Callback() {
1133 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1135 public void onDismissed(Snackbar snackbar, int event) {
1136 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1137 // Delete the DOM Storage.
1138 WebStorage webStorage = WebStorage.getInstance();
1139 webStorage.deleteAllData();
1141 // Initialize a handler to manually delete the DOM storage files and directories.
1142 Handler deleteDomStorageHandler = new Handler();
1144 // Setup a runnable to manually delete the DOM storage files and directories.
1145 Runnable deleteDomStorageRunnable = () -> {
1147 // Get a handle for the runtime.
1148 Runtime runtime = Runtime.getRuntime();
1150 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1151 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1152 String privateDataDirectoryString = getApplicationInfo().dataDir;
1154 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1155 Process deleteLocalStorageProcess = runtime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1157 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1158 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1159 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1160 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1161 Process deleteDatabasesProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1163 // Wait for the processes to finish.
1164 deleteLocalStorageProcess.waitFor();
1165 deleteIndexProcess.waitFor();
1166 deleteQuotaManagerProcess.waitFor();
1167 deleteQuotaManagerJournalProcess.waitFor();
1168 deleteDatabasesProcess.waitFor();
1169 } catch (Exception exception) {
1170 // Do nothing if an error is thrown.
1174 // Manually delete the DOM storage files after 200 milliseconds.
1175 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
1181 // Consume the event.
1184 // Form data can be remove once the minimum API >= 26.
1185 case R.id.clear_form_data:
1186 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1187 .setAction(R.string.undo, v -> {
1188 // Do nothing because everything will be handled by `onDismissed()` below.
1190 .addCallback(new Snackbar.Callback() {
1191 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1193 public void onDismissed(Snackbar snackbar, int event) {
1194 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1195 // Delete the form data.
1196 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1197 mainWebViewDatabase.clearFormData();
1203 // Consume the event.
1207 // Toggle the EasyList status.
1208 currentWebView.enableBlocklist(NestedScrollWebView.EASYLIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
1210 // Update the menu checkbox.
1211 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
1213 // Reload the current WebView.
1214 currentWebView.reload();
1216 // Consume the event.
1219 case R.id.easyprivacy:
1220 // Toggle the EasyPrivacy status.
1221 currentWebView.enableBlocklist(NestedScrollWebView.EASYPRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
1223 // Update the menu checkbox.
1224 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
1226 // Reload the current WebView.
1227 currentWebView.reload();
1229 // Consume the event.
1232 case R.id.fanboys_annoyance_list:
1233 // Toggle Fanboy's Annoyance List status.
1234 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1236 // Update the menu checkbox.
1237 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1239 // Update the staus of Fanboy's Social Blocking List.
1240 MenuItem fanboysSocialBlockingListMenuItem = optionsMenu.findItem(R.id.fanboys_social_blocking_list);
1241 fanboysSocialBlockingListMenuItem.setEnabled(!currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1243 // Reload the current WebView.
1244 currentWebView.reload();
1246 // Consume the event.
1249 case R.id.fanboys_social_blocking_list:
1250 // Toggle Fanboy's Social Blocking List status.
1251 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1253 // Update the menu checkbox.
1254 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1256 // Reload the current WebView.
1257 currentWebView.reload();
1259 // Consume the event.
1262 case R.id.ultralist:
1263 // Toggle the UltraList status.
1264 currentWebView.enableBlocklist(NestedScrollWebView.ULTRALIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
1266 // Update the menu checkbox.
1267 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
1269 // Reload the current WebView.
1270 currentWebView.reload();
1272 // Consume the event.
1275 case R.id.ultraprivacy:
1276 // Toggle the UltraPrivacy status.
1277 currentWebView.enableBlocklist(NestedScrollWebView.ULTRAPRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
1279 // Update the menu checkbox.
1280 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
1282 // Reload the current WebView.
1283 currentWebView.reload();
1285 // Consume the event.
1288 case R.id.block_all_third_party_requests:
1289 //Toggle the third-party requests blocker status.
1290 currentWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, !currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1292 // Update the menu checkbox.
1293 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1295 // Reload the current WebView.
1296 currentWebView.reload();
1298 // Consume the event.
1301 case R.id.proxy_none:
1302 // Update the proxy mode.
1303 proxyMode = ProxyHelper.NONE;
1305 // Apply the proxy mode.
1308 // Consume the event.
1311 case R.id.proxy_tor:
1312 // Update the proxy mode.
1313 proxyMode = ProxyHelper.TOR;
1315 // Apply the proxy mode.
1318 // Consume the event.
1321 case R.id.proxy_i2p:
1322 // Update the proxy mode.
1323 proxyMode = ProxyHelper.I2P;
1325 // Apply the proxy mode.
1328 // Consume the event.
1331 case R.id.proxy_custom:
1332 // Update the proxy mode.
1333 proxyMode = ProxyHelper.CUSTOM;
1335 // Apply the proxy mode.
1338 // Consume the event.
1341 case R.id.user_agent_privacy_browser:
1342 // Update the user agent.
1343 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
1345 // Reload the current WebView.
1346 currentWebView.reload();
1348 // Consume the event.
1351 case R.id.user_agent_webview_default:
1352 // Update the user agent.
1353 currentWebView.getSettings().setUserAgentString("");
1355 // Reload the current WebView.
1356 currentWebView.reload();
1358 // Consume the event.
1361 case R.id.user_agent_firefox_on_android:
1362 // Update the user agent.
1363 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
1365 // Reload the current WebView.
1366 currentWebView.reload();
1368 // Consume the event.
1371 case R.id.user_agent_chrome_on_android:
1372 // Update the user agent.
1373 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
1375 // Reload the current WebView.
1376 currentWebView.reload();
1378 // Consume the event.
1381 case R.id.user_agent_safari_on_ios:
1382 // Update the user agent.
1383 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
1385 // Reload the current WebView.
1386 currentWebView.reload();
1388 // Consume the event.
1391 case R.id.user_agent_firefox_on_linux:
1392 // Update the user agent.
1393 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
1395 // Reload the current WebView.
1396 currentWebView.reload();
1398 // Consume the event.
1401 case R.id.user_agent_chromium_on_linux:
1402 // Update the user agent.
1403 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
1405 // Reload the current WebView.
1406 currentWebView.reload();
1408 // Consume the event.
1411 case R.id.user_agent_firefox_on_windows:
1412 // Update the user agent.
1413 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
1415 // Reload the current WebView.
1416 currentWebView.reload();
1418 // Consume the event.
1421 case R.id.user_agent_chrome_on_windows:
1422 // Update the user agent.
1423 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
1425 // Reload the current WebView.
1426 currentWebView.reload();
1428 // Consume the event.
1431 case R.id.user_agent_edge_on_windows:
1432 // Update the user agent.
1433 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
1435 // Reload the current WebView.
1436 currentWebView.reload();
1438 // Consume the event.
1441 case R.id.user_agent_internet_explorer_on_windows:
1442 // Update the user agent.
1443 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
1445 // Reload the current WebView.
1446 currentWebView.reload();
1448 // Consume the event.
1451 case R.id.user_agent_safari_on_macos:
1452 // Update the user agent.
1453 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
1455 // Reload the current WebView.
1456 currentWebView.reload();
1458 // Consume the event.
1461 case R.id.user_agent_custom:
1462 // Update the user agent.
1463 currentWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
1465 // Reload the current WebView.
1466 currentWebView.reload();
1468 // Consume the event.
1471 case R.id.font_size:
1472 // Instantiate the font size dialog.
1473 DialogFragment fontSizeDialogFragment = FontSizeDialog.displayDialog(currentWebView.getSettings().getTextZoom());
1475 // Show the font size dialog.
1476 fontSizeDialogFragment.show(getSupportFragmentManager(), getString(R.string.font_size));
1478 // Consume the event.
1481 case R.id.swipe_to_refresh:
1482 // Toggle the stored status of swipe to refresh.
1483 currentWebView.setSwipeToRefresh(!currentWebView.getSwipeToRefresh());
1485 // Get a handle for the swipe refresh layout.
1486 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
1488 // Update the swipe refresh layout.
1489 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
1490 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
1491 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
1492 } else { // Swipe to refresh is disabled.
1493 // Disable the swipe refresh layout.
1494 swipeRefreshLayout.setEnabled(false);
1497 // Consume the event.
1500 case R.id.wide_viewport:
1501 // Toggle the viewport.
1502 currentWebView.getSettings().setUseWideViewPort(!currentWebView.getSettings().getUseWideViewPort());
1504 // Consume the event.
1507 case R.id.display_images:
1508 if (currentWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1509 // Disable loading of images.
1510 currentWebView.getSettings().setLoadsImagesAutomatically(false);
1512 // Reload the website to remove existing images.
1513 currentWebView.reload();
1514 } else { // Images are not currently loaded automatically.
1515 // Enable loading of images. Missing images will be loaded without the need for a reload.
1516 currentWebView.getSettings().setLoadsImagesAutomatically(true);
1519 // Consume the event.
1522 case R.id.night_mode:
1523 // Toggle night mode.
1524 currentWebView.setNightMode(!currentWebView.getNightMode());
1526 // Enable or disable JavaScript according to night mode, the global preference, and any domain settings.
1527 if (currentWebView.getNightMode()) { // Night mode is enabled, which requires JavaScript.
1528 // Enable JavaScript.
1529 currentWebView.getSettings().setJavaScriptEnabled(true);
1530 } else if (currentWebView.getDomainSettingsApplied()) { // Night mode is disabled and domain settings are applied. Set JavaScript according to the domain settings.
1531 // Apply the JavaScript preference that was stored the last time domain settings were loaded.
1532 currentWebView.getSettings().setJavaScriptEnabled(currentWebView.getDomainSettingsJavaScriptEnabled());
1533 } else { // Night mode is disabled and domain settings are not applied. Set JavaScript according to the global preference.
1534 // Apply the JavaScript preference.
1535 currentWebView.getSettings().setJavaScriptEnabled(sharedPreferences.getBoolean("javascript", false));
1538 // Update the privacy icons.
1539 updatePrivacyIcons(false);
1541 // Reload the website.
1542 currentWebView.reload();
1544 // Consume the event.
1547 case R.id.find_on_page:
1548 // Get a handle for the views.
1549 Toolbar toolbar = findViewById(R.id.toolbar);
1550 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
1551 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
1553 // Set the minimum height of the find on page linear layout to match the toolbar.
1554 findOnPageLinearLayout.setMinimumHeight(toolbar.getHeight());
1556 // Hide the toolbar.
1557 toolbar.setVisibility(View.GONE);
1559 // Show the find on page linear layout.
1560 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1562 // Display the keyboard. The app must wait 200 ms before running the command to work around a bug in Android.
1563 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1564 findOnPageEditText.postDelayed(() -> {
1565 // Set the focus on `findOnPageEditText`.
1566 findOnPageEditText.requestFocus();
1568 // Get a handle for the input method manager.
1569 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1571 // Remove the lint warning below that the input method manager might be null.
1572 assert inputMethodManager != null;
1574 // Display the keyboard. `0` sets no input flags.
1575 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1578 // Consume the event.
1582 // Get a print manager instance.
1583 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1585 // Remove the lint error below that print manager might be null.
1586 assert printManager != null;
1588 // Create a print document adapter from the current WebView.
1589 PrintDocumentAdapter printDocumentAdapter = currentWebView.createPrintDocumentAdapter();
1591 // Print the document.
1592 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1594 // Consume the event.
1598 // Instantiate the save dialog.
1599 DialogFragment saveDialogFragment = SaveDialog.saveUrl(StoragePermissionDialog.SAVE_URL, currentWebView.getCurrentUrl(), currentWebView.getSettings().getUserAgentString(),
1600 currentWebView.getAcceptFirstPartyCookies());
1602 // Show the save dialog. It must be named `save_dialog` so that the file picked can update the file name.
1603 saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
1605 // Consume the event.
1608 case R.id.save_as_archive:
1609 // Instantiate the save webpage archive dialog.
1610 DialogFragment saveWebpageArchiveDialogFragment = SaveDialog.saveUrl(StoragePermissionDialog.SAVE_AS_ARCHIVE, currentWebView.getCurrentUrl(), currentWebView.getSettings().getUserAgentString(),
1611 currentWebView.getAcceptFirstPartyCookies());
1613 // Show the save webpage archive dialog. It must be named `save_dialog` so that the file picked can update the file name.
1614 saveWebpageArchiveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
1616 // Consume the event.
1619 case R.id.save_as_image:
1620 // Instantiate the save webpage image dialog. It must be named `save_webpage` so that the file picked can update the file name.
1621 DialogFragment saveWebpageImageDialogFragment = SaveDialog.saveUrl(StoragePermissionDialog.SAVE_AS_IMAGE, currentWebView.getCurrentUrl(), currentWebView.getSettings().getUserAgentString(),
1622 currentWebView.getAcceptFirstPartyCookies());
1624 // Show the save webpage image dialog. It must be named `save_dialog` so that the file picked can update the file name.
1625 saveWebpageImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
1627 // Consume the event.
1630 case R.id.add_to_homescreen:
1631 // Instantiate the create home screen shortcut dialog.
1632 DialogFragment createHomeScreenShortcutDialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView.getTitle(), currentWebView.getUrl(),
1633 currentWebView.getFavoriteOrDefaultIcon());
1635 // Show the create home screen shortcut dialog.
1636 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
1638 // Consume the event.
1641 case R.id.view_source:
1642 // Create an intent to launch the view source activity.
1643 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
1645 // Add the variables to the intent.
1646 viewSourceIntent.putExtra("user_agent", currentWebView.getSettings().getUserAgentString());
1647 viewSourceIntent.putExtra("current_url", currentWebView.getUrl());
1650 startActivity(viewSourceIntent);
1652 // Consume the event.
1655 case R.id.share_url:
1656 // Setup the share string.
1657 String shareString = currentWebView.getTitle() + " – " + currentWebView.getUrl();
1659 // Create the share intent.
1660 Intent shareIntent = new Intent(Intent.ACTION_SEND);
1661 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1662 shareIntent.setType("text/plain");
1665 startActivity(Intent.createChooser(shareIntent, getString(R.string.share_url)));
1667 // Consume the event.
1670 case R.id.open_with_app:
1671 // Open the URL with an outside app.
1672 openWithApp(currentWebView.getUrl());
1674 // Consume the event.
1677 case R.id.open_with_browser:
1678 // Open the URL with an outside browser.
1679 openWithBrowser(currentWebView.getUrl());
1681 // Consume the event.
1684 case R.id.add_or_edit_domain:
1685 if (currentWebView.getDomainSettingsApplied()) { // Edit the current domain settings.
1686 // Reapply the domain settings on returning to `MainWebViewActivity`.
1687 reapplyDomainSettingsOnRestart = true;
1689 // Create an intent to launch the domains activity.
1690 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1692 // Add the extra information to the intent.
1693 domainsIntent.putExtra("load_domain", currentWebView.getDomainSettingsDatabaseId());
1694 domainsIntent.putExtra("close_on_back", true);
1695 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1697 // Get the current certificate.
1698 SslCertificate sslCertificate = currentWebView.getCertificate();
1700 // Check to see if the SSL certificate is populated.
1701 if (sslCertificate != null) {
1702 // Extract the certificate to strings.
1703 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1704 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1705 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1706 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1707 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1708 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1709 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1710 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1712 // Add the certificate to the intent.
1713 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1714 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1715 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1716 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1717 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1718 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1719 domainsIntent.putExtra("ssl_start_date", startDateLong);
1720 domainsIntent.putExtra("ssl_end_date", endDateLong);
1723 // Check to see if the current IP addresses have been received.
1724 if (currentWebView.hasCurrentIpAddresses()) {
1725 // Add the current IP addresses to the intent.
1726 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1730 startActivity(domainsIntent);
1731 } else { // Add a new domain.
1732 // Apply the new domain settings on returning to `MainWebViewActivity`.
1733 reapplyDomainSettingsOnRestart = true;
1735 // Get the current domain
1736 Uri currentUri = Uri.parse(currentWebView.getUrl());
1737 String currentDomain = currentUri.getHost();
1739 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1740 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1742 // Create the domain and store the database ID.
1743 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1745 // Create an intent to launch the domains activity.
1746 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1748 // Add the extra information to the intent.
1749 domainsIntent.putExtra("load_domain", newDomainDatabaseId);
1750 domainsIntent.putExtra("close_on_back", true);
1751 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1753 // Get the current certificate.
1754 SslCertificate sslCertificate = currentWebView.getCertificate();
1756 // Check to see if the SSL certificate is populated.
1757 if (sslCertificate != null) {
1758 // Extract the certificate to strings.
1759 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1760 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1761 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1762 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1763 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1764 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1765 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1766 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1768 // Add the certificate to the intent.
1769 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1770 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1771 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1772 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1773 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1774 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1775 domainsIntent.putExtra("ssl_start_date", startDateLong);
1776 domainsIntent.putExtra("ssl_end_date", endDateLong);
1779 // Check to see if the current IP addresses have been received.
1780 if (currentWebView.hasCurrentIpAddresses()) {
1781 // Add the current IP addresses to the intent.
1782 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1786 startActivity(domainsIntent);
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);
1899 startActivity(downloadManagerIntent);
1903 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
1904 reapplyDomainSettingsOnRestart = true;
1906 // Launch the domains activity.
1907 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1909 // Add the extra information to the intent.
1910 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1912 // Get the current certificate.
1913 SslCertificate sslCertificate = currentWebView.getCertificate();
1915 // Check to see if the SSL certificate is populated.
1916 if (sslCertificate != null) {
1917 // Extract the certificate to strings.
1918 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1919 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1920 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1921 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1922 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1923 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1924 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1925 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1927 // Add the certificate to the intent.
1928 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1929 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1930 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1931 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1932 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1933 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1934 domainsIntent.putExtra("ssl_start_date", startDateLong);
1935 domainsIntent.putExtra("ssl_end_date", endDateLong);
1938 // Check to see if the current IP addresses have been received.
1939 if (currentWebView.hasCurrentIpAddresses()) {
1940 // Add the current IP addresses to the intent.
1941 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1945 startActivity(domainsIntent);
1949 // Set the flag to reapply app settings on restart when returning from Settings.
1950 reapplyAppSettingsOnRestart = true;
1952 // Set the flag to reapply the domain settings on restart when returning from Settings.
1953 reapplyDomainSettingsOnRestart = true;
1955 // Launch the settings activity.
1956 Intent settingsIntent = new Intent(this, SettingsActivity.class);
1957 startActivity(settingsIntent);
1960 case R.id.import_export:
1961 // Launch the import/export activity.
1962 Intent importExportIntent = new Intent (this, ImportExportActivity.class);
1963 startActivity(importExportIntent);
1967 // Launch the logcat activity.
1968 Intent logcatIntent = new Intent(this, LogcatActivity.class);
1969 startActivity(logcatIntent);
1973 // Launch `GuideActivity`.
1974 Intent guideIntent = new Intent(this, GuideActivity.class);
1975 startActivity(guideIntent);
1979 // Create an intent to launch the about activity.
1980 Intent aboutIntent = new Intent(this, AboutActivity.class);
1982 // Create a string array for the blocklist versions.
1983 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],
1984 ultraList.get(0).get(0)[0], ultraPrivacy.get(0).get(0)[0]};
1986 // Add the blocklist versions to the intent.
1987 aboutIntent.putExtra("blocklist_versions", blocklistVersions);
1990 startActivity(aboutIntent);
1994 // Get a handle for the drawer layout.
1995 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
1997 // Close the navigation drawer.
1998 drawerLayout.closeDrawer(GravityCompat.START);
2003 public void onPostCreate(Bundle savedInstanceState) {
2004 // Run the default commands.
2005 super.onPostCreate(savedInstanceState);
2007 // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished. This creates the navigation drawer icon.
2008 actionBarDrawerToggle.syncState();
2012 public void onConfigurationChanged(@NonNull Configuration newConfig) {
2013 // Run the default commands.
2014 super.onConfigurationChanged(newConfig);
2016 // Get the status bar pixel size.
2017 int statusBarResourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
2018 int statusBarPixelSize = getResources().getDimensionPixelSize(statusBarResourceId);
2020 // Get the resource density.
2021 float screenDensity = getResources().getDisplayMetrics().density;
2023 // Recalculate the drawer header padding.
2024 drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
2025 drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
2026 drawerHeaderPaddingBottom = (int) (8 * screenDensity);
2028 // Reload the ad for the free flavor if not in full screen mode.
2029 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2030 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2031 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
2034 // `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:
2035 // https://code.google.com/p/android/issues/detail?id=20493#c8
2036 // ActivityCompat.invalidateOptionsMenu(this);
2040 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2041 // Store the hit test result.
2042 final WebView.HitTestResult hitTestResult = currentWebView.getHitTestResult();
2044 // Define the URL strings.
2045 final String imageUrl;
2046 final String linkUrl;
2048 // Get handles for the system managers.
2049 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2051 // Remove the lint errors below that the clipboard manager might be null.
2052 assert clipboardManager != null;
2054 // Process the link according to the type.
2055 switch (hitTestResult.getType()) {
2056 // `SRC_ANCHOR_TYPE` is a link.
2057 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2058 // Get the target URL.
2059 linkUrl = hitTestResult.getExtra();
2061 // Set the target URL as the title of the `ContextMenu`.
2062 menu.setHeaderTitle(linkUrl);
2064 // Add an Open in New Tab entry.
2065 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2066 // Load the link URL in a new tab and move to it.
2067 addNewTab(linkUrl, true);
2069 // Consume the event.
2073 // Add an Open in Background entry.
2074 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2075 // Load the link URL in a new tab but do not move to it.
2076 addNewTab(linkUrl, false);
2078 // Consume the event.
2082 // Add an Open with App entry.
2083 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2084 openWithApp(linkUrl);
2086 // Consume the event.
2090 // Add an Open with Browser entry.
2091 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2092 openWithBrowser(linkUrl);
2094 // Consume the event.
2098 // Add a Copy URL entry.
2099 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2100 // Save the link URL in a `ClipData`.
2101 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2103 // Set the `ClipData` as the clipboard's primary clip.
2104 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2106 // Consume the event.
2110 // Add a Save URL entry.
2111 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2112 // Instantiate the save dialog.
2113 DialogFragment saveDialogFragment = SaveDialog.saveUrl(StoragePermissionDialog.SAVE_URL, linkUrl, currentWebView.getSettings().getUserAgentString(),
2114 currentWebView.getAcceptFirstPartyCookies());
2116 // Show the save dialog. It must be named `save_dialog` so that the file picker can update the file name.
2117 saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
2119 // Consume the event.
2123 // Add a Cancel entry, which by default closes the context menu.
2124 menu.add(R.string.cancel);
2127 case WebView.HitTestResult.EMAIL_TYPE:
2128 // Get the target URL.
2129 linkUrl = hitTestResult.getExtra();
2131 // Set the target URL as the title of the `ContextMenu`.
2132 menu.setHeaderTitle(linkUrl);
2134 // Add a Write Email entry.
2135 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2136 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2137 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2139 // Parse the url and set it as the data for the `Intent`.
2140 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2142 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2143 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2146 startActivity(emailIntent);
2148 // Consume the event.
2152 // Add a Copy Email Address entry.
2153 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2154 // Save the email address in a `ClipData`.
2155 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2157 // Set the `ClipData` as the clipboard's primary clip.
2158 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2160 // Consume the event.
2164 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2165 menu.add(R.string.cancel);
2168 // `IMAGE_TYPE` is an image.
2169 case WebView.HitTestResult.IMAGE_TYPE:
2170 // Get the image URL.
2171 imageUrl = hitTestResult.getExtra();
2173 // Set the image URL as the title of the context menu.
2174 menu.setHeaderTitle(imageUrl);
2176 // Add an Open in New Tab entry.
2177 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2178 // Load the image in a new tab.
2179 addNewTab(imageUrl, true);
2181 // Consume the event.
2185 // Add a View Image entry.
2186 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2187 // Load the image in the current tab.
2188 loadUrl(currentWebView, imageUrl);
2190 // Consume the event.
2194 // Add a Save Image entry.
2195 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2196 // Instantiate the save dialog.
2197 DialogFragment saveDialogFragment = SaveDialog.saveUrl(StoragePermissionDialog.SAVE_URL, imageUrl, currentWebView.getSettings().getUserAgentString(),
2198 currentWebView.getAcceptFirstPartyCookies());
2200 // Show the save dialog. It must be named `save_dialog` so that the file picked can update the file name.
2201 saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
2203 // Consume the event.
2207 // Add a Copy URL entry.
2208 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2209 // Save the image URL in a clip data.
2210 ClipData imageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2212 // Set the clip data as the clipboard's primary clip.
2213 clipboardManager.setPrimaryClip(imageTypeClipData);
2215 // Consume the event.
2219 // Add an Open with App entry.
2220 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2221 // Open the image URL with an external app.
2222 openWithApp(imageUrl);
2224 // Consume the event.
2228 // Add an Open with Browser entry.
2229 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2230 // Open the image URL with an external browser.
2231 openWithBrowser(imageUrl);
2233 // Consume the event.
2237 // Add a Cancel entry, which by default closes the context menu.
2238 menu.add(R.string.cancel);
2241 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2242 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2243 // Get the image URL.
2244 imageUrl = hitTestResult.getExtra();
2246 // Instantiate a handler.
2247 Handler handler = new Handler();
2249 // Get a message from the handler.
2250 Message message = handler.obtainMessage();
2252 // Request the image details from the last touched node be returned in the message.
2253 currentWebView.requestFocusNodeHref(message);
2255 // Get the link URL from the message data.
2256 linkUrl = message.getData().getString("url");
2258 // Set the link URL as the title of the context menu.
2259 menu.setHeaderTitle(linkUrl);
2261 // Add an Open in New Tab entry.
2262 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2263 // Load the link URL in a new tab and move to it.
2264 addNewTab(linkUrl, true);
2266 // Consume the event.
2270 // Add an Open in Background entry.
2271 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2272 // Lod the link URL in a new tab but do not move to it.
2273 addNewTab(linkUrl, false);
2275 // Consume the event.
2279 // Add an Open Image in New Tab entry.
2280 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2281 // Load the image in a new tab and move to it.
2282 addNewTab(imageUrl, true);
2284 // Consume the event.
2288 // Add a View Image entry.
2289 menu.add(R.string.view_image).setOnMenuItemClickListener((MenuItem item) -> {
2290 // View the image in the current tab.
2291 loadUrl(currentWebView, imageUrl);
2293 // Consume the event.
2297 // Add a Copy URL entry.
2298 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2299 // Save the link URL in a clip data.
2300 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2302 // Set the clip data as the clipboard's primary clip.
2303 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2305 // Consume the event.
2309 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2310 // Instantiate the save dialog.
2311 DialogFragment saveDialogFragment = SaveDialog.saveUrl(StoragePermissionDialog.SAVE_URL, imageUrl, currentWebView.getSettings().getUserAgentString(),
2312 currentWebView.getAcceptFirstPartyCookies());
2314 // Show the save raw dialog. It must be named `save_dialog` so that the file picked can update the file name.
2315 saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
2317 // Consume the event.
2321 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2322 // Instantiate the save dialog.
2323 DialogFragment saveDialogFragment = SaveDialog.saveUrl(StoragePermissionDialog.SAVE_URL, linkUrl, currentWebView.getSettings().getUserAgentString(),
2324 currentWebView.getAcceptFirstPartyCookies());
2326 // Show the save raw dialog. It must be named `save_dialog` so that the file picked can update the file name.
2327 saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
2329 // Consume the event.
2333 // Add an Open with App entry.
2334 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2335 // Open the link URL with an external app.
2336 openWithApp(linkUrl);
2338 // Consume the event.
2342 // Add an Open with Browser entry.
2343 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2344 // Open the link URL with an external browser.
2345 openWithBrowser(linkUrl);
2347 // Consume the event.
2351 // Add a cancel entry, which by default closes the context menu.
2352 menu.add(R.string.cancel);
2358 public void onCreateBookmark(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2359 // Get a handle for the bookmarks list view.
2360 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2363 Dialog dialog = dialogFragment.getDialog();
2365 // Remove the incorrect lint warning below that the dialog might be null.
2366 assert dialog != null;
2368 // Get the views from the dialog fragment.
2369 EditText createBookmarkNameEditText = dialog.findViewById(R.id.create_bookmark_name_edittext);
2370 EditText createBookmarkUrlEditText = dialog.findViewById(R.id.create_bookmark_url_edittext);
2372 // Extract the strings from the edit texts.
2373 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2374 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2376 // Create a favorite icon byte array output stream.
2377 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2379 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2380 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2382 // Convert the favorite icon byte array stream to a byte array.
2383 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2385 // Display the new bookmark below the current items in the (0 indexed) list.
2386 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2388 // Create the bookmark.
2389 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2391 // Update the bookmarks cursor with the current contents of this folder.
2392 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2394 // Update the list view.
2395 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2397 // Scroll to the new bookmark.
2398 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2402 public void onCreateBookmarkFolder(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2403 // Get a handle for the bookmarks list view.
2404 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2407 Dialog dialog = dialogFragment.getDialog();
2409 // Remove the incorrect lint warning below that the dialog might be null.
2410 assert dialog != null;
2412 // Get handles for the views in the dialog fragment.
2413 EditText createFolderNameEditText = dialog.findViewById(R.id.create_folder_name_edittext);
2414 RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.create_folder_default_icon_radiobutton);
2415 ImageView folderIconImageView = dialog.findViewById(R.id.create_folder_default_icon);
2417 // Get new folder name string.
2418 String folderNameString = createFolderNameEditText.getText().toString();
2420 // Create a folder icon bitmap.
2421 Bitmap folderIconBitmap;
2423 // Set the folder icon bitmap according to the dialog.
2424 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
2425 // Get the default folder icon drawable.
2426 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2428 // Convert the folder icon drawable to a bitmap drawable.
2429 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2431 // Convert the folder icon bitmap drawable to a bitmap.
2432 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2433 } else { // Use the WebView favorite icon.
2434 // Copy the favorite icon bitmap to the folder icon bitmap.
2435 folderIconBitmap = favoriteIconBitmap;
2438 // Create a folder icon byte array output stream.
2439 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2441 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2442 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2444 // Convert the folder icon byte array stream to a byte array.
2445 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2447 // Move all the bookmarks down one in the display order.
2448 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2449 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2450 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2453 // Create the folder, which will be placed at the top of the `ListView`.
2454 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2456 // Update the bookmarks cursor with the current contents of this folder.
2457 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2459 // Update the `ListView`.
2460 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2462 // Scroll to the new folder.
2463 bookmarksListView.setSelection(0);
2467 public void onSaveBookmark(DialogFragment dialogFragment, int selectedBookmarkDatabaseId, Bitmap favoriteIconBitmap) {
2469 Dialog dialog = dialogFragment.getDialog();
2471 // Remove the incorrect lint warning below that the dialog might be null.
2472 assert dialog != null;
2474 // Get handles for the views from the dialog.
2475 EditText editBookmarkNameEditText = dialog.findViewById(R.id.edit_bookmark_name_edittext);
2476 EditText editBookmarkUrlEditText = dialog.findViewById(R.id.edit_bookmark_url_edittext);
2477 RadioButton currentBookmarkIconRadioButton = dialog.findViewById(R.id.edit_bookmark_current_icon_radiobutton);
2479 // Store the bookmark strings.
2480 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
2481 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
2483 // Update the bookmark.
2484 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
2485 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
2486 } else { // Update the bookmark using the `WebView` favorite icon.
2487 // Create a favorite icon byte array output stream.
2488 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2490 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2491 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
2493 // Convert the favorite icon byte array stream to a byte array.
2494 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
2496 // Update the bookmark and the favorite icon.
2497 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
2500 // Update the bookmarks cursor with the current contents of this folder.
2501 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2503 // Update the list view.
2504 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2508 public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, Bitmap favoriteIconBitmap) {
2510 Dialog dialog = dialogFragment.getDialog();
2512 // Remove the incorrect lint warning below that the dialog might be null.
2513 assert dialog != null;
2515 // Get handles for the views from `dialogFragment`.
2516 EditText editFolderNameEditText = dialog.findViewById(R.id.edit_folder_name_edittext);
2517 RadioButton currentFolderIconRadioButton = dialog.findViewById(R.id.edit_folder_current_icon_radiobutton);
2518 RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.edit_folder_default_icon_radiobutton);
2519 ImageView defaultFolderIconImageView = dialog.findViewById(R.id.edit_folder_default_icon_imageview);
2521 // Get the new folder name.
2522 String newFolderNameString = editFolderNameEditText.getText().toString();
2524 // Check if the favorite icon has changed.
2525 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
2526 // Update the name in the database.
2527 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2528 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
2529 // Create the new folder icon Bitmap.
2530 Bitmap folderIconBitmap;
2532 // Populate the new folder icon bitmap.
2533 if (defaultFolderIconRadioButton.isChecked()) {
2534 // Get the default folder icon drawable.
2535 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2537 // Convert the folder icon drawable to a bitmap drawable.
2538 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2540 // Convert the folder icon bitmap drawable to a bitmap.
2541 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2542 } else { // Use the `WebView` favorite icon.
2543 // Copy the favorite icon bitmap to the folder icon bitmap.
2544 folderIconBitmap = favoriteIconBitmap;
2547 // Create a folder icon byte array output stream.
2548 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2550 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2551 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2553 // Convert the folder icon byte array stream to a byte array.
2554 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2556 // Update the folder icon in the database.
2557 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, newFolderIconByteArray);
2558 } else { // The folder icon and the name have changed.
2559 // Get the new folder icon `Bitmap`.
2560 Bitmap folderIconBitmap;
2561 if (defaultFolderIconRadioButton.isChecked()) {
2562 // Get the default folder icon drawable.
2563 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2565 // Convert the folder icon drawable to a bitmap drawable.
2566 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2568 // Convert the folder icon bitmap drawable to a bitmap.
2569 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2570 } else { // Use the `WebView` favorite icon.
2571 // Copy the favorite icon bitmap to the folder icon bitmap.
2572 folderIconBitmap = favoriteIconBitmap;
2575 // Create a folder icon byte array output stream.
2576 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2578 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2579 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2581 // Convert the folder icon byte array stream to a byte array.
2582 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2584 // Update the folder name and icon in the database.
2585 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, newFolderIconByteArray);
2588 // Update the bookmarks cursor with the current contents of this folder.
2589 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2591 // Update the `ListView`.
2592 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2595 // Override `onBackPressed` to handle the navigation drawer and and the WebViews.
2597 public void onBackPressed() {
2598 // Get a handle for the drawer layout and the tab layout.
2599 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
2600 TabLayout tabLayout = findViewById(R.id.tablayout);
2602 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
2603 // Close the navigation drawer.
2604 drawerLayout.closeDrawer(GravityCompat.START);
2605 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
2606 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
2607 // close the bookmarks drawer.
2608 drawerLayout.closeDrawer(GravityCompat.END);
2609 } else { // A subfolder is displayed.
2610 // Place the former parent folder in `currentFolder`.
2611 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolderName(currentBookmarksFolder);
2613 // Load the new folder.
2614 loadBookmarksFolder();
2616 } else if (displayingFullScreenVideo) { // A full screen video is shown.
2617 // Get a handle for the layouts.
2618 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
2619 RelativeLayout mainContentRelativeLayout = findViewById(R.id.main_content_relativelayout);
2620 FrameLayout fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
2622 // Re-enable the screen timeout.
2623 fullScreenVideoFrameLayout.setKeepScreenOn(false);
2625 // Unset the full screen video flag.
2626 displayingFullScreenVideo = false;
2628 // Remove all the views from the full screen video frame layout.
2629 fullScreenVideoFrameLayout.removeAllViews();
2631 // Hide the full screen video frame layout.
2632 fullScreenVideoFrameLayout.setVisibility(View.GONE);
2634 // Enable the sliding drawers.
2635 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
2637 // Show the main content relative layout.
2638 mainContentRelativeLayout.setVisibility(View.VISIBLE);
2640 // Apply the appropriate full screen mode flags.
2641 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
2642 // Hide the app bar if specified.
2644 // Get handles for the views.
2645 LinearLayout tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
2646 ActionBar actionBar = getSupportActionBar();
2648 // Remove the incorrect lint warning below that the action bar might be null.
2649 assert actionBar != null;
2651 // Hide the tab linear layout.
2652 tabsLinearLayout.setVisibility(View.GONE);
2654 // Hide the action bar.
2658 // Hide the banner ad in the free flavor.
2659 if (BuildConfig.FLAVOR.contentEquals("free")) {
2660 AdHelper.hideAd(findViewById(R.id.adview));
2663 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
2664 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2666 /* Hide the system bars.
2667 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2668 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
2669 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2670 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
2672 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
2673 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
2674 } else { // Switch to normal viewing mode.
2675 // Remove the `SYSTEM_UI` flags from the root frame layout.
2676 rootFrameLayout.setSystemUiVisibility(0);
2678 // Add the translucent status flag.
2679 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2682 // Reload the ad for the free flavor if not in full screen mode.
2683 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2685 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
2687 } else if (currentWebView.canGoBack()) { // There is at least one item in the current WebView history.
2688 // Get the current web back forward list.
2689 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
2691 // Get the previous entry URL.
2692 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
2694 // Apply the domain settings.
2695 applyDomainSettings(currentWebView, previousUrl, false, false);
2698 currentWebView.goBack();
2699 } else if (tabLayout.getTabCount() > 1) { // There are at least two tabs.
2700 // Close the current tab.
2702 } else { // There isn't anything to do in Privacy Browser.
2703 // Close Privacy Browser. `finishAndRemoveTask()` also removes Privacy Browser from the recent app list.
2704 if (Build.VERSION.SDK_INT >= 21) {
2705 finishAndRemoveTask();
2710 // Manually kill Privacy Browser. Otherwise, it is glitchy when restarted.
2715 // Process the results of a file browse.
2717 public void onActivityResult(int requestCode, int resultCode, Intent returnedIntent) {
2718 // Run the default commands.
2719 super.onActivityResult(requestCode, resultCode, returnedIntent);
2721 // Run the commands that correlate to the specified request code.
2722 switch (requestCode) {
2723 case BROWSE_FILE_UPLOAD_REQUEST_CODE:
2724 // File uploads only work on API >= 21.
2725 if (Build.VERSION.SDK_INT >= 21) {
2726 // Pass the file to the WebView.
2727 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, returnedIntent));
2731 case BROWSE_SAVE_WEBPAGE_REQUEST_CODE:
2732 // Don't do anything if the user pressed back from the file picker.
2733 if (resultCode == Activity.RESULT_OK) {
2734 // Get a handle for the save dialog fragment.
2735 DialogFragment saveWebpageDialogFragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.save_dialog));
2737 // Only update the file name if the dialog still exists.
2738 if (saveWebpageDialogFragment != null) {
2739 // Get a handle for the save webpage dialog.
2740 Dialog saveWebpageDialog = saveWebpageDialogFragment.getDialog();
2742 // Remove the incorrect lint warning below that the dialog might be null.
2743 assert saveWebpageDialog != null;
2745 // Get a handle for the file name edit text.
2746 EditText fileNameEditText = saveWebpageDialog.findViewById(R.id.file_name_edittext);
2747 TextView fileExistsWarningTextView = saveWebpageDialog.findViewById(R.id.file_exists_warning_textview);
2749 // Instantiate the file name helper.
2750 FileNameHelper fileNameHelper = new FileNameHelper();
2752 // Get the file path if it isn't null.
2753 if (returnedIntent.getData() != null) {
2754 // Convert the file name URI to a file name path.
2755 String fileNamePath = fileNameHelper.convertUriToFileNamePath(returnedIntent.getData());
2757 // Set the file name path as the text of the file name edit text.
2758 fileNameEditText.setText(fileNamePath);
2760 // Move the cursor to the end of the file name edit text.
2761 fileNameEditText.setSelection(fileNamePath.length());
2763 // Hide the file exists warning.
2764 fileExistsWarningTextView.setVisibility(View.GONE);
2770 case BROWSE_OPEN_REQUEST_CODE:
2771 // Don't do anything if the user pressed back from the file picker.
2772 if (resultCode == Activity.RESULT_OK) {
2773 // Get a handle for the open dialog fragment.
2774 DialogFragment openDialogFragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.open));
2776 // Only update the file name if the dialog still exists.
2777 if (openDialogFragment != null) {
2778 // Get a handle for the open dialog.
2779 Dialog openDialog = openDialogFragment.getDialog();
2781 // Remove the incorrect lint warning below that the dialog might be null.
2782 assert openDialog != null;
2784 // Get a handle for the file name edit text.
2785 EditText fileNameEditText = openDialog.findViewById(R.id.file_name_edittext);
2787 // Instantiate the file name helper.
2788 FileNameHelper fileNameHelper = new FileNameHelper();
2790 // Get the file path if it isn't null.
2791 if (returnedIntent.getData() != null) {
2792 // Convert the file name URI to a file name path.
2793 String fileNamePath = fileNameHelper.convertUriToFileNamePath(returnedIntent.getData());
2795 // Set the file name path as the text of the file name edit text.
2796 fileNameEditText.setText(fileNamePath);
2798 // Move the cursor to the end of the file name edit text.
2799 fileNameEditText.setSelection(fileNamePath.length());
2807 private void loadUrlFromTextBox() {
2808 // Get a handle for the URL edit text.
2809 EditText urlEditText = findViewById(R.id.url_edittext);
2811 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2812 String unformattedUrlString = urlEditText.getText().toString().trim();
2814 // Initialize the formatted URL string.
2817 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
2818 if (unformattedUrlString.startsWith("content://")) { // This is a Content URL.
2819 // Load the entire content URL.
2820 url = unformattedUrlString;
2821 } else if (Patterns.WEB_URL.matcher(unformattedUrlString).matches() || unformattedUrlString.startsWith("http://") || unformattedUrlString.startsWith("https://") ||
2822 unformattedUrlString.startsWith("file://")) { // This is a standard URL.
2823 // Add `https://` at the beginning if there is no protocol. Otherwise the app will segfault.
2824 if (!unformattedUrlString.startsWith("http") && !unformattedUrlString.startsWith("file://") && !unformattedUrlString.startsWith("content://")) {
2825 unformattedUrlString = "https://" + unformattedUrlString;
2828 // Initialize `unformattedUrl`.
2829 URL unformattedUrl = null;
2831 // 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.
2833 unformattedUrl = new URL(unformattedUrlString);
2834 } catch (MalformedURLException e) {
2835 e.printStackTrace();
2838 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2839 String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2840 String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2841 String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2842 String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2843 String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2846 Uri.Builder uri = new Uri.Builder();
2847 uri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2849 // Decode the URI as a UTF-8 string in.
2851 url = URLDecoder.decode(uri.build().toString(), "UTF-8");
2852 } catch (UnsupportedEncodingException exception) {
2853 // Do nothing. The formatted URL string will remain blank.
2855 } else if (!unformattedUrlString.isEmpty()){ // This is not a URL, but rather a search string.
2856 // Create an encoded URL String.
2857 String encodedUrlString;
2859 // Sanitize the search input.
2861 encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2862 } catch (UnsupportedEncodingException exception) {
2863 encodedUrlString = "";
2866 // Add the base search URL.
2867 url = searchURL + encodedUrlString;
2870 // 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.
2871 urlEditText.clearFocus();
2874 loadUrl(currentWebView, url);
2877 private void loadUrl(NestedScrollWebView nestedScrollWebView, String url) {
2878 // Sanitize the URL.
2879 url = sanitizeUrl(url);
2881 // Apply the domain settings.
2882 applyDomainSettings(nestedScrollWebView, url, true, false);
2885 nestedScrollWebView.loadUrl(url, customHeaders);
2888 public void findPreviousOnPage(View view) {
2889 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
2890 currentWebView.findNext(false);
2893 public void findNextOnPage(View view) {
2894 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2895 currentWebView.findNext(true);
2898 public void closeFindOnPage(View view) {
2899 // Get a handle for the views.
2900 Toolbar toolbar = findViewById(R.id.toolbar);
2901 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
2902 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
2904 // Delete the contents of `find_on_page_edittext`.
2905 findOnPageEditText.setText(null);
2907 // Clear the highlighted phrases if the WebView is not null.
2908 if (currentWebView != null) {
2909 currentWebView.clearMatches();
2912 // Hide the find on page linear layout.
2913 findOnPageLinearLayout.setVisibility(View.GONE);
2915 // Show the toolbar.
2916 toolbar.setVisibility(View.VISIBLE);
2918 // Get a handle for the input method manager.
2919 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
2921 // Remove the lint warning below that the input method manager might be null.
2922 assert inputMethodManager != null;
2924 // Hide the keyboard.
2925 inputMethodManager.hideSoftInputFromWindow(toolbar.getWindowToken(), 0);
2929 public void onApplyNewFontSize(DialogFragment dialogFragment) {
2931 Dialog dialog = dialogFragment.getDialog();
2933 // Remove the incorrect lint warning below tha the dialog might be null.
2934 assert dialog != null;
2936 // Get a handle for the font size edit text.
2937 EditText fontSizeEditText = dialog.findViewById(R.id.font_size_edittext);
2939 // Initialize the new font size variable with the current font size.
2940 int newFontSize = currentWebView.getSettings().getTextZoom();
2942 // Get the font size from the edit text.
2944 newFontSize = Integer.parseInt(fontSizeEditText.getText().toString());
2945 } catch (Exception exception) {
2946 // If the edit text does not contain a valid font size do nothing.
2949 // Apply the new font size.
2950 currentWebView.getSettings().setTextZoom(newFontSize);
2954 public void onOpen(DialogFragment dialogFragment) {
2956 Dialog dialog = dialogFragment.getDialog();
2958 // Remove the incorrect lint warning below that the dialog might be null.
2959 assert dialog != null;
2961 // Get a handle for the file name edit text.
2962 EditText fileNameEditText = dialog.findViewById(R.id.file_name_edittext);
2964 // Get the file path string.
2965 openFilePath = fileNameEditText.getText().toString();
2967 // Check to see if the storage permission is needed.
2968 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // The storage permission has been granted.
2970 currentWebView.loadUrl("file://" + openFilePath);
2971 } else { // The storage permission has not been granted.
2972 // Get the external private directory file.
2973 File externalPrivateDirectoryFile = getExternalFilesDir(null);
2975 // Remove the incorrect lint error below that the file might be null.
2976 assert externalPrivateDirectoryFile != null;
2978 // Get the external private directory string.
2979 String externalPrivateDirectory = externalPrivateDirectoryFile.toString();
2981 // Check to see if the file path is in the external private directory.
2982 if (openFilePath.startsWith(externalPrivateDirectory)) { // the file path is in the external private directory.
2984 currentWebView.loadUrl("file://" + openFilePath);
2985 } else { // The file path is in a public directory.
2986 // Check if the user has previously denied the storage permission.
2987 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2988 // Instantiate the storage permission alert dialog.
2989 DialogFragment storagePermissionDialogFragment = StoragePermissionDialog.displayDialog(StoragePermissionDialog.OPEN);
2991 // Show the storage permission alert dialog. The permission will be requested the the dialog is closed.
2992 storagePermissionDialogFragment.show(getSupportFragmentManager(), getString(R.string.storage_permission));
2993 } else { // Show the permission request directly.
2994 // Request the write external storage permission. The file will be opened when it finishes.
2995 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_OPEN_REQUEST_CODE);
3002 public void onSaveWebpage(int saveType, DialogFragment dialogFragment) {
3004 Dialog dialog = dialogFragment.getDialog();
3006 // Remove the incorrect lint warning below that the dialog might be null.
3007 assert dialog != null;
3009 // Get a handle for the edit texts.
3010 EditText urlEditText = dialog.findViewById(R.id.url_edittext);
3011 EditText fileNameEditText = dialog.findViewById(R.id.file_name_edittext);
3013 // Get the strings from the edit texts.
3014 saveWebpageUrl = urlEditText.getText().toString();
3015 saveWebpageFilePath = fileNameEditText.getText().toString();
3017 // Check to see if the storage permission is needed.
3018 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // The storage permission has been granted.
3019 //Save the webpage according to the save type.
3021 case StoragePermissionDialog.SAVE_URL:
3023 new SaveUrl(this, this, saveWebpageFilePath, currentWebView.getSettings().getUserAgentString(), currentWebView.getAcceptFirstPartyCookies()).execute(saveWebpageUrl);
3026 case StoragePermissionDialog.SAVE_AS_ARCHIVE:
3027 // Save the webpage archive.
3028 currentWebView.saveWebArchive(saveWebpageFilePath);
3031 case StoragePermissionDialog.SAVE_AS_IMAGE:
3032 // Save the webpage image.
3033 new SaveWebpageImage(this, currentWebView).execute(saveWebpageFilePath);
3036 } else { // The storage permission has not been granted.
3037 // Get the external private directory file.
3038 File externalPrivateDirectoryFile = getExternalFilesDir(null);
3040 // Remove the incorrect lint error below that the file might be null.
3041 assert externalPrivateDirectoryFile != null;
3043 // Get the external private directory string.
3044 String externalPrivateDirectory = externalPrivateDirectoryFile.toString();
3046 // Check to see if the file path is in the external private directory.
3047 if (saveWebpageFilePath.startsWith(externalPrivateDirectory)) { // The file path is in the external private directory.
3048 // Save the webpage according to the save type.
3050 case StoragePermissionDialog.SAVE_URL:
3052 new SaveUrl(this, this, saveWebpageFilePath, currentWebView.getSettings().getUserAgentString(), currentWebView.getAcceptFirstPartyCookies()).execute(saveWebpageUrl);
3055 case StoragePermissionDialog.SAVE_AS_ARCHIVE:
3056 // Save the webpage archive.
3057 currentWebView.saveWebArchive(saveWebpageFilePath);
3060 case StoragePermissionDialog.SAVE_AS_IMAGE:
3061 // Save the webpage image.
3062 new SaveWebpageImage(this, currentWebView).execute(saveWebpageFilePath);
3065 } else { // The file path is in a public directory.
3066 // Check if the user has previously denied the storage permission.
3067 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
3068 // Instantiate the storage permission alert dialog.
3069 DialogFragment storagePermissionDialogFragment = StoragePermissionDialog.displayDialog(saveType);
3071 // Show the storage permission alert dialog. The permission will be requested when the dialog is closed.
3072 storagePermissionDialogFragment.show(getSupportFragmentManager(), getString(R.string.storage_permission));
3073 } else { // Show the permission request directly.
3075 case StoragePermissionDialog.SAVE_URL:
3076 // Request the write external storage permission. The URL will be saved when it finishes.
3077 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_SAVE_URL_REQUEST_CODE);
3079 case StoragePermissionDialog.SAVE_AS_ARCHIVE:
3080 // Request the write external storage permission. The webpage archive will be saved when it finishes.
3081 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_SAVE_AS_ARCHIVE_REQUEST_CODE);
3084 case StoragePermissionDialog.SAVE_AS_IMAGE:
3085 // Request the write external storage permission. The webpage image will be saved when it finishes.
3086 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_SAVE_AS_IMAGE_REQUEST_CODE);
3095 public void onCloseStoragePermissionDialog(int requestType) {
3096 switch (requestType) {
3097 case StoragePermissionDialog.OPEN:
3098 // Request the write external storage permission. The file will be opened when it finishes.
3099 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_OPEN_REQUEST_CODE);
3102 case StoragePermissionDialog.SAVE_URL:
3103 // Request the write external storage permission. The URL will be saved when it finishes.
3104 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_SAVE_URL_REQUEST_CODE);
3107 case StoragePermissionDialog.SAVE_AS_ARCHIVE:
3108 // Request the write external storage permission. The webpage archive will be saved when it finishes.
3109 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_SAVE_AS_ARCHIVE_REQUEST_CODE);
3112 case StoragePermissionDialog.SAVE_AS_IMAGE:
3113 // Request the write external storage permission. The webpage image will be saved when it finishes.
3114 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_SAVE_AS_IMAGE_REQUEST_CODE);
3120 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
3121 //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).
3122 if (grantResults.length > 0) {
3123 switch (requestCode) {
3124 case PERMISSION_OPEN_REQUEST_CODE:
3125 // Check to see if the storage permission was granted. If the dialog was canceled the grant results will be empty.
3126 if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // The storage permission was granted.
3128 currentWebView.loadUrl("file://" + openFilePath);
3129 } else { // The storage permission was not granted.
3130 // Display an error snackbar.
3131 Snackbar.make(currentWebView, getString(R.string.cannot_use_location), Snackbar.LENGTH_LONG).show();
3134 // Reset the open file path.
3138 case PERMISSION_SAVE_URL_REQUEST_CODE:
3139 // Check to see if the storage permission was granted. If the dialog was canceled the grant results will be empty.
3140 if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // The storage permission was granted.
3141 // Save the raw URL.
3142 new SaveUrl(this, this, saveWebpageFilePath, currentWebView.getSettings().getUserAgentString(), currentWebView.getAcceptFirstPartyCookies()).execute(saveWebpageUrl);
3143 } else { // The storage permission was not granted.
3144 // Display an error snackbar.
3145 Snackbar.make(currentWebView, getString(R.string.cannot_use_location), Snackbar.LENGTH_LONG).show();
3148 // Reset the save strings.
3149 saveWebpageUrl = "";
3150 saveWebpageFilePath = "";
3153 case PERMISSION_SAVE_AS_ARCHIVE_REQUEST_CODE:
3154 // Check to see if the storage permission was granted. If the dialog was canceled the grant results will be empty.
3155 if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // The storage permission was granted.
3156 // Save the webpage archive.
3157 currentWebView.saveWebArchive(saveWebpageFilePath);
3158 } else { // The storage permission was not granted.
3159 // Display an error snackbar.
3160 Snackbar.make(currentWebView, getString(R.string.cannot_use_location), Snackbar.LENGTH_LONG).show();
3163 // Reset the save webpage file path.
3164 saveWebpageFilePath = "";
3167 case PERMISSION_SAVE_AS_IMAGE_REQUEST_CODE:
3168 // Check to see if the storage permission was granted. If the dialog was canceled the grant results will be empty.
3169 if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // The storage permission was granted.
3170 // Save the webpage image.
3171 new SaveWebpageImage(this, currentWebView).execute(saveWebpageFilePath);
3172 } else { // The storage permission was not granted.
3173 // Display an error snackbar.
3174 Snackbar.make(currentWebView, getString(R.string.cannot_use_location), Snackbar.LENGTH_LONG).show();
3177 // Reset the save webpage file path.
3178 saveWebpageFilePath = "";
3184 private void applyAppSettings() {
3185 // 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.
3186 if (webViewDefaultUserAgent == null) {
3190 // Get a handle for the shared preferences.
3191 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3193 // Store the values from the shared preferences in variables.
3194 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3195 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3196 sanitizeGoogleAnalytics = sharedPreferences.getBoolean("google_analytics", true);
3197 sanitizeFacebookClickIds = sharedPreferences.getBoolean("facebook_click_ids", true);
3198 sanitizeTwitterAmpRedirects = sharedPreferences.getBoolean("twitter_amp_redirects", true);
3199 proxyMode = sharedPreferences.getString("proxy", getString(R.string.proxy_default_value));
3200 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3201 hideAppBar = sharedPreferences.getBoolean("hide_app_bar", true);
3202 scrollAppBar = sharedPreferences.getBoolean("scroll_app_bar", true);
3204 // Get the search string.
3205 String searchString = sharedPreferences.getString("search", getString(R.string.search_default_value));
3207 // Set the search string.
3208 if (searchString.equals("Custom URL")) { // A custom search string is used.
3209 searchURL = sharedPreferences.getString("search_custom_url", getString(R.string.search_custom_url_default_value));
3210 } else { // A custom search string is not used.
3211 searchURL = searchString;
3214 // Get handles for the views that need to be modified.
3215 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
3216 AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
3217 ActionBar actionBar = getSupportActionBar();
3218 Toolbar toolbar = findViewById(R.id.toolbar);
3219 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
3220 LinearLayout tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
3221 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
3223 // Remove the incorrect lint warning below that the action bar might be null.
3224 assert actionBar != null;
3229 // Set Do Not Track status.
3230 if (doNotTrackEnabled) {
3231 customHeaders.put("DNT", "1");
3233 customHeaders.remove("DNT");
3236 // Get the current layout parameters. Using coordinator layout parameters allows the `setBehavior()` command and using app bar layout parameters allows the `setScrollFlags()` command.
3237 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
3238 AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) toolbar.getLayoutParams();
3239 AppBarLayout.LayoutParams findOnPageLayoutParams = (AppBarLayout.LayoutParams) findOnPageLinearLayout.getLayoutParams();
3240 AppBarLayout.LayoutParams tabsLayoutParams = (AppBarLayout.LayoutParams) tabsLinearLayout.getLayoutParams();
3242 // Add the scrolling behavior to the layout parameters.
3244 // Enable scrolling of the app bar.
3245 swipeRefreshLayoutParams.setBehavior(new AppBarLayout.ScrollingViewBehavior());
3246 toolbarLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3247 findOnPageLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3248 tabsLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3250 // Disable scrolling of the app bar.
3251 swipeRefreshLayoutParams.setBehavior(null);
3252 toolbarLayoutParams.setScrollFlags(0);
3253 findOnPageLayoutParams.setScrollFlags(0);
3254 tabsLayoutParams.setScrollFlags(0);
3256 // Expand the app bar if it is currently collapsed.
3257 appBarLayout.setExpanded(true);
3260 // Apply the modified layout parameters.
3261 swipeRefreshLayout.setLayoutParams(swipeRefreshLayoutParams);
3262 toolbar.setLayoutParams(toolbarLayoutParams);
3263 findOnPageLinearLayout.setLayoutParams(findOnPageLayoutParams);
3264 tabsLinearLayout.setLayoutParams(tabsLayoutParams);
3266 // Set the app bar scrolling for each WebView.
3267 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3268 // Get the WebView tab fragment.
3269 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3271 // Get the fragment view.
3272 View fragmentView = webViewTabFragment.getView();
3274 // Only modify the WebViews if they exist.
3275 if (fragmentView != null) {
3276 // Get the nested scroll WebView from the tab fragment.
3277 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3279 // Set the app bar scrolling.
3280 nestedScrollWebView.setNestedScrollingEnabled(scrollAppBar);
3284 // Update the full screen browsing mode settings.
3285 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
3286 // Update the visibility of the app bar, which might have changed in the settings.
3288 // Hide the tab linear layout.
3289 tabsLinearLayout.setVisibility(View.GONE);
3291 // Hide the action bar.
3294 // Show the tab linear layout.
3295 tabsLinearLayout.setVisibility(View.VISIBLE);
3297 // Show the action bar.
3301 // Hide the banner ad in the free flavor.
3302 if (BuildConfig.FLAVOR.contentEquals("free")) {
3303 AdHelper.hideAd(findViewById(R.id.adview));
3306 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
3307 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3309 /* Hide the system bars.
3310 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3311 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
3312 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3313 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3315 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
3316 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3317 } else { // Privacy Browser is not in full screen browsing mode.
3318 // 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.
3319 inFullScreenBrowsingMode = false;
3321 // Show the tab linear layout.
3322 tabsLinearLayout.setVisibility(View.VISIBLE);
3324 // Show the action bar.
3327 // Show the banner ad in the free flavor.
3328 if (BuildConfig.FLAVOR.contentEquals("free")) {
3329 // Initialize the ads. If this isn't the first run, `loadAd()` will be automatically called instead.
3330 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getSupportFragmentManager(), getString(R.string.google_app_id), getString(R.string.ad_unit_id));
3333 // Remove the `SYSTEM_UI` flags from the root frame layout.
3334 rootFrameLayout.setSystemUiVisibility(0);
3336 // Add the translucent status flag.
3337 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3341 private void initializeApp() {
3342 // Get a handle for the shared preferences.
3343 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3345 // Get the theme preference.
3346 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
3348 // Get a handle for the input method.
3349 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
3351 // Remove the lint warning below that the input method manager might be null.
3352 assert inputMethodManager != null;
3354 // Initialize the foreground color spans for highlighting the URLs. We have to use the deprecated `getColor()` until API >= 23.
3355 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
3356 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
3357 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
3359 // Get handles for the URL views.
3360 EditText urlEditText = findViewById(R.id.url_edittext);
3362 // Remove the formatting from the URL edit text when the user is editing the text.
3363 urlEditText.setOnFocusChangeListener((View v, boolean hasFocus) -> {
3364 if (hasFocus) { // The user is editing the URL text box.
3365 // Remove the highlighting.
3366 urlEditText.getText().removeSpan(redColorSpan);
3367 urlEditText.getText().removeSpan(initialGrayColorSpan);
3368 urlEditText.getText().removeSpan(finalGrayColorSpan);
3369 } else { // The user has stopped editing the URL text box.
3370 // Move to the beginning of the string.
3371 urlEditText.setSelection(0);
3373 // Reapply the highlighting.
3378 // Set the go button on the keyboard to load the URL in `urlTextBox`.
3379 urlEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
3380 // If the event is a key-down event on the `enter` button, load the URL.
3381 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
3382 // Load the URL into the mainWebView and consume the event.
3383 loadUrlFromTextBox();
3385 // If the enter key was pressed, consume the event.
3388 // If any other key was pressed, do not consume the event.
3393 // Create an Orbot status broadcast receiver.
3394 orbotStatusBroadcastReceiver = new BroadcastReceiver() {
3396 public void onReceive(Context context, Intent intent) {
3397 // Store the content of the status message in `orbotStatus`.
3398 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
3400 // If Privacy Browser is waiting on the proxy, load the website now that Orbot is connected.
3401 if ((orbotStatus != null) && orbotStatus.equals("ON") && waitingForProxy) {
3402 // Reset the waiting for proxy status.
3403 waitingForProxy = false;
3405 // Get a handle for the waiting for proxy dialog.
3406 DialogFragment waitingForProxyDialogFragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.waiting_for_proxy_dialog));
3408 // Dismiss the waiting for proxy dialog if it is displayed.
3409 if (waitingForProxyDialogFragment != null) {
3410 waitingForProxyDialogFragment.dismiss();
3413 // Reload existing URLs and load any URLs that are waiting for the proxy.
3414 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3415 // Get the WebView tab fragment.
3416 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3418 // Get the fragment view.
3419 View fragmentView = webViewTabFragment.getView();
3421 // Only process the WebViews if they exist.
3422 if (fragmentView != null) {
3423 // Get the nested scroll WebView from the tab fragment.
3424 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3426 // Get the waiting for proxy URL string.
3427 String waitingForProxyUrlString = nestedScrollWebView.getWaitingForProxyUrlString();
3429 // Load the pending URL if it exists.
3430 if (!waitingForProxyUrlString.isEmpty()) { // A URL is waiting to be loaded.
3432 loadUrl(nestedScrollWebView, waitingForProxyUrlString);
3434 // Reset the waiting for proxy URL string.
3435 nestedScrollWebView.resetWaitingForProxyUrlString();
3436 } else { // No URL is waiting to be loaded.
3437 // Reload the existing URL.
3438 nestedScrollWebView.reload();
3446 // Register the Orbot status broadcast receiver on `this` context.
3447 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
3449 // Get handles for views that need to be modified.
3450 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
3451 NavigationView navigationView = findViewById(R.id.navigationview);
3452 TabLayout tabLayout = findViewById(R.id.tablayout);
3453 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
3454 ViewPager webViewPager = findViewById(R.id.webviewpager);
3455 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
3456 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
3457 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
3458 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
3459 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
3461 // Listen for touches on the navigation menu.
3462 navigationView.setNavigationItemSelectedListener(this);
3464 // Get handles for the navigation menu and the back and forward menu items. The menu is 0 based.
3465 Menu navigationMenu = navigationView.getMenu();
3466 MenuItem navigationBackMenuItem = navigationMenu.getItem(2);
3467 MenuItem navigationForwardMenuItem = navigationMenu.getItem(3);
3468 MenuItem navigationHistoryMenuItem = navigationMenu.getItem(4);
3469 MenuItem navigationRequestsMenuItem = navigationMenu.getItem(6);
3471 // Update the web view pager every time a tab is modified.
3472 webViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
3474 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
3479 public void onPageSelected(int position) {
3480 // Close the find on page bar if it is open.
3481 closeFindOnPage(null);
3483 // Set the current WebView.
3484 setCurrentWebView(position);
3486 // 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.
3487 if (tabLayout.getSelectedTabPosition() != position) {
3488 // Create a handler to select the tab.
3489 Handler selectTabHandler = new Handler();
3491 // Create a runnable to select the tab.
3492 Runnable selectTabRunnable = () -> {
3493 // Get a handle for the tab.
3494 TabLayout.Tab tab = tabLayout.getTabAt(position);
3496 // Assert that the tab is not null.
3503 // Select the tab layout after 150 milliseconds, which leaves enough time for a new tab to be inflated.
3504 selectTabHandler.postDelayed(selectTabRunnable, 150);
3509 public void onPageScrollStateChanged(int state) {
3514 // Display the View SSL Certificate dialog when the currently selected tab is reselected.
3515 tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
3517 public void onTabSelected(TabLayout.Tab tab) {
3518 // Select the same page in the view pager.
3519 webViewPager.setCurrentItem(tab.getPosition());
3523 public void onTabUnselected(TabLayout.Tab tab) {
3528 public void onTabReselected(TabLayout.Tab tab) {
3529 // Instantiate the View SSL Certificate dialog.
3530 DialogFragment viewSslCertificateDialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView.getWebViewFragmentId());
3532 // Display the View SSL Certificate dialog.
3533 viewSslCertificateDialogFragment.show(getSupportFragmentManager(), getString(R.string.view_ssl_certificate));
3537 // 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.
3538 // The deprecated `getResources().getDrawable()` must be used until the minimum API >= 21 and and `getResources().getColor()` must be used until the minimum API >= 23.
3540 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
3541 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
3542 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
3543 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
3545 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
3546 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
3547 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
3548 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
3551 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
3552 launchBookmarksActivityFab.setOnClickListener(v -> {
3553 // Get a copy of the favorite icon bitmap.
3554 Bitmap favoriteIconBitmap = currentWebView.getFavoriteOrDefaultIcon();
3556 // Create a favorite icon byte array output stream.
3557 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3559 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
3560 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
3562 // Convert the favorite icon byte array stream to a byte array.
3563 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
3565 // Create an intent to launch the bookmarks activity.
3566 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
3568 // Add the extra information to the intent.
3569 bookmarksIntent.putExtra("current_url", currentWebView.getUrl());
3570 bookmarksIntent.putExtra("current_title", currentWebView.getTitle());
3571 bookmarksIntent.putExtra("current_folder", currentBookmarksFolder);
3572 bookmarksIntent.putExtra("favorite_icon_byte_array", favoriteIconByteArray);
3575 startActivity(bookmarksIntent);
3578 // Set the create new bookmark folder FAB to display an alert dialog.
3579 createBookmarkFolderFab.setOnClickListener(v -> {
3580 // Create a create bookmark folder dialog.
3581 DialogFragment createBookmarkFolderDialog = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView.getFavoriteOrDefaultIcon());
3583 // Show the create bookmark folder dialog.
3584 createBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.create_folder));
3587 // Set the create new bookmark FAB to display an alert dialog.
3588 createBookmarkFab.setOnClickListener(view -> {
3589 // Instantiate the create bookmark dialog.
3590 DialogFragment createBookmarkDialog = CreateBookmarkDialog.createBookmark(currentWebView.getUrl(), currentWebView.getTitle(), currentWebView.getFavoriteOrDefaultIcon());
3592 // Display the create bookmark dialog.
3593 createBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.create_bookmark));
3596 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
3597 findOnPageEditText.addTextChangedListener(new TextWatcher() {
3599 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
3604 public void onTextChanged(CharSequence s, int start, int before, int count) {
3609 public void afterTextChanged(Editable s) {
3610 // 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.
3611 if (currentWebView != null) {
3612 currentWebView.findAllAsync(findOnPageEditText.getText().toString());
3617 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
3618 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
3619 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
3620 // Hide the soft keyboard.
3621 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3623 // Consume the event.
3625 } else { // A different key was pressed.
3626 // Do not consume the event.
3631 // Implement swipe to refresh.
3632 swipeRefreshLayout.setOnRefreshListener(() -> currentWebView.reload());
3634 // Store the default progress view offsets for use later in `initializeWebView()`.
3635 defaultProgressViewStartOffset = swipeRefreshLayout.getProgressViewStartOffset();
3636 defaultProgressViewEndOffset = swipeRefreshLayout.getProgressViewEndOffset();
3638 // Set the swipe to refresh color according to the theme.
3640 swipeRefreshLayout.setColorSchemeResources(R.color.blue_800);
3641 swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.gray_850);
3643 swipeRefreshLayout.setColorSchemeResources(R.color.blue_500);
3646 // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
3647 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
3648 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
3650 // Initialize the bookmarks database helper. The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
3651 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
3653 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
3654 currentBookmarksFolder = "";
3656 // Load the home folder, which is `""` in the database.
3657 loadBookmarksFolder();
3659 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
3660 // Convert the id from long to int to match the format of the bookmarks database.
3661 int databaseId = (int) id;
3663 // Get the bookmark cursor for this ID.
3664 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseId);
3666 // Move the bookmark cursor to the first row.
3667 bookmarkCursor.moveToFirst();
3669 // Act upon the bookmark according to the type.
3670 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
3671 // Store the new folder name in `currentBookmarksFolder`.
3672 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3674 // Load the new folder.
3675 loadBookmarksFolder();
3676 } else { // The selected bookmark is not a folder.
3677 // Load the bookmark URL.
3678 loadUrl(currentWebView, bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
3680 // Close the bookmarks drawer.
3681 drawerLayout.closeDrawer(GravityCompat.END);
3684 // Close the `Cursor`.
3685 bookmarkCursor.close();
3688 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
3689 // Convert the database ID from `long` to `int`.
3690 int databaseId = (int) id;
3692 // Find out if the selected bookmark is a folder.
3693 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
3696 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
3697 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3699 // Instantiate the edit folder bookmark dialog.
3700 DialogFragment editBookmarkFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
3702 // Show the edit folder bookmark dialog.
3703 editBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.edit_folder));
3705 // Get the bookmark cursor for this ID.
3706 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseId);
3708 // Move the bookmark cursor to the first row.
3709 bookmarkCursor.moveToFirst();
3711 // Load the bookmark in a new tab but do not switch to the tab or close the drawer.
3712 addNewTab(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)), false);
3715 // Consume the event.
3719 // Get the status bar pixel size.
3720 int statusBarResourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
3721 int statusBarPixelSize = getResources().getDimensionPixelSize(statusBarResourceId);
3723 // Get the resource density.
3724 float screenDensity = getResources().getDisplayMetrics().density;
3726 // Calculate the drawer header padding. This is used to move the text in the drawer headers below any cutouts.
3727 drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
3728 drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
3729 drawerHeaderPaddingBottom = (int) (8 * screenDensity);
3731 // The drawer listener is used to update the navigation menu.
3732 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
3734 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
3738 public void onDrawerOpened(@NonNull View drawerView) {
3742 public void onDrawerClosed(@NonNull View drawerView) {
3746 public void onDrawerStateChanged(int newState) {
3747 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // A drawer is opening or closing.
3748 // Get handles for the drawer headers.
3749 TextView navigationHeaderTextView = findViewById(R.id.navigationText);
3750 TextView bookmarksHeaderTextView = findViewById(R.id.bookmarks_title_textview);
3752 // 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.
3753 if (navigationHeaderTextView != null) {
3754 navigationHeaderTextView.setPadding(drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingTop, drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingBottom);
3757 // 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.
3758 if (bookmarksHeaderTextView != null) {
3759 bookmarksHeaderTextView.setPadding(drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingTop, drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingBottom);
3762 // Update the navigation menu items if the WebView is not null.
3763 if (currentWebView != null) {
3764 navigationBackMenuItem.setEnabled(currentWebView.canGoBack());
3765 navigationForwardMenuItem.setEnabled(currentWebView.canGoForward());
3766 navigationHistoryMenuItem.setEnabled((currentWebView.canGoBack() || currentWebView.canGoForward()));
3767 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
3769 // Hide the keyboard (if displayed).
3770 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3773 // 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.
3774 urlEditText.clearFocus();
3775 currentWebView.clearFocus();
3780 // 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).
3781 customHeaders.put("X-Requested-With", "");
3783 // Inflate a bare WebView to get the default user agent. It is not used to render content on the screen.
3784 @SuppressLint("InflateParams") View webViewLayout = getLayoutInflater().inflate(R.layout.bare_webview, null, false);
3786 // Get a handle for the WebView.
3787 WebView bareWebView = webViewLayout.findViewById(R.id.bare_webview);
3789 // Store the default user agent.
3790 webViewDefaultUserAgent = bareWebView.getSettings().getUserAgentString();
3792 // Destroy the bare WebView.
3793 bareWebView.destroy();
3797 public void navigateHistory(String url, int steps) {
3798 // Apply the domain settings.
3799 applyDomainSettings(currentWebView, url, false, false);
3801 // Load the history entry.
3802 currentWebView.goBackOrForward(steps);
3806 public void pinnedErrorGoBack() {
3807 // Get the current web back forward list.
3808 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
3810 // Get the previous entry URL.
3811 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
3813 // Apply the domain settings.
3814 applyDomainSettings(currentWebView, previousUrl, false, false);
3817 currentWebView.goBack();
3820 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
3821 @SuppressLint("SetJavaScriptEnabled")
3822 private boolean applyDomainSettings(NestedScrollWebView nestedScrollWebView, String url, boolean resetTab, boolean reloadWebsite) {
3823 // Store a copy of the current user agent to track changes for the return boolean.
3824 String initialUserAgent = nestedScrollWebView.getSettings().getUserAgentString();
3826 // Store the current URL.
3827 nestedScrollWebView.setCurrentUrl(url);
3829 // Parse the URL into a URI.
3830 Uri uri = Uri.parse(url);
3832 // Extract the domain from `uri`.
3833 String newHostName = uri.getHost();
3835 // Strings don't like to be null.
3836 if (newHostName == null) {
3840 // 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.
3841 if (!nestedScrollWebView.getCurrentDomainName().equals(newHostName) || newHostName.equals("")) {
3842 // Set the new host name as the current domain name.
3843 nestedScrollWebView.setCurrentDomainName(newHostName);
3845 // Reset the ignoring of pinned domain information.
3846 nestedScrollWebView.setIgnorePinnedDomainInformation(false);
3848 // Clear any pinned SSL certificate or IP addresses.
3849 nestedScrollWebView.clearPinnedSslCertificate();
3850 nestedScrollWebView.clearPinnedIpAddresses();
3852 // Reset the favorite icon if specified.
3854 // Initialize the favorite icon.
3855 nestedScrollWebView.initializeFavoriteIcon();
3857 // Get the current page position.
3858 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
3860 // Get a handle for the tab layout.
3861 TabLayout tabLayout = findViewById(R.id.tablayout);
3863 // Get the corresponding tab.
3864 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
3866 // Update the tab if it isn't null, which sometimes happens when restarting from the background.
3868 // Get the tab custom view.
3869 View tabCustomView = tab.getCustomView();
3871 // Remove the warning below that the tab custom view might be null.
3872 assert tabCustomView != null;
3874 // Get the tab views.
3875 ImageView tabFavoriteIconImageView = tabCustomView.findViewById(R.id.favorite_icon_imageview);
3876 TextView tabTitleTextView = tabCustomView.findViewById(R.id.title_textview);
3878 // Set the default favorite icon as the favorite icon for this tab.
3879 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nestedScrollWebView.getFavoriteOrDefaultIcon(), 64, 64, true));
3881 // Set the loading title text.
3882 tabTitleTextView.setText(R.string.loading);
3886 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3887 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3889 // Get a full cursor from `domainsDatabaseHelper`.
3890 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3892 // Initialize `domainSettingsSet`.
3893 Set<String> domainSettingsSet = new HashSet<>();
3895 // Get the domain name column index.
3896 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3898 // Populate `domainSettingsSet`.
3899 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3900 // Move `domainsCursor` to the current row.
3901 domainNameCursor.moveToPosition(i);
3903 // Store the domain name in `domainSettingsSet`.
3904 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3907 // Close `domainNameCursor.
3908 domainNameCursor.close();
3910 // Initialize the domain name in database variable.
3911 String domainNameInDatabase = null;
3913 // Check the hostname against the domain settings set.
3914 if (domainSettingsSet.contains(newHostName)) { // The hostname is contained in the domain settings set.
3915 // Record the domain name in the database.
3916 domainNameInDatabase = newHostName;
3918 // Set the domain settings applied tracker to true.
3919 nestedScrollWebView.setDomainSettingsApplied(true);
3920 } else { // The hostname is not contained in the domain settings set.
3921 // Set the domain settings applied tracker to false.
3922 nestedScrollWebView.setDomainSettingsApplied(false);
3925 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3926 while (!nestedScrollWebView.getDomainSettingsApplied() && newHostName.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the host name.
3927 if (domainSettingsSet.contains("*." + newHostName)) { // Check the host name prepended by `*.`.
3928 // Set the domain settings applied tracker to true.
3929 nestedScrollWebView.setDomainSettingsApplied(true);
3931 // Store the applied domain names as it appears in the database.
3932 domainNameInDatabase = "*." + newHostName;
3935 // Strip out the lowest subdomain of of the host name.
3936 newHostName = newHostName.substring(newHostName.indexOf(".") + 1);
3940 // Get a handle for the shared preferences.
3941 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3943 // Store the general preference information.
3944 String defaultFontSizeString = sharedPreferences.getString("font_size", getString(R.string.font_size_default_value));
3945 String defaultUserAgentName = sharedPreferences.getString("user_agent", getString(R.string.user_agent_default_value));
3946 boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
3947 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
3948 boolean wideViewport = sharedPreferences.getBoolean("wide_viewport", true);
3949 boolean displayWebpageImages = sharedPreferences.getBoolean("display_webpage_images", true);
3951 // Get a handle for the cookie manager.
3952 CookieManager cookieManager = CookieManager.getInstance();
3954 // Get handles for the views.
3955 RelativeLayout urlRelativeLayout = findViewById(R.id.url_relativelayout);
3956 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
3958 // Initialize the user agent array adapter and string array.
3959 ArrayAdapter<CharSequence> userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item);
3960 String[] userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
3962 if (nestedScrollWebView.getDomainSettingsApplied()) { // The url has custom domain settings.
3963 // Get a cursor for the current host and move it to the first position.
3964 Cursor currentDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3965 currentDomainSettingsCursor.moveToFirst();
3967 // Get the settings from the cursor.
3968 nestedScrollWebView.setDomainSettingsDatabaseId(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3969 nestedScrollWebView.setDomainSettingsJavaScriptEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3970 nestedScrollWebView.setAcceptFirstPartyCookies(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3971 boolean domainThirdPartyCookiesEnabled = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3972 nestedScrollWebView.getSettings().setDomStorageEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3973 // Form data can be removed once the minimum API >= 26.
3974 boolean saveFormData = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3975 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASYLIST,
3976 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3977 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASYPRIVACY,
3978 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3979 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST,
3980 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3981 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST,
3982 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3983 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRALIST, currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ULTRALIST)) == 1);
3984 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRAPRIVACY,
3985 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1);
3986 nestedScrollWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS,
3987 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
3988 String userAgentName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3989 int fontSize = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3990 int swipeToRefreshInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
3991 int nightModeInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
3992 int wideViewportInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.WIDE_VIEWPORT));
3993 int displayWebpageImagesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3994 boolean pinnedSslCertificate = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3995 String pinnedSslIssuedToCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3996 String pinnedSslIssuedToOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3997 String pinnedSslIssuedToUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3998 String pinnedSslIssuedByCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3999 String pinnedSslIssuedByOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
4000 String pinnedSslIssuedByUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
4001 boolean pinnedIpAddresses = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_IP_ADDRESSES)) == 1);
4002 String pinnedHostIpAddresses = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.IP_ADDRESSES));
4004 // Create the pinned SSL date variables.
4005 Date pinnedSslStartDate;
4006 Date pinnedSslEndDate;
4008 // 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.
4009 if (currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
4010 pinnedSslStartDate = null;
4012 pinnedSslStartDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
4015 // 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.
4016 if (currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
4017 pinnedSslEndDate = null;
4019 pinnedSslEndDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
4022 // If there is a pinned SSL certificate, store it in the WebView.
4023 if (pinnedSslCertificate) {
4024 nestedScrollWebView.setPinnedSslCertificate(pinnedSslIssuedToCName, pinnedSslIssuedToOName, pinnedSslIssuedToUName, pinnedSslIssuedByCName, pinnedSslIssuedByOName, pinnedSslIssuedByUName,
4025 pinnedSslStartDate, pinnedSslEndDate);
4028 // If there is a pinned IP address, store it in the WebView.
4029 if (pinnedIpAddresses) {
4030 nestedScrollWebView.setPinnedIpAddresses(pinnedHostIpAddresses);
4033 // Set night mode according to the night mode int.
4034 switch (nightModeInt) {
4035 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4036 // Set night mode according to the current default.
4037 nestedScrollWebView.setNightMode(sharedPreferences.getBoolean("night_mode", false));
4040 case DomainsDatabaseHelper.ENABLED:
4041 // Enable night mode.
4042 nestedScrollWebView.setNightMode(true);
4045 case DomainsDatabaseHelper.DISABLED:
4046 // Disable night mode.
4047 nestedScrollWebView.setNightMode(false);
4051 // Enable JavaScript if night mode is enabled.
4052 if (nestedScrollWebView.getNightMode()) {
4053 // Enable JavaScript.
4054 nestedScrollWebView.getSettings().setJavaScriptEnabled(true);
4056 // Set JavaScript according to the domain settings.
4057 nestedScrollWebView.getSettings().setJavaScriptEnabled(nestedScrollWebView.getDomainSettingsJavaScriptEnabled());
4060 // Close the current host domain settings cursor.
4061 currentDomainSettingsCursor.close();
4063 // Apply the domain settings.
4064 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptFirstPartyCookies());
4066 // Set third-party cookies status if API >= 21.
4067 if (Build.VERSION.SDK_INT >= 21) {
4068 cookieManager.setAcceptThirdPartyCookies(nestedScrollWebView, domainThirdPartyCookiesEnabled);
4071 // Apply the form data setting if the API < 26.
4072 if (Build.VERSION.SDK_INT < 26) {
4073 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
4076 // Apply the font size.
4077 try { // Try the specified font size to see if it is valid.
4078 if (fontSize == 0) { // Apply the default font size.
4079 // Try to set the font size from the value in the app settings.
4080 nestedScrollWebView.getSettings().setTextZoom(Integer.parseInt(defaultFontSizeString));
4081 } else { // Apply the font size from domain settings.
4082 nestedScrollWebView.getSettings().setTextZoom(fontSize);
4084 } catch (Exception exception) { // The specified font size is invalid
4085 // Set the font size to be 100%
4086 nestedScrollWebView.getSettings().setTextZoom(100);
4089 // Set the user agent.
4090 if (userAgentName.equals(getString(R.string.system_default_user_agent))) { // Use the system default user agent.
4091 // Get the array position of the default user agent name.
4092 int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4094 // Set the user agent according to the system default.
4095 switch (defaultUserAgentArrayPosition) {
4096 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
4097 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4098 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
4101 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4102 // Set the user agent to `""`, which uses the default value.
4103 nestedScrollWebView.getSettings().setUserAgentString("");
4106 case SETTINGS_CUSTOM_USER_AGENT:
4107 // Set the default custom user agent.
4108 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
4112 // Get the user agent string from the user agent data array
4113 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
4115 } else { // Set the user agent according to the stored name.
4116 // Get the array position of the user agent name.
4117 int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
4119 switch (userAgentArrayPosition) {
4120 case UNRECOGNIZED_USER_AGENT: // The user agent name contains a custom user agent.
4121 nestedScrollWebView.getSettings().setUserAgentString(userAgentName);
4124 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4125 // Set the user agent to `""`, which uses the default value.
4126 nestedScrollWebView.getSettings().setUserAgentString("");
4130 // Get the user agent string from the user agent data array.
4131 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4135 // Set swipe to refresh.
4136 switch (swipeToRefreshInt) {
4137 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4138 // Store the swipe to refresh status in the nested scroll WebView.
4139 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
4141 // 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.
4142 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
4145 case DomainsDatabaseHelper.ENABLED:
4146 // Store the swipe to refresh status in the nested scroll WebView.
4147 nestedScrollWebView.setSwipeToRefresh(true);
4149 // Enable swipe to refresh. This can be removed once the minimum API >= 23 because it is continuously set by an on scroll change listener.
4150 swipeRefreshLayout.setEnabled(true);
4153 case DomainsDatabaseHelper.DISABLED:
4154 // Store the swipe to refresh status in the nested scroll WebView.
4155 nestedScrollWebView.setSwipeToRefresh(false);
4157 // Disable swipe to refresh. This can be removed once the minimum API >= 23 because it is continuously set by an on scroll change listener.
4158 swipeRefreshLayout.setEnabled(false);
4161 // Set the viewport.
4162 switch (wideViewportInt) {
4163 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4164 nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
4167 case DomainsDatabaseHelper.ENABLED:
4168 nestedScrollWebView.getSettings().setUseWideViewPort(true);
4171 case DomainsDatabaseHelper.DISABLED:
4172 nestedScrollWebView.getSettings().setUseWideViewPort(false);
4176 // Set the loading of webpage images.
4177 switch (displayWebpageImagesInt) {
4178 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4179 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4182 case DomainsDatabaseHelper.ENABLED:
4183 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(true);
4186 case DomainsDatabaseHelper.DISABLED:
4187 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(false);
4191 // 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.
4193 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
4195 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
4197 } else { // The new URL does not have custom domain settings. Load the defaults.
4198 // Store the values from the shared preferences.
4199 boolean defaultJavaScriptEnabled = sharedPreferences.getBoolean("javascript", false);
4200 nestedScrollWebView.setAcceptFirstPartyCookies(sharedPreferences.getBoolean("first_party_cookies", false));
4201 boolean defaultThirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies", false);
4202 nestedScrollWebView.getSettings().setDomStorageEnabled(sharedPreferences.getBoolean("dom_storage", false));
4203 boolean saveFormData = sharedPreferences.getBoolean("save_form_data", false); // Form data can be removed once the minimum API >= 26.
4204 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASYLIST, sharedPreferences.getBoolean("easylist", true));
4205 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASYPRIVACY, sharedPreferences.getBoolean("easyprivacy", true));
4206 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, sharedPreferences.getBoolean("fanboys_annoyance_list", true));
4207 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, sharedPreferences.getBoolean("fanboys_social_blocking_list", true));
4208 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRALIST, sharedPreferences.getBoolean("ultralist", true));
4209 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRAPRIVACY, sharedPreferences.getBoolean("ultraprivacy", true));
4210 nestedScrollWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, sharedPreferences.getBoolean("block_all_third_party_requests", false));
4211 nestedScrollWebView.setNightMode(sharedPreferences.getBoolean("night_mode", false));
4213 // Enable JavaScript if night mode is enabled.
4214 if (nestedScrollWebView.getNightMode()) {
4215 // Enable JavaScript.
4216 nestedScrollWebView.getSettings().setJavaScriptEnabled(true);
4218 // Set JavaScript according to the domain settings.
4219 nestedScrollWebView.getSettings().setJavaScriptEnabled(defaultJavaScriptEnabled);
4222 // Apply the default first-party cookie setting.
4223 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptFirstPartyCookies());
4225 // Apply the default font size setting.
4227 // Try to set the font size from the value in the app settings.
4228 nestedScrollWebView.getSettings().setTextZoom(Integer.parseInt(defaultFontSizeString));
4229 } catch (Exception exception) {
4230 // If the app settings value is invalid, set the font size to 100%.
4231 nestedScrollWebView.getSettings().setTextZoom(100);
4234 // Apply the form data setting if the API < 26.
4235 if (Build.VERSION.SDK_INT < 26) {
4236 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
4239 // Store the swipe to refresh status in the nested scroll WebView.
4240 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
4242 // Apply swipe to refresh according to the default.
4243 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
4245 // Reset the pinned variables.
4246 nestedScrollWebView.setDomainSettingsDatabaseId(-1);
4248 // Set third-party cookies status if API >= 21.
4249 if (Build.VERSION.SDK_INT >= 21) {
4250 cookieManager.setAcceptThirdPartyCookies(nestedScrollWebView, defaultThirdPartyCookiesEnabled);
4253 // Get the array position of the user agent name.
4254 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4256 // Set the user agent.
4257 switch (userAgentArrayPosition) {
4258 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
4259 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4260 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
4263 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4264 // Set the user agent to `""`, which uses the default value.
4265 nestedScrollWebView.getSettings().setUserAgentString("");
4268 case SETTINGS_CUSTOM_USER_AGENT:
4269 // Set the default custom user agent.
4270 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
4274 // Get the user agent string from the user agent data array
4275 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4278 // Set the viewport.
4279 nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
4281 // Set the loading of webpage images.
4282 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4284 // Set a transparent background on URL edit text. The deprecated `getResources().getDrawable()` must be used until the minimum API >= 21.
4285 urlRelativeLayout.setBackground(getResources().getDrawable(R.color.transparent));
4288 // Close the domains database helper.
4289 domainsDatabaseHelper.close();
4291 // Update the privacy icons.
4292 updatePrivacyIcons(true);
4295 // Reload the website if returning from the Domains activity.
4296 if (reloadWebsite) {
4297 nestedScrollWebView.reload();
4300 // Return the user agent changed status.
4301 return !nestedScrollWebView.getSettings().getUserAgentString().equals(initialUserAgent);
4304 private void applyProxy(boolean reloadWebViews) {
4305 // Get a handle for the shared preferences.
4306 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4308 // Get the theme preferences.
4309 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
4311 // Get a handle for the app bar layout.
4312 AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
4314 // Set the proxy according to the mode. `this` refers to the current activity where an alert dialog might be displayed.
4315 ProxyHelper.setProxy(getApplicationContext(), appBarLayout, proxyMode);
4317 // Reset the waiting for proxy tracker.
4318 waitingForProxy = false;
4320 // Update the user interface and reload the WebViews if requested.
4321 switch (proxyMode) {
4322 case ProxyHelper.NONE:
4323 // Set the default app bar layout background.
4325 appBarLayout.setBackgroundResource(R.color.gray_900);
4327 appBarLayout.setBackgroundResource(R.color.gray_100);
4331 case ProxyHelper.TOR:
4332 // Set the app bar background to indicate proxying through Orbot is enabled.
4334 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4336 appBarLayout.setBackgroundResource(R.color.blue_50);
4339 // Check to see if Orbot is installed.
4341 // Get the package manager.
4342 PackageManager packageManager = getPackageManager();
4344 // 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.
4345 packageManager.getPackageInfo("org.torproject.android", 0);
4347 // Check to see if the proxy is ready.
4348 if (!orbotStatus.equals("ON")) { // Orbot is not ready.
4349 // Set the waiting for proxy status.
4350 waitingForProxy = true;
4352 // Show the waiting for proxy dialog if it isn't already displayed.
4353 if (getSupportFragmentManager().findFragmentByTag(getString(R.string.waiting_for_proxy_dialog)) == null) {
4354 // Get a handle for the waiting for proxy alert dialog.
4355 DialogFragment waitingForProxyDialogFragment = new WaitingForProxyDialog();
4357 // Display the waiting for proxy alert dialog.
4358 waitingForProxyDialogFragment.show(getSupportFragmentManager(), getString(R.string.waiting_for_proxy_dialog));
4361 } catch (PackageManager.NameNotFoundException exception) { // Orbot is not installed.
4362 // Show the Orbot not installed dialog if it is not already displayed.
4363 if (getSupportFragmentManager().findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
4364 // Get a handle for the Orbot not installed alert dialog.
4365 DialogFragment orbotNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode);
4367 // Display the Orbot not installed alert dialog.
4368 orbotNotInstalledDialogFragment.show(getSupportFragmentManager(), getString(R.string.proxy_not_installed_dialog));
4373 case ProxyHelper.I2P:
4374 // Set the app bar background to indicate proxying through Orbot is enabled.
4376 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4378 appBarLayout.setBackgroundResource(R.color.blue_50);
4381 // Check to see if I2P is installed.
4383 // Get the package manager.
4384 PackageManager packageManager = getPackageManager();
4386 // 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.
4387 packageManager.getPackageInfo("org.torproject.android", 0);
4388 } catch (PackageManager.NameNotFoundException exception) { // I2P is not installed.
4389 // Sow the I2P not installed dialog if it is not already displayed.
4390 if (getSupportFragmentManager().findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
4391 // Get a handle for the waiting for proxy alert dialog.
4392 DialogFragment i2pNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode);
4394 // Display the I2P not installed alert dialog.
4395 i2pNotInstalledDialogFragment.show(getSupportFragmentManager(), getString(R.string.proxy_not_installed_dialog));
4400 case ProxyHelper.CUSTOM:
4401 // Set the app bar background to indicate proxying through Orbot is enabled.
4403 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4405 appBarLayout.setBackgroundResource(R.color.blue_50);
4410 // Reload the WebViews if requested and not waiting for the proxy.
4411 if (reloadWebViews && !waitingForProxy) {
4412 // Reload the WebViews.
4413 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4414 // Get the WebView tab fragment.
4415 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4417 // Get the fragment view.
4418 View fragmentView = webViewTabFragment.getView();
4420 // Only reload the WebViews if they exist.
4421 if (fragmentView != null) {
4422 // Get the nested scroll WebView from the tab fragment.
4423 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4425 // Reload the WebView.
4426 nestedScrollWebView.reload();
4432 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
4433 // Only update the privacy icons if the options menu and the current WebView have already been populated.
4434 if ((optionsMenu != null) && (currentWebView != null)) {
4435 // Get a handle for the shared preferences.
4436 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4438 // Get the theme and screenshot preferences.
4439 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
4441 // Get handles for the menu items.
4442 MenuItem privacyMenuItem = optionsMenu.findItem(R.id.toggle_javascript);
4443 MenuItem firstPartyCookiesMenuItem = optionsMenu.findItem(R.id.toggle_first_party_cookies);
4444 MenuItem domStorageMenuItem = optionsMenu.findItem(R.id.toggle_dom_storage);
4445 MenuItem refreshMenuItem = optionsMenu.findItem(R.id.refresh);
4447 // Update the privacy icon.
4448 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is enabled.
4449 privacyMenuItem.setIcon(R.drawable.javascript_enabled);
4450 } else if (currentWebView.getAcceptFirstPartyCookies()) { // JavaScript is disabled but cookies are enabled.
4451 privacyMenuItem.setIcon(R.drawable.warning);
4452 } else { // All the dangerous features are disabled.
4453 privacyMenuItem.setIcon(R.drawable.privacy_mode);
4456 // Update the first-party cookies icon.
4457 if (currentWebView.getAcceptFirstPartyCookies()) { // First-party cookies are enabled.
4458 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
4459 } else { // First-party cookies are disabled.
4461 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_dark);
4463 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_light);
4467 // Update the DOM storage icon.
4468 if (currentWebView.getSettings().getJavaScriptEnabled() && currentWebView.getSettings().getDomStorageEnabled()) { // Both JavaScript and DOM storage are enabled.
4469 domStorageMenuItem.setIcon(R.drawable.dom_storage_enabled);
4470 } else if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is enabled but DOM storage is disabled.
4472 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
4474 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
4476 } else { // JavaScript is disabled, so DOM storage is ghosted.
4478 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
4480 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
4484 // Update the refresh icon.
4486 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
4488 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
4491 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
4492 if (runInvalidateOptionsMenu) {
4493 invalidateOptionsMenu();
4498 private void highlightUrlText() {
4499 // Get a handle for the URL edit text.
4500 EditText urlEditText = findViewById(R.id.url_edittext);
4502 // Only highlight the URL text if the box is not currently selected.
4503 if (!urlEditText.hasFocus()) {
4504 // Get the URL string.
4505 String urlString = urlEditText.getText().toString();
4507 // Highlight the URL according to the protocol.
4508 if (urlString.startsWith("file://") || urlString.startsWith("content://")) { // This is a file or content URL.
4509 // De-emphasize everything before the file name.
4510 urlEditText.getText().setSpan(initialGrayColorSpan, 0, urlString.lastIndexOf("/") + 1,Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4511 } else { // This is a web URL.
4512 // Get the index of the `/` immediately after the domain name.
4513 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
4515 // Create a base URL string.
4518 // Get the base URL.
4519 if (endOfDomainName > 0) { // There is at least one character after the base URL.
4520 // Get the base URL.
4521 baseUrl = urlString.substring(0, endOfDomainName);
4522 } else { // There are no characters after the base URL.
4523 // Set the base URL to be the entire URL string.
4524 baseUrl = urlString;
4527 // Get the index of the last `.` in the domain.
4528 int lastDotIndex = baseUrl.lastIndexOf(".");
4530 // Get the index of the penultimate `.` in the domain.
4531 int penultimateDotIndex = baseUrl.lastIndexOf(".", lastDotIndex - 1);
4533 // Markup the beginning of the URL.
4534 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
4535 urlEditText.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4537 // De-emphasize subdomains.
4538 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
4539 urlEditText.getText().setSpan(initialGrayColorSpan, 7, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4541 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
4542 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
4543 // De-emphasize the protocol and the additional subdomains.
4544 urlEditText.getText().setSpan(initialGrayColorSpan, 0, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4545 } else { // There is only one subdomain in the domain name.
4546 // De-emphasize only the protocol.
4547 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4551 // De-emphasize the text after the domain name.
4552 if (endOfDomainName > 0) {
4553 urlEditText.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4559 private void loadBookmarksFolder() {
4560 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
4561 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
4563 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
4564 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
4566 public View newView(Context context, Cursor cursor, ViewGroup parent) {
4567 // Inflate the individual item layout. `false` does not attach it to the root.
4568 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
4572 public void bindView(View view, Context context, Cursor cursor) {
4573 // Get handles for the views.
4574 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
4575 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
4577 // Get the favorite icon byte array from the cursor.
4578 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
4580 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
4581 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
4583 // Display the bitmap in `bookmarkFavoriteIcon`.
4584 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4586 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4587 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
4588 bookmarkNameTextView.setText(bookmarkNameString);
4590 // Make the font bold for folders.
4591 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4592 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4593 } else { // Reset the font to default for normal bookmarks.
4594 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4599 // Get a handle for the bookmarks list view.
4600 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
4602 // Populate the list view with the adapter.
4603 bookmarksListView.setAdapter(bookmarksCursorAdapter);
4605 // Get a handle for the bookmarks title text view.
4606 TextView bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
4608 // Set the bookmarks drawer title.
4609 if (currentBookmarksFolder.isEmpty()) {
4610 bookmarksTitleTextView.setText(R.string.bookmarks);
4612 bookmarksTitleTextView.setText(currentBookmarksFolder);
4616 private void openWithApp(String url) {
4617 // Create an open with app intent with `ACTION_VIEW`.
4618 Intent openWithAppIntent = new Intent(Intent.ACTION_VIEW);
4620 // Set the URI but not the MIME type. This should open all available apps.
4621 openWithAppIntent.setData(Uri.parse(url));
4623 // Flag the intent to open in a new task.
4624 openWithAppIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4628 // Show the chooser.
4629 startActivity(openWithAppIntent);
4630 } catch (ActivityNotFoundException exception) { // There are no apps available to open the URL.
4631 // Show a snackbar with the error.
4632 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
4636 private void openWithBrowser(String url) {
4637 // Create an open with browser intent with `ACTION_VIEW`.
4638 Intent openWithBrowserIntent = new Intent(Intent.ACTION_VIEW);
4640 // Set the URI and the MIME type. `"text/html"` should load browser options.
4641 openWithBrowserIntent.setDataAndType(Uri.parse(url), "text/html");
4643 // Flag the intent to open in a new task.
4644 openWithBrowserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4648 // Show the chooser.
4649 startActivity(openWithBrowserIntent);
4650 } catch (ActivityNotFoundException exception) { // There are no browsers available to open the URL.
4651 // Show a snackbar with the error.
4652 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
4656 private String sanitizeUrl(String url) {
4657 // Sanitize Google Analytics.
4658 if (sanitizeGoogleAnalytics) {
4660 if (url.contains("?utm_")) {
4661 url = url.substring(0, url.indexOf("?utm_"));
4665 if (url.contains("&utm_")) {
4666 url = url.substring(0, url.indexOf("&utm_"));
4670 // Sanitize Facebook Click IDs.
4671 if (sanitizeFacebookClickIds) {
4672 // Remove `?fbclid=`.
4673 if (url.contains("?fbclid=")) {
4674 url = url.substring(0, url.indexOf("?fbclid="));
4677 // Remove `&fbclid=`.
4678 if (url.contains("&fbclid=")) {
4679 url = url.substring(0, url.indexOf("&fbclid="));
4682 // Remove `?fbadid=`.
4683 if (url.contains("?fbadid=")) {
4684 url = url.substring(0, url.indexOf("?fbadid="));
4687 // Remove `&fbadid=`.
4688 if (url.contains("&fbadid=")) {
4689 url = url.substring(0, url.indexOf("&fbadid="));
4693 // Sanitize Twitter AMP redirects.
4694 if (sanitizeTwitterAmpRedirects) {
4696 if (url.contains("?amp=1")) {
4697 url = url.substring(0, url.indexOf("?amp=1"));
4701 // Return the sanitized URL.
4705 public void finishedPopulatingBlocklists(ArrayList<ArrayList<List<String[]>>> combinedBlocklists) {
4706 // Store the blocklists.
4707 easyList = combinedBlocklists.get(0);
4708 easyPrivacy = combinedBlocklists.get(1);
4709 fanboysAnnoyanceList = combinedBlocklists.get(2);
4710 fanboysSocialList = combinedBlocklists.get(3);
4711 ultraList = combinedBlocklists.get(4);
4712 ultraPrivacy = combinedBlocklists.get(5);
4714 // Add the first tab.
4715 addNewTab("", true);
4718 public void addTab(View view) {
4719 // Add a new tab with a blank URL.
4720 addNewTab("", true);
4723 private void addNewTab(String url, boolean moveToTab) {
4724 // Sanitize the URL.
4725 url = sanitizeUrl(url);
4727 // Get a handle for the tab layout and the view pager.
4728 TabLayout tabLayout = findViewById(R.id.tablayout);
4729 ViewPager webViewPager = findViewById(R.id.webviewpager);
4731 // Get the new page number. The page numbers are 0 indexed, so the new page number will match the current count.
4732 int newTabNumber = tabLayout.getTabCount();
4735 tabLayout.addTab(tabLayout.newTab());
4738 TabLayout.Tab newTab = tabLayout.getTabAt(newTabNumber);
4740 // Remove the lint warning below that the current tab might be null.
4741 assert newTab != null;
4743 // Set a custom view on the new tab.
4744 newTab.setCustomView(R.layout.tab_custom_view);
4746 // Add the new WebView page.
4747 webViewPagerAdapter.addPage(newTabNumber, webViewPager, url, moveToTab);
4750 public void closeTab(View view) {
4751 // Get a handle for the tab layout.
4752 TabLayout tabLayout = findViewById(R.id.tablayout);
4754 // Run the command according to the number of tabs.
4755 if (tabLayout.getTabCount() > 1) { // There is more than one tab open.
4756 // Close the current tab.
4758 } else { // There is only one tab open.
4763 private void closeCurrentTab() {
4764 // Get handles for the views.
4765 AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
4766 TabLayout tabLayout = findViewById(R.id.tablayout);
4767 ViewPager webViewPager = findViewById(R.id.webviewpager);
4769 // Get the current tab number.
4770 int currentTabNumber = tabLayout.getSelectedTabPosition();
4772 // Delete the current tab.
4773 tabLayout.removeTabAt(currentTabNumber);
4775 // 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.
4776 if (webViewPagerAdapter.deletePage(currentTabNumber, webViewPager)) {
4777 setCurrentWebView(currentTabNumber);
4780 // Expand the app bar if it is currently collapsed.
4781 appBarLayout.setExpanded(true);
4784 private void clearAndExit() {
4785 // Get a handle for the shared preferences.
4786 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4788 // Close the bookmarks cursor and database.
4789 bookmarksCursor.close();
4790 bookmarksDatabaseHelper.close();
4792 // Get the status of the clear everything preference.
4793 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
4795 // Get a handle for the runtime.
4796 Runtime runtime = Runtime.getRuntime();
4798 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
4799 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
4800 String privateDataDirectoryString = getApplicationInfo().dataDir;
4803 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
4804 // The command to remove cookies changed slightly in API 21.
4805 if (Build.VERSION.SDK_INT >= 21) {
4806 CookieManager.getInstance().removeAllCookies(null);
4808 CookieManager.getInstance().removeAllCookie();
4811 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4813 // Two commands must be used because `Runtime.exec()` does not like `*`.
4814 Process deleteCookiesProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
4815 Process deleteCookiesJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
4817 // Wait until the processes have finished.
4818 deleteCookiesProcess.waitFor();
4819 deleteCookiesJournalProcess.waitFor();
4820 } catch (Exception exception) {
4821 // Do nothing if an error is thrown.
4825 // Clear DOM storage.
4826 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
4827 // Ask `WebStorage` to clear the DOM storage.
4828 WebStorage webStorage = WebStorage.getInstance();
4829 webStorage.deleteAllData();
4831 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4833 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4834 Process deleteLocalStorageProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
4836 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
4837 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
4838 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
4839 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
4840 Process deleteDatabaseProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
4842 // Wait until the processes have finished.
4843 deleteLocalStorageProcess.waitFor();
4844 deleteIndexProcess.waitFor();
4845 deleteQuotaManagerProcess.waitFor();
4846 deleteQuotaManagerJournalProcess.waitFor();
4847 deleteDatabaseProcess.waitFor();
4848 } catch (Exception exception) {
4849 // Do nothing if an error is thrown.
4853 // Clear form data if the API < 26.
4854 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
4855 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
4856 webViewDatabase.clearFormData();
4858 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4860 // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
4861 Process deleteWebDataProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
4862 Process deleteWebDataJournalProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
4864 // Wait until the processes have finished.
4865 deleteWebDataProcess.waitFor();
4866 deleteWebDataJournalProcess.waitFor();
4867 } catch (Exception exception) {
4868 // Do nothing if an error is thrown.
4873 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
4874 // Clear the cache from each WebView.
4875 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4876 // Get the WebView tab fragment.
4877 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4879 // Get the fragment view.
4880 View fragmentView = webViewTabFragment.getView();
4882 // Only clear the cache if the WebView exists.
4883 if (fragmentView != null) {
4884 // Get the nested scroll WebView from the tab fragment.
4885 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4887 // Clear the cache for this WebView.
4888 nestedScrollWebView.clearCache(true);
4892 // Manually delete the cache directories.
4894 // Delete the main cache directory.
4895 Process deleteCacheProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/cache");
4897 // Delete the secondary `Service Worker` cache directory.
4898 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4899 Process deleteServiceWorkerProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
4901 // Wait until the processes have finished.
4902 deleteCacheProcess.waitFor();
4903 deleteServiceWorkerProcess.waitFor();
4904 } catch (Exception exception) {
4905 // Do nothing if an error is thrown.
4909 // Wipe out each WebView.
4910 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4911 // Get the WebView tab fragment.
4912 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4914 // Get the fragment view.
4915 View fragmentView = webViewTabFragment.getView();
4917 // Only wipe out the WebView if it exists.
4918 if (fragmentView != null) {
4919 // Get the nested scroll WebView from the tab fragment.
4920 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4922 // Clear SSL certificate preferences for this WebView.
4923 nestedScrollWebView.clearSslPreferences();
4925 // Clear the back/forward history for this WebView.
4926 nestedScrollWebView.clearHistory();
4928 // Destroy the internal state of `mainWebView`.
4929 nestedScrollWebView.destroy();
4933 // Clear the custom headers.
4934 customHeaders.clear();
4936 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
4937 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
4938 if (clearEverything) {
4940 // Delete the folder.
4941 Process deleteAppWebviewProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
4943 // Wait until the process has finished.
4944 deleteAppWebviewProcess.waitFor();
4945 } catch (Exception exception) {
4946 // Do nothing if an error is thrown.
4950 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
4951 if (Build.VERSION.SDK_INT >= 21) {
4952 finishAndRemoveTask();
4957 // Remove the terminated program from RAM. The status code is `0`.
4961 private void setCurrentWebView(int pageNumber) {
4962 // Get a handle for the shared preferences.
4963 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4965 // Get the theme preference.
4966 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
4968 // Get handles for the URL views.
4969 RelativeLayout urlRelativeLayout = findViewById(R.id.url_relativelayout);
4970 EditText urlEditText = findViewById(R.id.url_edittext);
4971 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
4973 // Stop the swipe to refresh indicator if it is running
4974 swipeRefreshLayout.setRefreshing(false);
4976 // Get the WebView tab fragment.
4977 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(pageNumber);
4979 // Get the fragment view.
4980 View fragmentView = webViewTabFragment.getView();
4982 // Set the current WebView if the fragment view is not null.
4983 if (fragmentView != null) { // The fragment has been populated.
4984 // Store the current WebView.
4985 currentWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4987 // Update the status of swipe to refresh.
4988 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
4989 // Enable the swipe refresh layout if the WebView is scrolled all the way to the top. It is updated every time the scroll changes.
4990 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
4991 } else { // Swipe to refresh is disabled.
4992 // Disable the swipe refresh layout.
4993 swipeRefreshLayout.setEnabled(false);
4996 // Get a handle for the cookie manager.
4997 CookieManager cookieManager = CookieManager.getInstance();
4999 // Set the first-party cookie status.
5000 cookieManager.setAcceptCookie(currentWebView.getAcceptFirstPartyCookies());
5002 // Update the privacy icons. `true` redraws the icons in the app bar.
5003 updatePrivacyIcons(true);
5005 // Get a handle for the input method manager.
5006 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
5008 // Remove the lint warning below that the input method manager might be null.
5009 assert inputMethodManager != null;
5011 // Get the current URL.
5012 String url = currentWebView.getUrl();
5014 // Update the URL edit text if not loading a new intent. Otherwise, this will be handled by `onPageStarted()` (if called) and `onPageFinished()`.
5015 if (!loadingNewIntent) { // A new intent is not being loaded.
5016 if ((url == null) || url.equals("about:blank")) { // The WebView is blank.
5017 // Display the hint in the URL edit text.
5018 urlEditText.setText("");
5020 // Request focus for the URL text box.
5021 urlEditText.requestFocus();
5023 // Display the keyboard.
5024 inputMethodManager.showSoftInput(urlEditText, 0);
5025 } else { // The WebView has a loaded URL.
5026 // Clear the focus from the URL text box.
5027 urlEditText.clearFocus();
5029 // Hide the soft keyboard.
5030 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
5032 // Display the current URL in the URL text box.
5033 urlEditText.setText(url);
5035 // Highlight the URL text.
5038 } else { // A new intent is being loaded.
5039 // Reset the loading new intent tracker.
5040 loadingNewIntent = false;
5043 // Set the background to indicate the domain settings status.
5044 if (currentWebView.getDomainSettingsApplied()) {
5045 // 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.
5047 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
5049 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
5052 urlRelativeLayout.setBackground(getResources().getDrawable(R.color.transparent));
5054 } else { // The fragment has not been populated. Try again in 100 milliseconds.
5055 // Create a handler to set the current WebView.
5056 Handler setCurrentWebViewHandler = new Handler();
5058 // Create a runnable to set the current WebView.
5059 Runnable setCurrentWebWebRunnable = () -> {
5060 // Set the current WebView.
5061 setCurrentWebView(pageNumber);
5064 // Try setting the current WebView again after 100 milliseconds.
5065 setCurrentWebViewHandler.postDelayed(setCurrentWebWebRunnable, 100);
5070 public void initializeWebView(NestedScrollWebView nestedScrollWebView, int pageNumber, ProgressBar progressBar, String url) {
5071 // Get handles for the activity views.
5072 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
5073 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
5074 RelativeLayout mainContentRelativeLayout = findViewById(R.id.main_content_relativelayout);
5075 ActionBar actionBar = getSupportActionBar();
5076 LinearLayout tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
5077 EditText urlEditText = findViewById(R.id.url_edittext);
5078 TabLayout tabLayout = findViewById(R.id.tablayout);
5079 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
5081 // Remove the incorrect lint warning below that the action bar might be null.
5082 assert actionBar != null;
5084 // Get a handle for the activity
5085 Activity activity = this;
5087 // Get a handle for the input method manager.
5088 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
5090 // Instantiate the blocklist helper.
5091 BlocklistHelper blocklistHelper = new BlocklistHelper();
5093 // Remove the lint warning below that the input method manager might be null.
5094 assert inputMethodManager != null;
5096 // Get a handle for the shared preferences.
5097 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
5099 // Initialize the favorite icon.
5100 nestedScrollWebView.initializeFavoriteIcon();
5102 // Set the app bar scrolling.
5103 nestedScrollWebView.setNestedScrollingEnabled(sharedPreferences.getBoolean("scroll_app_bar", true));
5105 // Allow pinch to zoom.
5106 nestedScrollWebView.getSettings().setBuiltInZoomControls(true);
5108 // Hide zoom controls.
5109 nestedScrollWebView.getSettings().setDisplayZoomControls(false);
5111 // Don't allow mixed content (HTTP and HTTPS) on the same website.
5112 if (Build.VERSION.SDK_INT >= 21) {
5113 nestedScrollWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);
5116 // Set the WebView to load in overview mode (zoomed out to the maximum width).
5117 nestedScrollWebView.getSettings().setLoadWithOverviewMode(true);
5119 // Explicitly disable geolocation.
5120 nestedScrollWebView.getSettings().setGeolocationEnabled(false);
5122 // Create a double-tap gesture detector to toggle full-screen mode.
5123 GestureDetector doubleTapGestureDetector = new GestureDetector(getApplicationContext(), new GestureDetector.SimpleOnGestureListener() {
5124 // Override `onDoubleTap()`. All other events are handled using the default settings.
5126 public boolean onDoubleTap(MotionEvent event) {
5127 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
5128 // Toggle the full screen browsing mode tracker.
5129 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
5131 // Toggle the full screen browsing mode.
5132 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
5133 // Store the swipe refresh layout top padding.
5134 swipeRefreshLayoutPaddingTop = swipeRefreshLayout.getPaddingTop();
5136 // Hide the app bar if specified.
5138 // Close the find on page bar if it is visible.
5139 closeFindOnPage(null);
5141 // Hide the tab linear layout.
5142 tabsLinearLayout.setVisibility(View.GONE);
5144 // Hide the action bar.
5147 // Check to see if app bar scrolling is disabled.
5148 if (!scrollAppBar) {
5149 // Remove the padding from the top of the swipe refresh layout.
5150 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5154 // Hide the banner ad in the free flavor.
5155 if (BuildConfig.FLAVOR.contentEquals("free")) {
5156 AdHelper.hideAd(findViewById(R.id.adview));
5159 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
5160 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
5162 /* Hide the system bars.
5163 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5164 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5165 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5166 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5168 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5169 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5170 } else { // Switch to normal viewing mode.
5171 // Show the tab linear layout.
5172 tabsLinearLayout.setVisibility(View.VISIBLE);
5174 // Show the action bar.
5177 // Check to see if app bar scrolling is disabled.
5178 if (!scrollAppBar) {
5179 // Add the padding from the top of the swipe refresh layout.
5180 swipeRefreshLayout.setPadding(0, swipeRefreshLayoutPaddingTop, 0, 0);
5183 // Show the banner ad in the free flavor.
5184 if (BuildConfig.FLAVOR.contentEquals("free")) {
5186 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
5189 // Remove the `SYSTEM_UI` flags from the root frame layout.
5190 rootFrameLayout.setSystemUiVisibility(0);
5192 // Add the translucent status flag.
5193 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
5196 // Consume the double-tap.
5198 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
5204 // Pass all touch events on the WebView through the double-tap gesture detector.
5205 nestedScrollWebView.setOnTouchListener((View view, MotionEvent event) -> {
5206 // Call `performClick()` on the view, which is required for accessibility.
5207 view.performClick();
5209 // Send the event to the gesture detector.
5210 return doubleTapGestureDetector.onTouchEvent(event);
5213 // Register the WebView for a context menu. This is used to see link targets and download images.
5214 registerForContextMenu(nestedScrollWebView);
5216 // Allow the downloading of files.
5217 nestedScrollWebView.setDownloadListener((String downloadUrl, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
5218 // Instantiate the save dialog.
5219 DialogFragment saveDialogFragment = SaveDialog.saveUrl(StoragePermissionDialog.SAVE_URL, downloadUrl, userAgent, nestedScrollWebView.getAcceptFirstPartyCookies());
5221 // Show the save dialog. It must be named `save_dialog` so that the file picker can update the file name.
5222 saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
5225 // Update the find on page count.
5226 nestedScrollWebView.setFindListener(new WebView.FindListener() {
5227 // Get a handle for `findOnPageCountTextView`.
5228 final TextView findOnPageCountTextView = findViewById(R.id.find_on_page_count_textview);
5231 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
5232 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
5233 // Set `findOnPageCountTextView` to `0/0`.
5234 findOnPageCountTextView.setText(R.string.zero_of_zero);
5235 } else if (isDoneCounting) { // There are matches.
5236 // `activeMatchOrdinal` is zero-based.
5237 int activeMatch = activeMatchOrdinal + 1;
5239 // Build the match string.
5240 String matchString = activeMatch + "/" + numberOfMatches;
5242 // Set `findOnPageCountTextView`.
5243 findOnPageCountTextView.setText(matchString);
5248 // Update the status of swipe to refresh based on the scroll position of the nested scroll WebView. Also reinforce full screen browsing mode.
5249 // Once the minimum API >= 23 this can be replaced with `nestedScrollWebView.setOnScrollChangeListener()`.
5250 nestedScrollWebView.getViewTreeObserver().addOnScrollChangedListener(() -> {
5251 if (nestedScrollWebView.getSwipeToRefresh()) {
5252 // Only enable swipe to refresh if the WebView is scrolled to the top.
5253 swipeRefreshLayout.setEnabled(nestedScrollWebView.getScrollY() == 0);
5256 // Reinforce the system UI visibility flags if in full screen browsing mode.
5257 // This hides the status and navigation bars, which are displayed if other elements are shown, like dialog boxes, the options menu, or the keyboard.
5258 if (inFullScreenBrowsingMode) {
5259 /* Hide the system bars.
5260 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5261 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5262 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5263 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5265 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5266 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5270 // Set the web chrome client.
5271 nestedScrollWebView.setWebChromeClient(new WebChromeClient() {
5272 // Update the progress bar when a page is loading.
5274 public void onProgressChanged(WebView view, int progress) {
5275 // Inject the night mode CSS if night mode is enabled.
5276 if (nestedScrollWebView.getNightMode()) { // Night mode is enabled.
5277 // `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
5278 // used by WordPress. `text-decoration: none` removes all text underlines. `text-shadow: none` removes text shadows, which usually have a hard coded color.
5279 // `border: none` removes all borders, which can also be used to underline text. `a {color: #1565C0}` sets links to be a dark blue.
5280 // `::selection {background: #0D47A1}' sets the text selection highlight color to be a dark blue. `!important` takes precedent over any existing sub-settings.
5281 nestedScrollWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
5282 "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
5283 "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;} ::selection {background: #0D47A1 !important;}'; parent.appendChild(style)})()", value -> {
5284 // Initialize a handler to display `mainWebView`.
5285 Handler displayWebViewHandler = new Handler();
5287 // Setup a runnable to display `mainWebView` after a delay to allow the CSS to be applied.
5288 Runnable displayWebViewRunnable = () -> {
5289 // Only display `mainWebView` if the progress bar is gone. This prevents the display of the `WebView` while it is still loading.
5290 if (progressBar.getVisibility() == View.GONE) {
5291 nestedScrollWebView.setVisibility(View.VISIBLE);
5295 // Display the WebView after 500 milliseconds.
5296 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
5298 } else { // Night mode is disabled.
5299 // Display the nested scroll WebView if night mode is disabled.
5300 // Because of a race condition between `applyDomainSettings` and `onPageStarted`,
5301 // when night mode is set by domain settings the WebView may be hidden even if night mode is not currently enabled.
5302 nestedScrollWebView.setVisibility(View.VISIBLE);
5305 // Update the progress bar.
5306 progressBar.setProgress(progress);
5308 // Set the visibility of the progress bar.
5309 if (progress < 100) {
5310 // Show the progress bar.
5311 progressBar.setVisibility(View.VISIBLE);
5313 // Hide the progress bar.
5314 progressBar.setVisibility(View.GONE);
5316 //Stop the swipe to refresh indicator if it is running
5317 swipeRefreshLayout.setRefreshing(false);
5321 // Set the favorite icon when it changes.
5323 public void onReceivedIcon(WebView view, Bitmap icon) {
5324 // Only update the favorite icon if the website has finished loading.
5325 if (progressBar.getVisibility() == View.GONE) {
5326 // Store the new favorite icon.
5327 nestedScrollWebView.setFavoriteOrDefaultIcon(icon);
5329 // Get the current page position.
5330 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5332 // Get the current tab.
5333 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
5335 // Check to see if the tab has been populated.
5337 // Get the custom view from the tab.
5338 View tabView = tab.getCustomView();
5340 // Check to see if the custom tab view has been populated.
5341 if (tabView != null) {
5342 // Get the favorite icon image view from the tab.
5343 ImageView tabFavoriteIconImageView = tabView.findViewById(R.id.favorite_icon_imageview);
5345 // Display the favorite icon in the tab.
5346 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
5352 // Save a copy of the title when it changes.
5354 public void onReceivedTitle(WebView view, String title) {
5355 // Get the current page position.
5356 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5358 // Get the current tab.
5359 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
5361 // Only populate the title text view if the tab has been fully created.
5363 // Get the custom view from the tab.
5364 View tabView = tab.getCustomView();
5366 // Remove the incorrect warning below that the current tab view might be null.
5367 assert tabView != null;
5369 // Get the title text view from the tab.
5370 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
5372 // Set the title according to the URL.
5373 if (title.equals("about:blank")) {
5374 // Set the title to indicate a new tab.
5375 tabTitleTextView.setText(R.string.new_tab);
5377 // Set the title as the tab text.
5378 tabTitleTextView.setText(title);
5383 // Enter full screen video.
5385 public void onShowCustomView(View video, CustomViewCallback callback) {
5386 // Get a handle for the full screen video frame layout.
5387 FrameLayout fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
5389 // Set the full screen video flag.
5390 displayingFullScreenVideo = true;
5392 // Pause the ad if this is the free flavor.
5393 if (BuildConfig.FLAVOR.contentEquals("free")) {
5394 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
5395 AdHelper.pauseAd(findViewById(R.id.adview));
5398 // Hide the keyboard.
5399 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
5401 // Hide the main content relative layout.
5402 mainContentRelativeLayout.setVisibility(View.GONE);
5404 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
5405 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
5407 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
5408 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
5410 /* Hide the system bars.
5411 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5412 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5413 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5414 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5416 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5417 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5419 // Disable the sliding drawers.
5420 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
5422 // Add the video view to the full screen video frame layout.
5423 fullScreenVideoFrameLayout.addView(video);
5425 // Show the full screen video frame layout.
5426 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
5428 // Disable the screen timeout while the video is playing. YouTube does this automatically, but not all other videos do.
5429 fullScreenVideoFrameLayout.setKeepScreenOn(true);
5432 // Exit full screen video.
5434 public void onHideCustomView() {
5435 // Get a handle for the full screen video frame layout.
5436 FrameLayout fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
5438 // Re-enable the screen timeout.
5439 fullScreenVideoFrameLayout.setKeepScreenOn(false);
5441 // Unset the full screen video flag.
5442 displayingFullScreenVideo = false;
5444 // Remove all the views from the full screen video frame layout.
5445 fullScreenVideoFrameLayout.removeAllViews();
5447 // Hide the full screen video frame layout.
5448 fullScreenVideoFrameLayout.setVisibility(View.GONE);
5450 // Enable the sliding drawers.
5451 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
5453 // Show the main content relative layout.
5454 mainContentRelativeLayout.setVisibility(View.VISIBLE);
5456 // Apply the appropriate full screen mode flags.
5457 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
5458 // Hide the app bar if specified.
5460 // Hide the tab linear layout.
5461 tabsLinearLayout.setVisibility(View.GONE);
5463 // Hide the action bar.
5467 // Hide the banner ad in the free flavor.
5468 if (BuildConfig.FLAVOR.contentEquals("free")) {
5469 AdHelper.hideAd(findViewById(R.id.adview));
5472 // Remove the translucent status flag. This is necessary so the root frame layout can fill the entire screen.
5473 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
5475 /* Hide the system bars.
5476 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5477 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5478 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5479 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5481 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5482 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5483 } else { // Switch to normal viewing mode.
5484 // Remove the `SYSTEM_UI` flags from the root frame layout.
5485 rootFrameLayout.setSystemUiVisibility(0);
5487 // Add the translucent status flag.
5488 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
5491 // Reload the ad for the free flavor if not in full screen mode.
5492 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
5494 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
5500 public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
5501 // Show the file chooser if the device is running API >= 21.
5502 if (Build.VERSION.SDK_INT >= 21) {
5503 // Store the file path callback.
5504 fileChooserCallback = filePathCallback;
5506 // Create an intent to open a chooser based ont the file chooser parameters.
5507 Intent fileChooserIntent = fileChooserParams.createIntent();
5509 // Open the file chooser.
5510 startActivityForResult(fileChooserIntent, BROWSE_FILE_UPLOAD_REQUEST_CODE);
5516 nestedScrollWebView.setWebViewClient(new WebViewClient() {
5517 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
5518 // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
5520 public boolean shouldOverrideUrlLoading(WebView view, String url) {
5521 // Sanitize the url.
5522 url = sanitizeUrl(url);
5524 if (url.startsWith("http")) { // Load the URL in Privacy Browser.
5525 // Apply the domain settings for the new URL. This doesn't do anything if the domain has not changed.
5526 boolean userAgentChanged = applyDomainSettings(nestedScrollWebView, url, true, false);
5528 // Check if the user agent has changed.
5529 if (userAgentChanged) {
5530 // Manually load the URL. The changing of the user agent will cause WebView to reload the previous URL.
5531 nestedScrollWebView.loadUrl(url, customHeaders);
5533 // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
5536 // Returning false causes the current WebView to handle the URL and prevents it from adding redirects to the history list.
5539 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
5540 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
5541 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
5543 // Parse the url and set it as the data for the intent.
5544 emailIntent.setData(Uri.parse(url));
5546 // Open the email program in a new task instead of as part of Privacy Browser.
5547 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5550 startActivity(emailIntent);
5552 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5554 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
5555 // Open the dialer and load the phone number, but wait for the user to place the call.
5556 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
5558 // Add the phone number to the intent.
5559 dialIntent.setData(Uri.parse(url));
5561 // Open the dialer in a new task instead of as part of Privacy Browser.
5562 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5565 startActivity(dialIntent);
5567 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5569 } else { // Load a system chooser to select an app that can handle the URL.
5570 // Open an app that can handle the URL.
5571 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
5573 // Add the URL to the intent.
5574 genericIntent.setData(Uri.parse(url));
5576 // List all apps that can handle the URL instead of just opening the first one.
5577 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
5579 // Open the app in a new task instead of as part of Privacy Browser.
5580 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5582 // Start the app or display a snackbar if no app is available to handle the URL.
5584 startActivity(genericIntent);
5585 } catch (ActivityNotFoundException exception) {
5586 Snackbar.make(nestedScrollWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
5589 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5594 // Check requests against the block lists. The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
5596 public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
5597 // Check to see if the resource request is for the main URL.
5598 if (url.equals(nestedScrollWebView.getCurrentUrl())) {
5599 // `return null` loads the resource request, which should never be blocked if it is the main URL.
5603 // 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.
5604 while (ultraPrivacy == null) {
5605 // The wait must be synchronized, which only lets one thread run on it at a time, or `java.lang.IllegalMonitorStateException` is thrown.
5606 synchronized (this) {
5608 // Check to see if the blocklists have been populated after 100 ms.
5610 } catch (InterruptedException exception) {
5616 // Sanitize the URL.
5617 url = sanitizeUrl(url);
5619 // Get a handle for the navigation view.
5620 NavigationView navigationView = findViewById(R.id.navigationview);
5622 // Get a handle for the navigation menu.
5623 Menu navigationMenu = navigationView.getMenu();
5625 // Get a handle for the navigation requests menu item. The menu is 0 based.
5626 MenuItem navigationRequestsMenuItem = navigationMenu.getItem(6);
5628 // Create an empty web resource response to be used if the resource request is blocked.
5629 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
5631 // Reset the whitelist results tracker.
5632 String[] whitelistResultStringArray = null;
5634 // Initialize the third party request tracker.
5635 boolean isThirdPartyRequest = false;
5637 // Get the current URL. `.getUrl()` throws an error because operations on the WebView cannot be made from this thread.
5638 String currentBaseDomain = nestedScrollWebView.getCurrentDomainName();
5640 // Store a copy of the current domain for use in later requests.
5641 String currentDomain = currentBaseDomain;
5643 // Nobody is happy when comparing null strings.
5644 if ((currentBaseDomain != null) && (url != null)) {
5645 // Convert the request URL to a URI.
5646 Uri requestUri = Uri.parse(url);
5648 // Get the request host name.
5649 String requestBaseDomain = requestUri.getHost();
5651 // Only check for third-party requests if the current base domain is not empty and the request domain is not null.
5652 if (!currentBaseDomain.isEmpty() && (requestBaseDomain != null)) {
5653 // Determine the current base domain.
5654 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5655 // Remove the first subdomain.
5656 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
5659 // Determine the request base domain.
5660 while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5661 // Remove the first subdomain.
5662 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
5665 // Update the third party request tracker.
5666 isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
5670 // Get the current WebView page position.
5671 int webViewPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5673 // Determine if the WebView is currently displayed.
5674 boolean webViewDisplayed = (webViewPagePosition == tabLayout.getSelectedTabPosition());
5676 // Block third-party requests if enabled.
5677 if (isThirdPartyRequest && nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS)) {
5678 // Add the result to the resource requests.
5679 nestedScrollWebView.addResourceRequest(new String[]{BlocklistHelper.REQUEST_THIRD_PARTY, url});
5681 // Increment the blocked requests counters.
5682 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5683 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS);
5685 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5686 if (webViewDisplayed) {
5687 // Updating the UI must be run from the UI thread.
5688 activity.runOnUiThread(() -> {
5689 // Update the menu item titles.
5690 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5692 // Update the options menu if it has been populated.
5693 if (optionsMenu != null) {
5694 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5695 optionsMenu.findItem(R.id.block_all_third_party_requests).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " +
5696 getString(R.string.block_all_third_party_requests));
5701 // Return an empty web resource response.
5702 return emptyWebResourceResponse;
5705 // Check UltraList if it is enabled.
5706 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST)) {
5707 // Check the URL against UltraList.
5708 String[] ultraListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraList);
5710 // Process the UltraList results.
5711 if (ultraListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched UltraLists's blacklist.
5712 // Add the result to the resource requests.
5713 nestedScrollWebView.addResourceRequest(new String[] {ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]});
5715 // Increment the blocked requests counters.
5716 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5717 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRALIST);
5719 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5720 if (webViewDisplayed) {
5721 // Updating the UI must be run from the UI thread.
5722 activity.runOnUiThread(() -> {
5723 // Update the menu item titles.
5724 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5726 // Update the options menu if it has been populated.
5727 if (optionsMenu != null) {
5728 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5729 optionsMenu.findItem(R.id.ultralist).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRALIST) + " - " + getString(R.string.ultralist));
5734 // The resource request was blocked. Return an empty web resource response.
5735 return emptyWebResourceResponse;
5736 } else if (ultraListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched UltraList's whitelist.
5737 // Add a whitelist entry to the resource requests array.
5738 nestedScrollWebView.addResourceRequest(new String[] {ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]});
5740 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
5745 // Check UltraPrivacy if it is enabled.
5746 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY)) {
5747 // Check the URL against UltraPrivacy.
5748 String[] ultraPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraPrivacy);
5750 // Process the UltraPrivacy results.
5751 if (ultraPrivacyResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched UltraPrivacy's blacklist.
5752 // Add the result to the resource requests.
5753 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5754 ultraPrivacyResults[5]});
5756 // Increment the blocked requests counters.
5757 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5758 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRAPRIVACY);
5760 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5761 if (webViewDisplayed) {
5762 // Updating the UI must be run from the UI thread.
5763 activity.runOnUiThread(() -> {
5764 // Update the menu item titles.
5765 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5767 // Update the options menu if it has been populated.
5768 if (optionsMenu != null) {
5769 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5770 optionsMenu.findItem(R.id.ultraprivacy).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRAPRIVACY) + " - " + getString(R.string.ultraprivacy));
5775 // The resource request was blocked. Return an empty web resource response.
5776 return emptyWebResourceResponse;
5777 } else if (ultraPrivacyResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched UltraPrivacy's whitelist.
5778 // Add a whitelist entry to the resource requests array.
5779 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5780 ultraPrivacyResults[5]});
5782 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
5787 // Check EasyList if it is enabled.
5788 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST)) {
5789 // Check the URL against EasyList.
5790 String[] easyListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyList);
5792 // Process the EasyList results.
5793 if (easyListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched EasyList's blacklist.
5794 // Add the result to the resource requests.
5795 nestedScrollWebView.addResourceRequest(new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]});
5797 // Increment the blocked requests counters.
5798 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5799 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASYLIST);
5801 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5802 if (webViewDisplayed) {
5803 // Updating the UI must be run from the UI thread.
5804 activity.runOnUiThread(() -> {
5805 // Update the menu item titles.
5806 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5808 // Update the options menu if it has been populated.
5809 if (optionsMenu != null) {
5810 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5811 optionsMenu.findItem(R.id.easylist).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASYLIST) + " - " + getString(R.string.easylist));
5816 // The resource request was blocked. Return an empty web resource response.
5817 return emptyWebResourceResponse;
5818 } else if (easyListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched EasyList's whitelist.
5819 // Update the whitelist result string array tracker.
5820 whitelistResultStringArray = new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]};
5824 // Check EasyPrivacy if it is enabled.
5825 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY)) {
5826 // Check the URL against EasyPrivacy.
5827 String[] easyPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyPrivacy);
5829 // Process the EasyPrivacy results.
5830 if (easyPrivacyResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched EasyPrivacy's blacklist.
5831 // Add the result to the resource requests.
5832 nestedScrollWebView.addResourceRequest(new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4],
5833 easyPrivacyResults[5]});
5835 // Increment the blocked requests counters.
5836 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5837 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASYPRIVACY);
5839 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5840 if (webViewDisplayed) {
5841 // Updating the UI must be run from the UI thread.
5842 activity.runOnUiThread(() -> {
5843 // Update the menu item titles.
5844 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5846 // Update the options menu if it has been populated.
5847 if (optionsMenu != null) {
5848 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5849 optionsMenu.findItem(R.id.easyprivacy).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASYPRIVACY) + " - " + getString(R.string.easyprivacy));
5854 // The resource request was blocked. Return an empty web resource response.
5855 return emptyWebResourceResponse;
5856 } else if (easyPrivacyResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched EasyPrivacy's whitelist.
5857 // Update the whitelist result string array tracker.
5858 whitelistResultStringArray = new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5]};
5862 // Check Fanboy’s Annoyance List if it is enabled.
5863 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST)) {
5864 // Check the URL against Fanboy's Annoyance List.
5865 String[] fanboysAnnoyanceListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList);
5867 // Process the Fanboy's Annoyance List results.
5868 if (fanboysAnnoyanceListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Annoyance List's blacklist.
5869 // Add the result to the resource requests.
5870 nestedScrollWebView.addResourceRequest(new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5871 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]});
5873 // Increment the blocked requests counters.
5874 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5875 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST);
5877 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5878 if (webViewDisplayed) {
5879 // Updating the UI must be run from the UI thread.
5880 activity.runOnUiThread(() -> {
5881 // Update the menu item titles.
5882 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5884 // Update the options menu if it has been populated.
5885 if (optionsMenu != null) {
5886 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5887 optionsMenu.findItem(R.id.fanboys_annoyance_list).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " +
5888 getString(R.string.fanboys_annoyance_list));
5893 // The resource request was blocked. Return an empty web resource response.
5894 return emptyWebResourceResponse;
5895 } else if (fanboysAnnoyanceListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)){ // The resource request matched Fanboy's Annoyance List's whitelist.
5896 // Update the whitelist result string array tracker.
5897 whitelistResultStringArray = new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5898 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]};
5900 } else if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST)) { // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
5901 // Check the URL against Fanboy's Annoyance List.
5902 String[] fanboysSocialListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysSocialList);
5904 // Process the Fanboy's Social Blocking List results.
5905 if (fanboysSocialListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Social Blocking List's blacklist.
5906 // Add the result to the resource requests.
5907 nestedScrollWebView.addResourceRequest(new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5908 fanboysSocialListResults[4], fanboysSocialListResults[5]});
5910 // Increment the blocked requests counters.
5911 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5912 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST);
5914 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5915 if (webViewDisplayed) {
5916 // Updating the UI must be run from the UI thread.
5917 activity.runOnUiThread(() -> {
5918 // Update the menu item titles.
5919 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5921 // Update the options menu if it has been populated.
5922 if (optionsMenu != null) {
5923 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5924 optionsMenu.findItem(R.id.fanboys_social_blocking_list).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " +
5925 getString(R.string.fanboys_social_blocking_list));
5930 // The resource request was blocked. Return an empty web resource response.
5931 return emptyWebResourceResponse;
5932 } else if (fanboysSocialListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched Fanboy's Social Blocking List's whitelist.
5933 // Update the whitelist result string array tracker.
5934 whitelistResultStringArray = new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5935 fanboysSocialListResults[4], fanboysSocialListResults[5]};
5939 // Add the request to the log because it hasn't been processed by any of the previous checks.
5940 if (whitelistResultStringArray != null) { // The request was processed by a whitelist.
5941 nestedScrollWebView.addResourceRequest(whitelistResultStringArray);
5942 } else { // The request didn't match any blocklist entry. Log it as a default request.
5943 nestedScrollWebView.addResourceRequest(new String[]{BlocklistHelper.REQUEST_DEFAULT, url});
5946 // The resource request has not been blocked. `return null` loads the requested resource.
5950 // Handle HTTP authentication requests.
5952 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
5953 // Store the handler.
5954 nestedScrollWebView.setHttpAuthHandler(handler);
5956 // Instantiate an HTTP authentication dialog.
5957 DialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm, nestedScrollWebView.getWebViewFragmentId());
5959 // Show the HTTP authentication dialog.
5960 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
5964 public void onPageStarted(WebView view, String url, Bitmap favicon) {
5965 // Get the preferences.
5966 boolean scrollAppBar = sharedPreferences.getBoolean("scroll_app_bar", true);
5967 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
5969 // Get a handler for the app bar layout.
5970 AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
5972 // Set the top padding of the swipe refresh layout according to the app bar scrolling preference.
5974 // No padding is needed because it will automatically be placed below the app bar layout due to the scrolling layout behavior.
5975 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5977 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5978 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10, defaultProgressViewEndOffset);
5980 // Get the app bar layout height. This can't be done in `applyAppSettings()` because the app bar is not yet populated.
5981 int appBarHeight = appBarLayout.getHeight();
5983 // The swipe refresh layout must be manually moved below the app bar layout.
5984 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0);
5986 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5987 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight);
5990 // Reset the list of resource requests.
5991 nestedScrollWebView.clearResourceRequests();
5993 // Reset the requests counters.
5994 nestedScrollWebView.resetRequestsCounters();
5996 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
5997 if (nestedScrollWebView.getNightMode()) {
5998 nestedScrollWebView.setVisibility(View.INVISIBLE);
6000 nestedScrollWebView.setVisibility(View.VISIBLE);
6003 // Hide the keyboard.
6004 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
6006 // Get the current page position.
6007 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
6009 // Update the URL text bar if the page is currently selected.
6010 if (tabLayout.getSelectedTabPosition() == currentPagePosition) {
6011 // Clear the focus from the URL edit text.
6012 urlEditText.clearFocus();
6014 // Display the formatted URL text.
6015 urlEditText.setText(url);
6017 // Apply text highlighting to `urlTextBox`.
6021 // Reset the list of host IP addresses.
6022 nestedScrollWebView.clearCurrentIpAddresses();
6024 // Get a URI for the current URL.
6025 Uri currentUri = Uri.parse(url);
6027 // Get the IP addresses for the host.
6028 new GetHostIpAddresses(activity, getSupportFragmentManager(), nestedScrollWebView).execute(currentUri.getHost());
6030 // Replace Refresh with Stop if the options menu has been created. (The first WebView typically begins loading before the menu items are instantiated.)
6031 if (optionsMenu != null) {
6032 // Get a handle for the refresh menu item.
6033 MenuItem refreshMenuItem = optionsMenu.findItem(R.id.refresh);
6036 refreshMenuItem.setTitle(R.string.stop);
6038 // Get the app bar and theme preferences.
6039 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
6041 // If the icon is displayed in the AppBar, set it according to the theme.
6042 if (displayAdditionalAppBarIcons) {
6044 refreshMenuItem.setIcon(R.drawable.close_dark);
6046 refreshMenuItem.setIcon(R.drawable.close_light);
6053 public void onPageFinished(WebView view, String url) {
6054 // Flush any cookies to persistent storage. The cookie manager has become very lazy about flushing cookies in recent versions.
6055 if (nestedScrollWebView.getAcceptFirstPartyCookies() && Build.VERSION.SDK_INT >= 21) {
6056 CookieManager.getInstance().flush();
6059 // Update the Refresh menu item if the options menu has been created.
6060 if (optionsMenu != null) {
6061 // Get a handle for the refresh menu item.
6062 MenuItem refreshMenuItem = optionsMenu.findItem(R.id.refresh);
6064 // Reset the Refresh title.
6065 refreshMenuItem.setTitle(R.string.refresh);
6067 // Get the app bar and theme preferences.
6068 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
6069 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
6071 // If the icon is displayed in the AppBar, reset it according to the theme.
6072 if (displayAdditionalAppBarIcons) {
6074 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
6076 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
6081 // Clear the cache and history if Incognito Mode is enabled.
6082 if (incognitoModeEnabled) {
6083 // Clear the cache. `true` includes disk files.
6084 nestedScrollWebView.clearCache(true);
6086 // Clear the back/forward history.
6087 nestedScrollWebView.clearHistory();
6089 // Manually delete cache folders.
6091 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
6092 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
6093 String privateDataDirectoryString = getApplicationInfo().dataDir;
6095 // Delete the main cache directory.
6096 Runtime.getRuntime().exec("rm -rf " + privateDataDirectoryString + "/cache");
6098 // Delete the secondary `Service Worker` cache directory.
6099 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
6100 Runtime.getRuntime().exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
6101 } catch (IOException e) {
6102 // Do nothing if an error is thrown.
6106 // Get the current page position.
6107 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
6109 // Check the current website information against any pinned domain information if the current IP addresses have been loaded.
6110 if ((nestedScrollWebView.hasPinnedSslCertificate() || nestedScrollWebView.hasPinnedIpAddresses()) && nestedScrollWebView.hasCurrentIpAddresses() &&
6111 !nestedScrollWebView.ignorePinnedDomainInformation()) {
6112 CheckPinnedMismatchHelper.checkPinnedMismatch(getSupportFragmentManager(), nestedScrollWebView);
6115 // 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.
6116 String currentUrl = nestedScrollWebView.getUrl();
6118 // Get the current tab.
6119 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
6121 // Update the URL text bar if the page is currently selected and the user is not currently typing in the URL edit text.
6122 // Crash records show that, in some crazy way, it is possible for the current URL to be blank at this point.
6123 // Probably some sort of race condition when Privacy Browser is being resumed.
6124 if ((tabLayout.getSelectedTabPosition() == currentPagePosition) && !urlEditText.hasFocus() && (currentUrl != null)) {
6125 // Check to see if the URL is `about:blank`.
6126 if (currentUrl.equals("about:blank")) { // The WebView is blank.
6127 // Display the hint in the URL edit text.
6128 urlEditText.setText("");
6130 // Request focus for the URL text box.
6131 urlEditText.requestFocus();
6133 // Display the keyboard.
6134 inputMethodManager.showSoftInput(urlEditText, 0);
6136 // Apply the domain settings. This clears any settings from the previous domain.
6137 applyDomainSettings(nestedScrollWebView, "", true, false);
6139 // Only populate the title text view if the tab has been fully created.
6141 // Get the custom view from the tab.
6142 View tabView = tab.getCustomView();
6144 // Remove the incorrect warning below that the current tab view might be null.
6145 assert tabView != null;
6147 // Get the title text view from the tab.
6148 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
6150 // Set the title as the tab text.
6151 tabTitleTextView.setText(R.string.new_tab);
6153 } else { // The WebView has loaded a webpage.
6154 // Update the URL edit text if it is not currently being edited.
6155 if (!urlEditText.hasFocus()) {
6156 // 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.
6157 String sanitizedUrl = sanitizeUrl(currentUrl);
6159 // Display the final URL. Getting the URL from the WebView instead of using the one provided by `onPageFinished()` makes websites like YouTube function correctly.
6160 urlEditText.setText(sanitizedUrl);
6162 // Apply text highlighting to the URL.
6166 // Only populate the title text view if the tab has been fully created.
6168 // Get the custom view from the tab.
6169 View tabView = tab.getCustomView();
6171 // Remove the incorrect warning below that the current tab view might be null.
6172 assert tabView != null;
6174 // Get the title text view from the tab.
6175 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
6177 // Set the title as the tab text. Sometimes `onReceivedTitle()` is not called, especially when navigating history.
6178 tabTitleTextView.setText(nestedScrollWebView.getTitle());
6184 // Handle SSL Certificate errors.
6186 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
6187 // Get the current website SSL certificate.
6188 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
6190 // Extract the individual pieces of information from the current website SSL certificate.
6191 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
6192 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
6193 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
6194 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
6195 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
6196 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
6197 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
6198 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
6200 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
6201 if (nestedScrollWebView.hasPinnedSslCertificate()) {
6202 // Get the pinned SSL certificate.
6203 ArrayList<Object> pinnedSslCertificateArrayList = nestedScrollWebView.getPinnedSslCertificate();
6205 // Extract the arrays from the array list.
6206 String[] pinnedSslCertificateStringArray = (String[]) pinnedSslCertificateArrayList.get(0);
6207 Date[] pinnedSslCertificateDateArray = (Date[]) pinnedSslCertificateArrayList.get(1);
6209 // Check if the current SSL certificate matches the pinned certificate.
6210 if (currentWebsiteIssuedToCName.equals(pinnedSslCertificateStringArray[0]) && currentWebsiteIssuedToOName.equals(pinnedSslCertificateStringArray[1]) &&
6211 currentWebsiteIssuedToUName.equals(pinnedSslCertificateStringArray[2]) && currentWebsiteIssuedByCName.equals(pinnedSslCertificateStringArray[3]) &&
6212 currentWebsiteIssuedByOName.equals(pinnedSslCertificateStringArray[4]) && currentWebsiteIssuedByUName.equals(pinnedSslCertificateStringArray[5]) &&
6213 currentWebsiteSslStartDate.equals(pinnedSslCertificateDateArray[0]) && currentWebsiteSslEndDate.equals(pinnedSslCertificateDateArray[1])) {
6215 // An SSL certificate is pinned and matches the current domain certificate. Proceed to the website without displaying an error.
6218 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
6219 // Store the SSL error handler.
6220 nestedScrollWebView.setSslErrorHandler(handler);
6222 // Instantiate an SSL certificate error alert dialog.
6223 DialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error, nestedScrollWebView.getWebViewFragmentId());
6225 // Show the SSL certificate error dialog.
6226 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
6231 // Check to see if this is the first page.
6232 if (pageNumber == 0) {
6233 // Set this nested scroll WebView as the current WebView.
6234 currentWebView = nestedScrollWebView;
6236 // Apply the app settings from the shared preferences.
6239 // Initialize the URL to load string.
6240 String urlToLoadString;
6242 // Get the intent that started the app.
6243 Intent launchingIntent = getIntent();
6245 // Get the information from the intent.
6246 String launchingIntentAction = launchingIntent.getAction();
6247 Uri launchingIntentUriData = launchingIntent.getData();
6249 // Parse the launching intent URL.
6250 if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) { // The intent contains a search string.
6251 // Create an encoded URL string.
6252 String encodedUrlString;
6254 // Sanitize the search input and convert it to a search.
6256 encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
6257 } catch (UnsupportedEncodingException exception) {
6258 encodedUrlString = "";
6261 // Store the web search as the URL to load.
6262 urlToLoadString = searchURL + encodedUrlString;
6263 } else if (launchingIntentUriData != null){ // The intent contains a URL.
6265 urlToLoadString = launchingIntentUriData.toString();
6266 } else { // The is no URL in the intent.
6267 // Store the homepage to be loaded.
6268 urlToLoadString = sharedPreferences.getString("homepage", getString(R.string.homepage_default_value));
6271 // Load the website if not waiting for the proxy.
6272 if (waitingForProxy) { // Store the URL to be loaded in the Nested Scroll WebView.
6273 nestedScrollWebView.setWaitingForProxyUrlString(urlToLoadString);
6274 } else { // Load the URL.
6275 loadUrl(nestedScrollWebView, urlToLoadString);
6277 } else { // This is not the first tab.
6278 // Apply the domain settings.
6279 applyDomainSettings(nestedScrollWebView, url, false, false);
6282 nestedScrollWebView.loadUrl(url, customHeaders);
6284 // Set the focus and display the keyboard if the URL is blank.
6285 if (url.equals("")) {
6286 // Request focus for the URL text box.
6287 urlEditText.requestFocus();
6289 // Create a display keyboard handler.
6290 Handler displayKeyboardHandler = new Handler();
6292 // Create a display keyboard runnable.
6293 Runnable displayKeyboardRunnable = () -> {
6294 // Display the keyboard.
6295 inputMethodManager.showSoftInput(urlEditText, 0);
6298 // Display the keyboard after 100 milliseconds, which leaves enough time for the tab to transition.
6299 displayKeyboardHandler.postDelayed(displayKeyboardRunnable, 100);