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.util.TypedValue;
62 import android.view.ContextMenu;
63 import android.view.GestureDetector;
64 import android.view.KeyEvent;
65 import android.view.Menu;
66 import android.view.MenuItem;
67 import android.view.MotionEvent;
68 import android.view.View;
69 import android.view.ViewGroup;
70 import android.view.WindowManager;
71 import android.view.inputmethod.InputMethodManager;
72 import android.webkit.CookieManager;
73 import android.webkit.HttpAuthHandler;
74 import android.webkit.SslErrorHandler;
75 import android.webkit.ValueCallback;
76 import android.webkit.WebBackForwardList;
77 import android.webkit.WebChromeClient;
78 import android.webkit.WebResourceResponse;
79 import android.webkit.WebSettings;
80 import android.webkit.WebStorage;
81 import android.webkit.WebView;
82 import android.webkit.WebViewClient;
83 import android.webkit.WebViewDatabase;
84 import android.widget.ArrayAdapter;
85 import android.widget.CursorAdapter;
86 import android.widget.EditText;
87 import android.widget.FrameLayout;
88 import android.widget.ImageView;
89 import android.widget.LinearLayout;
90 import android.widget.ListView;
91 import android.widget.ProgressBar;
92 import android.widget.RadioButton;
93 import android.widget.RelativeLayout;
94 import android.widget.TextView;
96 import androidx.annotation.NonNull;
97 import androidx.appcompat.app.ActionBar;
98 import androidx.appcompat.app.ActionBarDrawerToggle;
99 import androidx.appcompat.app.AppCompatActivity;
100 import androidx.appcompat.app.AppCompatDelegate;
101 import androidx.appcompat.widget.Toolbar;
102 import androidx.coordinatorlayout.widget.CoordinatorLayout;
103 import androidx.core.app.ActivityCompat;
104 import androidx.core.content.ContextCompat;
105 import androidx.core.view.GravityCompat;
106 import androidx.drawerlayout.widget.DrawerLayout;
107 import androidx.fragment.app.DialogFragment;
108 import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
109 import androidx.viewpager.widget.ViewPager;
110 import androidx.webkit.WebSettingsCompat;
111 import androidx.webkit.WebViewFeature;
113 import com.google.android.material.appbar.AppBarLayout;
114 import com.google.android.material.floatingactionbutton.FloatingActionButton;
115 import com.google.android.material.navigation.NavigationView;
116 import com.google.android.material.snackbar.Snackbar;
117 import com.google.android.material.tabs.TabLayout;
119 import com.stoutner.privacybrowser.BuildConfig;
120 import com.stoutner.privacybrowser.R;
121 import com.stoutner.privacybrowser.adapters.WebViewPagerAdapter;
122 import com.stoutner.privacybrowser.asynctasks.GetHostIpAddresses;
123 import com.stoutner.privacybrowser.asynctasks.PopulateBlocklists;
124 import com.stoutner.privacybrowser.asynctasks.PrepareSaveDialog;
125 import com.stoutner.privacybrowser.asynctasks.SaveUrl;
126 import com.stoutner.privacybrowser.asynctasks.SaveWebpageImage;
127 import com.stoutner.privacybrowser.dialogs.AdConsentDialog;
128 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
129 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
130 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
131 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
132 import com.stoutner.privacybrowser.dialogs.FontSizeDialog;
133 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
134 import com.stoutner.privacybrowser.dialogs.OpenDialog;
135 import com.stoutner.privacybrowser.dialogs.ProxyNotInstalledDialog;
136 import com.stoutner.privacybrowser.dialogs.PinnedMismatchDialog;
137 import com.stoutner.privacybrowser.dialogs.SaveDialog;
138 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
139 import com.stoutner.privacybrowser.dialogs.StoragePermissionDialog;
140 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
141 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
142 import com.stoutner.privacybrowser.dialogs.WaitingForProxyDialog;
143 import com.stoutner.privacybrowser.fragments.WebViewTabFragment;
144 import com.stoutner.privacybrowser.helpers.AdHelper;
145 import com.stoutner.privacybrowser.helpers.BlocklistHelper;
146 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
147 import com.stoutner.privacybrowser.helpers.CheckPinnedMismatchHelper;
148 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
149 import com.stoutner.privacybrowser.helpers.FileNameHelper;
150 import com.stoutner.privacybrowser.helpers.ProxyHelper;
151 import com.stoutner.privacybrowser.views.NestedScrollWebView;
153 import java.io.ByteArrayInputStream;
154 import java.io.ByteArrayOutputStream;
156 import java.io.IOException;
157 import java.io.UnsupportedEncodingException;
158 import java.net.MalformedURLException;
160 import java.net.URLDecoder;
161 import java.net.URLEncoder;
162 import java.text.NumberFormat;
163 import java.util.ArrayList;
164 import java.util.Date;
165 import java.util.HashMap;
166 import java.util.HashSet;
167 import java.util.List;
168 import java.util.Map;
169 import java.util.Objects;
170 import java.util.Set;
172 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
173 EditBookmarkFolderDialog.EditBookmarkFolderListener, FontSizeDialog.UpdateFontSizeListener, NavigationView.OnNavigationItemSelectedListener, OpenDialog.OpenListener,
174 PinnedMismatchDialog.PinnedMismatchListener, PopulateBlocklists.PopulateBlocklistsListener, SaveDialog.SaveWebpageListener, StoragePermissionDialog.StoragePermissionDialogListener,
175 UrlHistoryDialog.NavigateHistoryListener, WebViewTabFragment.NewTabListener {
177 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`, `onResume()`, and `applyProxy()`.
178 public static String orbotStatus = "unknown";
180 // The WebView pager adapter is accessed from `HttpAuthenticationDialog`, `PinnedMismatchDialog`, and `SslCertificateErrorDialog`. It is also used in `onCreate()`, `onResume()`, and `addTab()`.
181 public static WebViewPagerAdapter webViewPagerAdapter;
183 // The load URL on restart variables are public static so they can be accessed from `BookmarksActivity`. They are used in `onRestart()`.
184 public static boolean loadUrlOnRestart;
185 public static String urlToLoadOnRestart;
187 // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onRestart()`.
188 public static boolean restartFromBookmarksActivity;
190 // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
191 // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
192 public static String currentBookmarksFolder;
194 // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
195 public final static int UNRECOGNIZED_USER_AGENT = -1;
196 public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
197 public final static int SETTINGS_CUSTOM_USER_AGENT = 12;
198 public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
199 public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
200 public final static int DOMAINS_CUSTOM_USER_AGENT = 13;
202 // Start activity for result request codes. The public static entries are accessed from `OpenDialog()` and `SaveWebpageDialog()`.
203 public final static int BROWSE_OPEN_REQUEST_CODE = 0;
204 public final static int BROWSE_SAVE_WEBPAGE_REQUEST_CODE = 1;
205 private final int BROWSE_FILE_UPLOAD_REQUEST_CODE = 2;
207 // The proxy mode is public static so it can be accessed from `ProxyHelper()`.
208 // It is also used in `onRestart()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `applyAppSettings()`, and `applyProxy()`.
209 // It will be updated in `applyAppSettings()`, but it needs to be initialized here or the first run of `onPrepareOptionsMenu()` crashes.
210 public static String proxyMode = ProxyHelper.NONE;
213 // The permission result request codes are used in `onCreateContextMenu()`, `onRequestPermissionResult()`, `onSaveWebpage()`, `onCloseStoragePermissionDialog()`, and `initializeWebView()`.
214 private final int PERMISSION_OPEN_REQUEST_CODE = 0;
215 private final int PERMISSION_SAVE_URL_REQUEST_CODE = 1;
216 private final int PERMISSION_SAVE_AS_ARCHIVE_REQUEST_CODE = 2;
217 private final int PERMISSION_SAVE_AS_IMAGE_REQUEST_CODE = 3;
219 // The current WebView is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
220 // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, `applyProxy()`, and `applyDomainSettings()`.
221 private NestedScrollWebView currentWebView;
223 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
224 private final Map<String, String> customHeaders = new HashMap<>();
226 // The search URL is set in `applyAppSettings()` and used in `onNewIntent()`, `loadUrlFromTextBox()`, `initializeApp()`, and `initializeWebView()`.
227 private String searchURL;
229 // The options menu is set in `onCreateOptionsMenu()` and used in `onOptionsItemSelected()`, `updatePrivacyIcons()`, and `initializeWebView()`.
230 private Menu optionsMenu;
232 // The blocklists are populated in `finishedPopulatingBlocklists()` and accessed from `initializeWebView()`.
233 private ArrayList<List<String[]>> easyList;
234 private ArrayList<List<String[]>> easyPrivacy;
235 private ArrayList<List<String[]>> fanboysAnnoyanceList;
236 private ArrayList<List<String[]>> fanboysSocialList;
237 private ArrayList<List<String[]>> ultraList;
238 private ArrayList<List<String[]>> ultraPrivacy;
240 // `webViewDefaultUserAgent` is used in `onCreate()` and `onPrepareOptionsMenu()`.
241 private String webViewDefaultUserAgent;
243 // The incognito mode is set in `applyAppSettings()` and used in `initializeWebView()`.
244 private boolean incognitoModeEnabled;
246 // The full screen browsing mode tracker is set it `applyAppSettings()` and used in `initializeWebView()`.
247 private boolean fullScreenBrowsingModeEnabled;
249 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
250 private boolean inFullScreenBrowsingMode;
252 // The app bar trackers are set in `applyAppSettings()` and used in `initializeWebView()`.
253 private boolean hideAppBar;
254 private boolean scrollAppBar;
256 // The loading new intent tracker is set in `onNewIntent()` and used in `setCurrentWebView()`.
257 private boolean loadingNewIntent;
259 // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
260 private boolean reapplyDomainSettingsOnRestart;
262 // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
263 private boolean reapplyAppSettingsOnRestart;
265 // `displayingFullScreenVideo` is used in `onCreate()` and `onResume()`.
266 private boolean displayingFullScreenVideo;
268 // `orbotStatusBroadcastReceiver` is used in `onCreate()` and `onDestroy()`.
269 private BroadcastReceiver orbotStatusBroadcastReceiver;
271 // The waiting for proxy boolean is used in `onResume()`, `initializeApp()` and `applyProxy()`.
272 private boolean waitingForProxy = false;
274 // The action bar drawer toggle is initialized in `onCreate()` and used in `onResume()`.
275 private ActionBarDrawerToggle actionBarDrawerToggle;
277 // The color spans are used in `onCreate()` and `highlightUrlText()`.
278 private ForegroundColorSpan redColorSpan;
279 private ForegroundColorSpan initialGrayColorSpan;
280 private ForegroundColorSpan finalGrayColorSpan;
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 appBarHeight;
300 private int defaultProgressViewStartOffset;
301 private int defaultProgressViewEndOffset;
303 // The URL sanitizers are set in `applyAppSettings()` and used in `sanitizeUrl()`.
304 private boolean sanitizeGoogleAnalytics;
305 private boolean sanitizeFacebookClickIds;
306 private boolean sanitizeTwitterAmpRedirects;
308 // The file path strings are used in `onSaveWebpage()` and `onRequestPermissionResult()`
309 private String openFilePath;
310 private String saveWebpageUrl;
311 private String saveWebpageFilePath;
314 // Remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
315 @SuppressLint("ClickableViewAccessibility")
316 protected void onCreate(Bundle savedInstanceState) {
317 // Run the default commands.
318 super.onCreate(savedInstanceState);
320 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
321 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
323 // Get a handle for the shared preferences.
324 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
326 // Get the screenshot preference.
327 String appTheme = sharedPreferences.getString("app_theme", getString(R.string.app_theme_default_value));
328 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
330 // Get the theme entry values string array.
331 String[] appThemeEntryValuesStringArray = getResources().getStringArray(R.array.app_theme_entry_values);
333 // Set the app theme according to the preference. A switch statement cannot be used because the theme entry values string array is not a compile time constant.
334 if (appTheme.equals(appThemeEntryValuesStringArray[1])) { // The light theme is selected.
335 // Apply the light theme.
336 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
337 } else if (appTheme.equals(appThemeEntryValuesStringArray[2])) { // The dark theme is selected.
338 // Apply the dark theme.
339 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
340 } else { // The system default theme is selected.
341 if (Build.VERSION.SDK_INT >= 28) { // The system default theme is supported.
342 // Follow the system default theme.
343 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
344 } else { // The system default theme is not supported.
345 // Follow the battery saver mode.
346 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
350 // Disable screenshots if not allowed.
351 if (!allowScreenshots) {
352 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
355 // Enable the drawing of the entire webpage. This makes it possible to save a website image. This must be done before anything else happens with the WebView.
356 if (Build.VERSION.SDK_INT >= 21) {
357 WebView.enableSlowWholeDocumentDraw();
361 setTheme(R.style.PrivacyBrowser);
363 // Set the content view.
364 setContentView(R.layout.main_framelayout);
366 // Get handles for the views that need to be modified.
367 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
368 Toolbar toolbar = findViewById(R.id.toolbar);
369 ViewPager webViewPager = findViewById(R.id.webviewpager);
371 // Get a handle for the app compat delegate.
372 AppCompatDelegate appCompatDelegate = getDelegate();
374 // Set the support action bar.
375 appCompatDelegate.setSupportActionBar(toolbar);
377 // Get a handle for the action bar.
378 ActionBar actionBar = appCompatDelegate.getSupportActionBar();
380 // This is needed to get rid of the Android Studio warning that the action bar might be null.
381 assert actionBar != null;
383 // Add the custom layout, which shows the URL text bar.
384 actionBar.setCustomView(R.layout.url_app_bar);
385 actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
387 // Create the hamburger icon at the start of the AppBar.
388 actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
390 // Initially disable the sliding drawers. They will be enabled once the blocklists are loaded.
391 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
393 // Initialize the web view pager adapter.
394 webViewPagerAdapter = new WebViewPagerAdapter(getSupportFragmentManager());
396 // Set the pager adapter on the web view pager.
397 webViewPager.setAdapter(webViewPagerAdapter);
399 // Store up to 100 tabs in memory.
400 webViewPager.setOffscreenPageLimit(100);
402 // Populate the blocklists.
403 new PopulateBlocklists(this, this).execute();
407 protected void onNewIntent(Intent intent) {
408 // Run the default commands.
409 super.onNewIntent(intent);
411 // Replace the intent that started the app with this one.
414 // 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()`.
415 if (ultraPrivacy != null) {
416 // Get the information from the intent.
417 String intentAction = intent.getAction();
418 Uri intentUriData = intent.getData();
420 // Determine if this is a web search.
421 boolean isWebSearch = ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH));
423 // 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.
424 if (intentUriData != null || isWebSearch) {
425 // Get the shared preferences.
426 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
428 // Create a URL string.
431 // If the intent action is a web search, perform the search.
433 // Create an encoded URL string.
434 String encodedUrlString;
436 // Sanitize the search input and convert it to a search.
438 encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
439 } catch (UnsupportedEncodingException exception) {
440 encodedUrlString = "";
443 // Add the base search URL.
444 url = searchURL + encodedUrlString;
445 } else { // The intent should contain a URL.
446 // Set the intent data as the URL.
447 url = intentUriData.toString();
450 // Add a new tab if specified in the preferences.
451 if (sharedPreferences.getBoolean("open_intents_in_new_tab", true)) { // Load the URL in a new tab.
452 // Set the loading new intent flag.
453 loadingNewIntent = true;
456 addNewTab(url, true);
457 } else { // Load the URL in the current tab.
459 loadUrl(currentWebView, url);
462 // Get a handle for the drawer layout.
463 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
465 // Close the navigation drawer if it is open.
466 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
467 drawerLayout.closeDrawer(GravityCompat.START);
470 // Close the bookmarks drawer if it is open.
471 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
472 drawerLayout.closeDrawer(GravityCompat.END);
479 public void onRestart() {
480 // Run the default commands.
483 // Apply the app settings if returning from the Settings activity.
484 if (reapplyAppSettingsOnRestart) {
485 // Reset the reapply app settings on restart tracker.
486 reapplyAppSettingsOnRestart = false;
488 // Apply the app settings.
492 // Apply the domain settings if returning from the settings or domains activity.
493 if (reapplyDomainSettingsOnRestart) {
494 // Reset the reapply domain settings on restart tracker.
495 reapplyDomainSettingsOnRestart = false;
497 // Reapply the domain settings for each tab.
498 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
499 // Get the WebView tab fragment.
500 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
502 // Get the fragment view.
503 View fragmentView = webViewTabFragment.getView();
505 // Only reload the WebViews if they exist.
506 if (fragmentView != null) {
507 // Get the nested scroll WebView from the tab fragment.
508 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
510 // Reset the current domain name so the domain settings will be reapplied.
511 nestedScrollWebView.resetCurrentDomainName();
513 // Reapply the domain settings if the URL is not null, which can happen if an empty tab is active when returning from settings.
514 if (nestedScrollWebView.getUrl() != null) {
515 applyDomainSettings(nestedScrollWebView, nestedScrollWebView.getUrl(), false, true);
521 // Load the URL on restart (used when loading a bookmark).
522 if (loadUrlOnRestart) {
523 // Load the specified URL.
524 loadUrl(currentWebView, urlToLoadOnRestart);
526 // Reset the load on restart tracker.
527 loadUrlOnRestart = false;
530 // Update the bookmarks drawer if returning from the Bookmarks activity.
531 if (restartFromBookmarksActivity) {
532 // Get a handle for the drawer layout.
533 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
535 // Close the bookmarks drawer.
536 drawerLayout.closeDrawer(GravityCompat.END);
538 // Reload the bookmarks drawer.
539 loadBookmarksFolder();
541 // Reset `restartFromBookmarksActivity`.
542 restartFromBookmarksActivity = false;
545 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
546 updatePrivacyIcons(true);
549 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
551 public void onResume() {
552 // Run the default commands.
555 // Resume any WebViews.
556 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
557 // Get the WebView tab fragment.
558 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
560 // Get the fragment view.
561 View fragmentView = webViewTabFragment.getView();
563 // Only resume the WebViews if they exist (they won't when the app is first created).
564 if (fragmentView != null) {
565 // Get the nested scroll WebView from the tab fragment.
566 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
568 // Resume the nested scroll WebView JavaScript timers.
569 nestedScrollWebView.resumeTimers();
571 // Resume the nested scroll WebView.
572 nestedScrollWebView.onResume();
576 // Reapply the proxy settings if the system is using a proxy. This redisplays the appropriate alert dialog.
577 if (!proxyMode.equals(ProxyHelper.NONE)) {
581 // Reapply any system UI flags and the ad in the free flavor.
582 if (displayingFullScreenVideo || inFullScreenBrowsingMode) { // The system is displaying a website or a video in full screen mode.
583 // Get a handle for the root frame layouts.
584 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
586 /* Hide the system bars.
587 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
588 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
589 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
590 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
592 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
593 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
594 } else if (BuildConfig.FLAVOR.contentEquals("free")) { // The system in not in full screen mode.
596 AdHelper.resumeAd(findViewById(R.id.adview));
601 public void onPause() {
602 // Run the default commands.
605 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
606 // Get the WebView tab fragment.
607 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
609 // Get the fragment view.
610 View fragmentView = webViewTabFragment.getView();
612 // Only pause the WebViews if they exist (they won't when the app is first created).
613 if (fragmentView != null) {
614 // Get the nested scroll WebView from the tab fragment.
615 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
617 // Pause the nested scroll WebView.
618 nestedScrollWebView.onPause();
620 // Pause the nested scroll WebView JavaScript timers.
621 nestedScrollWebView.pauseTimers();
625 // Pause the ad or it will continue to consume resources in the background on the free flavor.
626 if (BuildConfig.FLAVOR.contentEquals("free")) {
628 AdHelper.pauseAd(findViewById(R.id.adview));
633 public void onDestroy() {
634 // Unregister the orbot status broadcast receiver if it exists.
635 if (orbotStatusBroadcastReceiver != null) {
636 this.unregisterReceiver(orbotStatusBroadcastReceiver);
639 // Close the bookmarks cursor if it exists.
640 if (bookmarksCursor != null) {
641 bookmarksCursor.close();
644 // Close the bookmarks database if it exists.
645 if (bookmarksDatabaseHelper != null) {
646 bookmarksDatabaseHelper.close();
649 // Run the default commands.
654 public boolean onCreateOptionsMenu(Menu menu) {
655 // Inflate the menu. This adds items to the action bar if it is present.
656 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
658 // Store a handle for the options menu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons()`.
661 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
662 updatePrivacyIcons(false);
664 // Get handles for the menu items.
665 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
666 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
667 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
668 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
669 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
670 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
671 MenuItem darkWebViewMenuItem = menu.findItem(R.id.dark_webview);
672 MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
674 // Only display third-party cookies if API >= 21
675 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
677 // Only display the form data menu items if the API < 26.
678 toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
679 clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
681 // Disable the clear form data menu item if the API >= 26 so that the status of the main Clear Data is calculated correctly.
682 clearFormDataMenuItem.setEnabled(Build.VERSION.SDK_INT < 26);
684 // Only display the dark WebView menu item if API >= 21.
685 darkWebViewMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
687 // Only show Ad Consent if this is the free flavor.
688 adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
690 // Get the shared preferences.
691 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
693 // Get the dark theme and app bar preferences..
694 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
696 // 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.
697 if (displayAdditionalAppBarIcons) {
698 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
699 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
700 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
701 } else { //Do not display the additional icons.
702 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
703 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
704 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
707 // Replace Refresh with Stop if a URL is already loading.
708 if (currentWebView != null && currentWebView.getProgress() != 100) {
710 refreshMenuItem.setTitle(R.string.stop);
712 // Set the icon if it is displayed in the app bar.
713 if (displayAdditionalAppBarIcons) {
714 // Get the current theme status.
715 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
717 // Set the icon according to the current theme status.
718 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES) {
719 // Set the dark stop icon.
720 refreshMenuItem.setIcon(R.drawable.close_night);
722 // Set the light stop icon.
723 refreshMenuItem.setIcon(R.drawable.close_day);
733 public boolean onPrepareOptionsMenu(Menu menu) {
734 // Get handles for the menu items.
735 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
736 MenuItem firstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
737 MenuItem thirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
738 MenuItem domStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
739 MenuItem saveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
740 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
741 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
742 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
743 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
744 MenuItem blocklistsMenuItem = menu.findItem(R.id.blocklists);
745 MenuItem easyListMenuItem = menu.findItem(R.id.easylist);
746 MenuItem easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
747 MenuItem fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
748 MenuItem fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
749 MenuItem ultraListMenuItem = menu.findItem(R.id.ultralist);
750 MenuItem ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
751 MenuItem blockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
752 MenuItem proxyMenuItem = menu.findItem(R.id.proxy);
753 MenuItem userAgentMenuItem = menu.findItem(R.id.user_agent);
754 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
755 MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
756 MenuItem wideViewportMenuItem = menu.findItem(R.id.wide_viewport);
757 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
758 MenuItem darkWebViewMenuItem = menu.findItem(R.id.dark_webview);
760 // Get a handle for the cookie manager.
761 CookieManager cookieManager = CookieManager.getInstance();
763 // Initialize the current user agent string and the font size.
764 String currentUserAgent = getString(R.string.user_agent_privacy_browser);
767 // 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.
768 if (currentWebView != null) {
769 // Set the add or edit domain text.
770 if (currentWebView.getDomainSettingsApplied()) {
771 addOrEditDomain.setTitle(R.string.edit_domain_settings);
773 addOrEditDomain.setTitle(R.string.add_domain_settings);
776 // Get the current user agent from the WebView.
777 currentUserAgent = currentWebView.getSettings().getUserAgentString();
779 // Get the current font size from the
780 fontSize = currentWebView.getSettings().getTextZoom();
782 // Set the status of the menu item checkboxes.
783 domStorageMenuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
784 saveFormDataMenuItem.setChecked(currentWebView.getSettings().getSaveFormData()); // Form data can be removed once the minimum API >= 26.
785 easyListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
786 easyPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
787 fanboysAnnoyanceListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
788 fanboysSocialBlockingListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
789 ultraListMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
790 ultraPrivacyMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
791 blockAllThirdPartyRequestsMenuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
792 swipeToRefreshMenuItem.setChecked(currentWebView.getSwipeToRefresh());
793 wideViewportMenuItem.setChecked(currentWebView.getSettings().getUseWideViewPort());
794 displayImagesMenuItem.setChecked(currentWebView.getSettings().getLoadsImagesAutomatically());
796 // Initialize the display names for the blocklists with the number of blocked requests.
797 blocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
798 easyListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYLIST) + " - " + getString(R.string.easylist));
799 easyPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.EASYPRIVACY) + " - " + getString(R.string.easyprivacy));
800 fanboysAnnoyanceListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " + getString(R.string.fanboys_annoyance_list));
801 fanboysSocialBlockingListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " + getString(R.string.fanboys_social_blocking_list));
802 ultraListMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRALIST) + " - " + getString(R.string.ultralist));
803 ultraPrivacyMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.ULTRAPRIVACY) + " - " + getString(R.string.ultraprivacy));
804 blockAllThirdPartyRequestsMenuItem.setTitle(currentWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " + getString(R.string.block_all_third_party_requests));
806 // Only modify third-party cookies if the API >= 21.
807 if (Build.VERSION.SDK_INT >= 21) {
808 // Set the status of the third-party cookies checkbox.
809 thirdPartyCookiesMenuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
811 // Enable third-party cookies if first-party cookies are enabled.
812 thirdPartyCookiesMenuItem.setEnabled(cookieManager.acceptCookie());
815 // Enable DOM Storage if JavaScript is enabled.
816 domStorageMenuItem.setEnabled(currentWebView.getSettings().getJavaScriptEnabled());
818 // Set the checkbox status for dark WebView if the WebView supports it.
819 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
820 darkWebViewMenuItem.setChecked(WebSettingsCompat.getForceDark(currentWebView.getSettings()) == WebSettingsCompat.FORCE_DARK_ON);
824 // Set the checked status of the first party cookies menu item.
825 firstPartyCookiesMenuItem.setChecked(cookieManager.acceptCookie());
827 // Enable Clear Cookies if there are any.
828 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
830 // 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`.
831 String privateDataDirectoryString = getApplicationInfo().dataDir;
833 // Get a count of the number of files in the Local Storage directory.
834 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
835 int localStorageDirectoryNumberOfFiles = 0;
836 if (localStorageDirectory.exists()) {
837 // `Objects.requireNonNull` removes a lint warning that `localStorageDirectory.list` might produce a null pointed exception if it is dereferenced.
838 localStorageDirectoryNumberOfFiles = Objects.requireNonNull(localStorageDirectory.list()).length;
841 // Get a count of the number of files in the IndexedDB directory.
842 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
843 int indexedDBDirectoryNumberOfFiles = 0;
844 if (indexedDBDirectory.exists()) {
845 // `Objects.requireNonNull` removes a lint warning that `indexedDBDirectory.list` might produce a null pointed exception if it is dereferenced.
846 indexedDBDirectoryNumberOfFiles = Objects.requireNonNull(indexedDBDirectory.list()).length;
849 // Enable Clear DOM Storage if there is any.
850 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
852 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
853 if (Build.VERSION.SDK_INT < 26) {
854 // Get the WebView database.
855 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
857 // Enable the clear form data menu item if there is anything to clear.
858 clearFormDataMenuItem.setEnabled(webViewDatabase.hasFormData());
861 // Enable Clear Data if any of the submenu items are enabled.
862 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
864 // Disable Fanboy's Social Blocking List menu item if Fanboy's Annoyance List is checked.
865 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListMenuItem.isChecked());
867 // Set the proxy title and check the applied proxy.
869 case ProxyHelper.NONE:
870 // Set the proxy title.
871 proxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_none));
873 // Check the proxy None radio button.
874 menu.findItem(R.id.proxy_none).setChecked(true);
877 case ProxyHelper.TOR:
878 // Set the proxy title.
879 proxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_tor));
881 // Check the proxy Tor radio button.
882 menu.findItem(R.id.proxy_tor).setChecked(true);
885 case ProxyHelper.I2P:
886 // Set the proxy title.
887 proxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_i2p));
889 // Check the proxy I2P radio button.
890 menu.findItem(R.id.proxy_i2p).setChecked(true);
893 case ProxyHelper.CUSTOM:
894 // Set the proxy title.
895 proxyMenuItem.setTitle(getString(R.string.proxy) + " - " + getString(R.string.proxy_custom));
897 // Check the proxy Custom radio button.
898 menu.findItem(R.id.proxy_custom).setChecked(true);
902 // Select the current user agent menu item. A switch statement cannot be used because the user agents are not compile time constants.
903 if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) { // Privacy Browser.
904 // Update the user agent menu item title.
905 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_privacy_browser));
907 // Select the Privacy Browser radio box.
908 menu.findItem(R.id.user_agent_privacy_browser).setChecked(true);
909 } else if (currentUserAgent.equals(webViewDefaultUserAgent)) { // WebView Default.
910 // Update the user agent menu item title.
911 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_webview_default));
913 // Select the WebView Default radio box.
914 menu.findItem(R.id.user_agent_webview_default).setChecked(true);
915 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) { // Firefox on Android.
916 // Update the user agent menu item title.
917 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_android));
919 // Select the Firefox on Android radio box.
920 menu.findItem(R.id.user_agent_firefox_on_android).setChecked(true);
921 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) { // Chrome on Android.
922 // Update the user agent menu item title.
923 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_android));
925 // Select the Chrome on Android radio box.
926 menu.findItem(R.id.user_agent_chrome_on_android).setChecked(true);
927 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) { // Safari on iOS.
928 // Update the user agent menu item title.
929 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_ios));
931 // Select the Safari on iOS radio box.
932 menu.findItem(R.id.user_agent_safari_on_ios).setChecked(true);
933 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) { // Firefox on Linux.
934 // Update the user agent menu item title.
935 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_linux));
937 // Select the Firefox on Linux radio box.
938 menu.findItem(R.id.user_agent_firefox_on_linux).setChecked(true);
939 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) { // Chromium on Linux.
940 // Update the user agent menu item title.
941 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chromium_on_linux));
943 // Select the Chromium on Linux radio box.
944 menu.findItem(R.id.user_agent_chromium_on_linux).setChecked(true);
945 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) { // Firefox on Windows.
946 // Update the user agent menu item title.
947 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_firefox_on_windows));
949 // Select the Firefox on Windows radio box.
950 menu.findItem(R.id.user_agent_firefox_on_windows).setChecked(true);
951 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) { // Chrome on Windows.
952 // Update the user agent menu item title.
953 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_chrome_on_windows));
955 // Select the Chrome on Windows radio box.
956 menu.findItem(R.id.user_agent_chrome_on_windows).setChecked(true);
957 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) { // Edge on Windows.
958 // Update the user agent menu item title.
959 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_edge_on_windows));
961 // Select the Edge on Windows radio box.
962 menu.findItem(R.id.user_agent_edge_on_windows).setChecked(true);
963 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) { // Internet Explorer on Windows.
964 // Update the user agent menu item title.
965 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_internet_explorer_on_windows));
967 // Select the Internet on Windows radio box.
968 menu.findItem(R.id.user_agent_internet_explorer_on_windows).setChecked(true);
969 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) { // Safari on macOS.
970 // Update the user agent menu item title.
971 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_safari_on_macos));
973 // Select the Safari on macOS radio box.
974 menu.findItem(R.id.user_agent_safari_on_macos).setChecked(true);
975 } else { // Custom user agent.
976 // Update the user agent menu item title.
977 userAgentMenuItem.setTitle(getString(R.string.options_user_agent) + " - " + getString(R.string.user_agent_custom));
979 // Select the Custom radio box.
980 menu.findItem(R.id.user_agent_custom).setChecked(true);
983 // Set the font size title.
984 fontSizeMenuItem.setTitle(getString(R.string.font_size) + " - " + fontSize + "%");
986 // Run all the other default commands.
987 super.onPrepareOptionsMenu(menu);
994 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
995 @SuppressLint("SetJavaScriptEnabled")
996 public boolean onOptionsItemSelected(MenuItem menuItem) {
997 // Get the selected menu item ID.
998 int menuItemId = menuItem.getItemId();
1000 // Get a handle for the shared preferences.
1001 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1003 // Get a handle for the cookie manager.
1004 CookieManager cookieManager = CookieManager.getInstance();
1006 // Run the commands that correlate to the selected menu item.
1007 switch (menuItemId) {
1008 case R.id.toggle_javascript:
1009 // Toggle the JavaScript status.
1010 currentWebView.getSettings().setJavaScriptEnabled(!currentWebView.getSettings().getJavaScriptEnabled());
1012 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1013 updatePrivacyIcons(true);
1015 // Display a `Snackbar`.
1016 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScrip is enabled.
1017 Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1018 } else if (cookieManager.acceptCookie()) { // JavaScript is disabled, but first-party cookies are enabled.
1019 Snackbar.make(findViewById(R.id.webviewpager), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1020 } else { // Privacy mode.
1021 Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1024 // Reload the current WebView.
1025 currentWebView.reload();
1027 // Consume the event.
1031 if (menuItem.getTitle().equals(getString(R.string.refresh))) { // The refresh button was pushed.
1032 // Reload the current WebView.
1033 currentWebView.reload();
1034 } else { // The stop button was pushed.
1035 // Stop the loading of the WebView.
1036 currentWebView.stopLoading();
1039 // Consume the event.
1042 case R.id.bookmarks:
1043 // Get a handle for the drawer layout.
1044 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
1046 // Open the bookmarks drawer.
1047 drawerLayout.openDrawer(GravityCompat.END);
1049 // Consume the event.
1052 case R.id.toggle_first_party_cookies:
1053 // Switch the first-party cookie status.
1054 cookieManager.setAcceptCookie(!cookieManager.acceptCookie());
1056 // Store the first-party cookie status.
1057 currentWebView.setAcceptFirstPartyCookies(cookieManager.acceptCookie());
1059 // Update the menu checkbox.
1060 menuItem.setChecked(cookieManager.acceptCookie());
1062 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1063 updatePrivacyIcons(true);
1065 // Display a snackbar.
1066 if (cookieManager.acceptCookie()) { // First-party cookies are enabled.
1067 Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1068 } else if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is still enabled.
1069 Snackbar.make(findViewById(R.id.webviewpager), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1070 } else { // Privacy mode.
1071 Snackbar.make(findViewById(R.id.webviewpager), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1074 // Reload the current WebView.
1075 currentWebView.reload();
1077 // Consume the event.
1080 case R.id.toggle_third_party_cookies:
1081 if (Build.VERSION.SDK_INT >= 21) {
1082 // Switch the status of thirdPartyCookiesEnabled.
1083 cookieManager.setAcceptThirdPartyCookies(currentWebView, !cookieManager.acceptThirdPartyCookies(currentWebView));
1085 // Update the menu checkbox.
1086 menuItem.setChecked(cookieManager.acceptThirdPartyCookies(currentWebView));
1088 // Display a snackbar.
1089 if (cookieManager.acceptThirdPartyCookies(currentWebView)) {
1090 Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1092 Snackbar.make(findViewById(R.id.webviewpager), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1095 // Reload the current WebView.
1096 currentWebView.reload();
1097 } // Else do nothing because SDK < 21.
1099 // Consume the event.
1102 case R.id.toggle_dom_storage:
1103 // Toggle the status of domStorageEnabled.
1104 currentWebView.getSettings().setDomStorageEnabled(!currentWebView.getSettings().getDomStorageEnabled());
1106 // Update the menu checkbox.
1107 menuItem.setChecked(currentWebView.getSettings().getDomStorageEnabled());
1109 // Update the privacy icon. `true` refreshes the app bar icons.
1110 updatePrivacyIcons(true);
1112 // Display a snackbar.
1113 if (currentWebView.getSettings().getDomStorageEnabled()) {
1114 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1116 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1119 // Reload the current WebView.
1120 currentWebView.reload();
1122 // Consume the event.
1125 // Form data can be removed once the minimum API >= 26.
1126 case R.id.toggle_save_form_data:
1127 // Switch the status of saveFormDataEnabled.
1128 currentWebView.getSettings().setSaveFormData(!currentWebView.getSettings().getSaveFormData());
1130 // Update the menu checkbox.
1131 menuItem.setChecked(currentWebView.getSettings().getSaveFormData());
1133 // Display a snackbar.
1134 if (currentWebView.getSettings().getSaveFormData()) {
1135 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1137 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1140 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1141 updatePrivacyIcons(true);
1143 // Reload the current WebView.
1144 currentWebView.reload();
1146 // Consume the event.
1149 case R.id.clear_cookies:
1150 Snackbar.make(findViewById(R.id.webviewpager), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1151 .setAction(R.string.undo, v -> {
1152 // Do nothing because everything will be handled by `onDismissed()` below.
1154 .addCallback(new Snackbar.Callback() {
1155 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1157 public void onDismissed(Snackbar snackbar, int event) {
1158 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1159 // Delete the cookies, which command varies by SDK.
1160 if (Build.VERSION.SDK_INT < 21) {
1161 cookieManager.removeAllCookie();
1163 cookieManager.removeAllCookies(null);
1170 // Consume the event.
1173 case R.id.clear_dom_storage:
1174 Snackbar.make(findViewById(R.id.webviewpager), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1175 .setAction(R.string.undo, v -> {
1176 // Do nothing because everything will be handled by `onDismissed()` below.
1178 .addCallback(new Snackbar.Callback() {
1179 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1181 public void onDismissed(Snackbar snackbar, int event) {
1182 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1183 // Delete the DOM Storage.
1184 WebStorage webStorage = WebStorage.getInstance();
1185 webStorage.deleteAllData();
1187 // Initialize a handler to manually delete the DOM storage files and directories.
1188 Handler deleteDomStorageHandler = new Handler();
1190 // Setup a runnable to manually delete the DOM storage files and directories.
1191 Runnable deleteDomStorageRunnable = () -> {
1193 // Get a handle for the runtime.
1194 Runtime runtime = Runtime.getRuntime();
1196 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
1197 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
1198 String privateDataDirectoryString = getApplicationInfo().dataDir;
1200 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1201 Process deleteLocalStorageProcess = runtime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1203 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1204 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1205 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1206 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1207 Process deleteDatabasesProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1209 // Wait for the processes to finish.
1210 deleteLocalStorageProcess.waitFor();
1211 deleteIndexProcess.waitFor();
1212 deleteQuotaManagerProcess.waitFor();
1213 deleteQuotaManagerJournalProcess.waitFor();
1214 deleteDatabasesProcess.waitFor();
1215 } catch (Exception exception) {
1216 // Do nothing if an error is thrown.
1220 // Manually delete the DOM storage files after 200 milliseconds.
1221 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
1227 // Consume the event.
1230 // Form data can be remove once the minimum API >= 26.
1231 case R.id.clear_form_data:
1232 Snackbar.make(findViewById(R.id.webviewpager), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1233 .setAction(R.string.undo, v -> {
1234 // Do nothing because everything will be handled by `onDismissed()` below.
1236 .addCallback(new Snackbar.Callback() {
1237 @SuppressLint("SwitchIntDef") // Ignore the lint warning about not handling the other possible events as they are covered by `default:`.
1239 public void onDismissed(Snackbar snackbar, int event) {
1240 if (event != Snackbar.Callback.DISMISS_EVENT_ACTION) { // The snackbar was dismissed without the undo button being pushed.
1241 // Delete the form data.
1242 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1243 mainWebViewDatabase.clearFormData();
1249 // Consume the event.
1253 // Toggle the EasyList status.
1254 currentWebView.enableBlocklist(NestedScrollWebView.EASYLIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
1256 // Update the menu checkbox.
1257 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST));
1259 // Reload the current WebView.
1260 currentWebView.reload();
1262 // Consume the event.
1265 case R.id.easyprivacy:
1266 // Toggle the EasyPrivacy status.
1267 currentWebView.enableBlocklist(NestedScrollWebView.EASYPRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
1269 // Update the menu checkbox.
1270 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY));
1272 // Reload the current WebView.
1273 currentWebView.reload();
1275 // Consume the event.
1278 case R.id.fanboys_annoyance_list:
1279 // Toggle Fanboy's Annoyance List status.
1280 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1282 // Update the menu checkbox.
1283 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1285 // Update the staus of Fanboy's Social Blocking List.
1286 MenuItem fanboysSocialBlockingListMenuItem = optionsMenu.findItem(R.id.fanboys_social_blocking_list);
1287 fanboysSocialBlockingListMenuItem.setEnabled(!currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST));
1289 // Reload the current WebView.
1290 currentWebView.reload();
1292 // Consume the event.
1295 case R.id.fanboys_social_blocking_list:
1296 // Toggle Fanboy's Social Blocking List status.
1297 currentWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1299 // Update the menu checkbox.
1300 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST));
1302 // Reload the current WebView.
1303 currentWebView.reload();
1305 // Consume the event.
1308 case R.id.ultralist:
1309 // Toggle the UltraList status.
1310 currentWebView.enableBlocklist(NestedScrollWebView.ULTRALIST, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
1312 // Update the menu checkbox.
1313 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST));
1315 // Reload the current WebView.
1316 currentWebView.reload();
1318 // Consume the event.
1321 case R.id.ultraprivacy:
1322 // Toggle the UltraPrivacy status.
1323 currentWebView.enableBlocklist(NestedScrollWebView.ULTRAPRIVACY, !currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
1325 // Update the menu checkbox.
1326 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY));
1328 // Reload the current WebView.
1329 currentWebView.reload();
1331 // Consume the event.
1334 case R.id.block_all_third_party_requests:
1335 //Toggle the third-party requests blocker status.
1336 currentWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, !currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1338 // Update the menu checkbox.
1339 menuItem.setChecked(currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1341 // Reload the current WebView.
1342 currentWebView.reload();
1344 // Consume the event.
1347 case R.id.proxy_none:
1348 // Update the proxy mode.
1349 proxyMode = ProxyHelper.NONE;
1351 // Apply the proxy mode.
1354 // Consume the event.
1357 case R.id.proxy_tor:
1358 // Update the proxy mode.
1359 proxyMode = ProxyHelper.TOR;
1361 // Apply the proxy mode.
1364 // Consume the event.
1367 case R.id.proxy_i2p:
1368 // Update the proxy mode.
1369 proxyMode = ProxyHelper.I2P;
1371 // Apply the proxy mode.
1374 // Consume the event.
1377 case R.id.proxy_custom:
1378 // Update the proxy mode.
1379 proxyMode = ProxyHelper.CUSTOM;
1381 // Apply the proxy mode.
1384 // Consume the event.
1387 case R.id.user_agent_privacy_browser:
1388 // Update the user agent.
1389 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
1391 // Reload the current WebView.
1392 currentWebView.reload();
1394 // Consume the event.
1397 case R.id.user_agent_webview_default:
1398 // Update the user agent.
1399 currentWebView.getSettings().setUserAgentString("");
1401 // Reload the current WebView.
1402 currentWebView.reload();
1404 // Consume the event.
1407 case R.id.user_agent_firefox_on_android:
1408 // Update the user agent.
1409 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
1411 // Reload the current WebView.
1412 currentWebView.reload();
1414 // Consume the event.
1417 case R.id.user_agent_chrome_on_android:
1418 // Update the user agent.
1419 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
1421 // Reload the current WebView.
1422 currentWebView.reload();
1424 // Consume the event.
1427 case R.id.user_agent_safari_on_ios:
1428 // Update the user agent.
1429 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
1431 // Reload the current WebView.
1432 currentWebView.reload();
1434 // Consume the event.
1437 case R.id.user_agent_firefox_on_linux:
1438 // Update the user agent.
1439 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
1441 // Reload the current WebView.
1442 currentWebView.reload();
1444 // Consume the event.
1447 case R.id.user_agent_chromium_on_linux:
1448 // Update the user agent.
1449 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
1451 // Reload the current WebView.
1452 currentWebView.reload();
1454 // Consume the event.
1457 case R.id.user_agent_firefox_on_windows:
1458 // Update the user agent.
1459 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
1461 // Reload the current WebView.
1462 currentWebView.reload();
1464 // Consume the event.
1467 case R.id.user_agent_chrome_on_windows:
1468 // Update the user agent.
1469 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
1471 // Reload the current WebView.
1472 currentWebView.reload();
1474 // Consume the event.
1477 case R.id.user_agent_edge_on_windows:
1478 // Update the user agent.
1479 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
1481 // Reload the current WebView.
1482 currentWebView.reload();
1484 // Consume the event.
1487 case R.id.user_agent_internet_explorer_on_windows:
1488 // Update the user agent.
1489 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
1491 // Reload the current WebView.
1492 currentWebView.reload();
1494 // Consume the event.
1497 case R.id.user_agent_safari_on_macos:
1498 // Update the user agent.
1499 currentWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
1501 // Reload the current WebView.
1502 currentWebView.reload();
1504 // Consume the event.
1507 case R.id.user_agent_custom:
1508 // Update the user agent.
1509 currentWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
1511 // Reload the current WebView.
1512 currentWebView.reload();
1514 // Consume the event.
1517 case R.id.font_size:
1518 // Instantiate the font size dialog.
1519 DialogFragment fontSizeDialogFragment = FontSizeDialog.displayDialog(currentWebView.getSettings().getTextZoom());
1521 // Show the font size dialog.
1522 fontSizeDialogFragment.show(getSupportFragmentManager(), getString(R.string.font_size));
1524 // Consume the event.
1527 case R.id.swipe_to_refresh:
1528 // Toggle the stored status of swipe to refresh.
1529 currentWebView.setSwipeToRefresh(!currentWebView.getSwipeToRefresh());
1531 // Get a handle for the swipe refresh layout.
1532 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
1534 // Update the swipe refresh layout.
1535 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
1536 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
1537 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
1538 } else { // Swipe to refresh is disabled.
1539 // Disable the swipe refresh layout.
1540 swipeRefreshLayout.setEnabled(false);
1543 // Consume the event.
1546 case R.id.wide_viewport:
1547 // Toggle the viewport.
1548 currentWebView.getSettings().setUseWideViewPort(!currentWebView.getSettings().getUseWideViewPort());
1550 // Consume the event.
1553 case R.id.display_images:
1554 if (currentWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1555 // Disable loading of images.
1556 currentWebView.getSettings().setLoadsImagesAutomatically(false);
1558 // Reload the website to remove existing images.
1559 currentWebView.reload();
1560 } else { // Images are not currently loaded automatically.
1561 // Enable loading of images. Missing images will be loaded without the need for a reload.
1562 currentWebView.getSettings().setLoadsImagesAutomatically(true);
1565 // Consume the event.
1568 case R.id.dark_webview:
1569 // Check to see if dark WebView is supported by this WebView.
1570 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
1571 // Toggle the dark WebView setting.
1572 if (WebSettingsCompat.getForceDark(currentWebView.getSettings()) == WebSettingsCompat.FORCE_DARK_ON) { // Dark WebView is currently enabled.
1573 // Turn off dark WebView.
1574 WebSettingsCompat.setForceDark(currentWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
1575 } else { // Dark WebView is currently disabled.
1576 // turn on dark WebView.
1577 WebSettingsCompat.setForceDark(currentWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
1581 // Consume the event.
1584 case R.id.find_on_page:
1585 // Get a handle for the views.
1586 Toolbar toolbar = findViewById(R.id.toolbar);
1587 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
1588 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
1590 // Set the minimum height of the find on page linear layout to match the toolbar.
1591 findOnPageLinearLayout.setMinimumHeight(toolbar.getHeight());
1593 // Hide the toolbar.
1594 toolbar.setVisibility(View.GONE);
1596 // Show the find on page linear layout.
1597 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1599 // Display the keyboard. The app must wait 200 ms before running the command to work around a bug in Android.
1600 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1601 findOnPageEditText.postDelayed(() -> {
1602 // Set the focus on `findOnPageEditText`.
1603 findOnPageEditText.requestFocus();
1605 // Get a handle for the input method manager.
1606 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1608 // Remove the lint warning below that the input method manager might be null.
1609 assert inputMethodManager != null;
1611 // Display the keyboard. `0` sets no input flags.
1612 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1615 // Consume the event.
1619 // Get a print manager instance.
1620 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1622 // Remove the lint error below that print manager might be null.
1623 assert printManager != null;
1625 // Create a print document adapter from the current WebView.
1626 PrintDocumentAdapter printDocumentAdapter = currentWebView.createPrintDocumentAdapter();
1628 // Print the document.
1629 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1631 // Consume the event.
1635 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
1636 new PrepareSaveDialog(this, this, getSupportFragmentManager(), StoragePermissionDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
1637 currentWebView.getAcceptFirstPartyCookies()).execute(currentWebView.getCurrentUrl());
1639 // Consume the event.
1642 case R.id.save_as_archive:
1643 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
1644 new PrepareSaveDialog(this, this, getSupportFragmentManager(), StoragePermissionDialog.SAVE_AS_ARCHIVE, currentWebView.getSettings().getUserAgentString(),
1645 currentWebView.getAcceptFirstPartyCookies()).execute(currentWebView.getCurrentUrl());
1647 // Consume the event.
1650 case R.id.save_as_image:
1651 // Prepare the save dialog. The dialog will be displayed once the file size adn the content disposition have been acquired.
1652 new PrepareSaveDialog(this, this, getSupportFragmentManager(), StoragePermissionDialog.SAVE_AS_IMAGE, currentWebView.getSettings().getUserAgentString(),
1653 currentWebView.getAcceptFirstPartyCookies()).execute(currentWebView.getCurrentUrl());
1655 // Consume the event.
1658 case R.id.add_to_homescreen:
1659 // Instantiate the create home screen shortcut dialog.
1660 DialogFragment createHomeScreenShortcutDialogFragment = CreateHomeScreenShortcutDialog.createDialog(currentWebView.getTitle(), currentWebView.getUrl(),
1661 currentWebView.getFavoriteOrDefaultIcon());
1663 // Show the create home screen shortcut dialog.
1664 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
1666 // Consume the event.
1669 case R.id.view_source:
1670 // Create an intent to launch the view source activity.
1671 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
1673 // Add the variables to the intent.
1674 viewSourceIntent.putExtra("user_agent", currentWebView.getSettings().getUserAgentString());
1675 viewSourceIntent.putExtra("current_url", currentWebView.getUrl());
1678 startActivity(viewSourceIntent);
1680 // Consume the event.
1683 case R.id.share_url:
1684 // Setup the share string.
1685 String shareString = currentWebView.getTitle() + " – " + currentWebView.getUrl();
1687 // Create the share intent.
1688 Intent shareIntent = new Intent(Intent.ACTION_SEND);
1689 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1690 shareIntent.setType("text/plain");
1693 startActivity(Intent.createChooser(shareIntent, getString(R.string.share_url)));
1695 // Consume the event.
1698 case R.id.open_with_app:
1699 // Open the URL with an outside app.
1700 openWithApp(currentWebView.getUrl());
1702 // Consume the event.
1705 case R.id.open_with_browser:
1706 // Open the URL with an outside browser.
1707 openWithBrowser(currentWebView.getUrl());
1709 // Consume the event.
1712 case R.id.add_or_edit_domain:
1713 if (currentWebView.getDomainSettingsApplied()) { // Edit the current domain settings.
1714 // Reapply the domain settings on returning to `MainWebViewActivity`.
1715 reapplyDomainSettingsOnRestart = true;
1717 // Create an intent to launch the domains activity.
1718 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1720 // Add the extra information to the intent.
1721 domainsIntent.putExtra("load_domain", currentWebView.getDomainSettingsDatabaseId());
1722 domainsIntent.putExtra("close_on_back", true);
1723 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1725 // Get the current certificate.
1726 SslCertificate sslCertificate = currentWebView.getCertificate();
1728 // Check to see if the SSL certificate is populated.
1729 if (sslCertificate != null) {
1730 // Extract the certificate to strings.
1731 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1732 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1733 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1734 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1735 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1736 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1737 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1738 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1740 // Add the certificate to the intent.
1741 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1742 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1743 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1744 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1745 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1746 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1747 domainsIntent.putExtra("ssl_start_date", startDateLong);
1748 domainsIntent.putExtra("ssl_end_date", endDateLong);
1751 // Check to see if the current IP addresses have been received.
1752 if (currentWebView.hasCurrentIpAddresses()) {
1753 // Add the current IP addresses to the intent.
1754 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1758 startActivity(domainsIntent);
1759 } else { // Add a new domain.
1760 // Apply the new domain settings on returning to `MainWebViewActivity`.
1761 reapplyDomainSettingsOnRestart = true;
1763 // Get the current domain
1764 Uri currentUri = Uri.parse(currentWebView.getUrl());
1765 String currentDomain = currentUri.getHost();
1767 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1768 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1770 // Create the domain and store the database ID.
1771 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1773 // Create an intent to launch the domains activity.
1774 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1776 // Add the extra information to the intent.
1777 domainsIntent.putExtra("load_domain", newDomainDatabaseId);
1778 domainsIntent.putExtra("close_on_back", true);
1779 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1781 // Get the current certificate.
1782 SslCertificate sslCertificate = currentWebView.getCertificate();
1784 // Check to see if the SSL certificate is populated.
1785 if (sslCertificate != null) {
1786 // Extract the certificate to strings.
1787 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1788 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1789 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1790 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1791 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1792 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1793 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1794 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1796 // Add the certificate to the intent.
1797 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1798 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1799 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1800 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1801 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1802 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1803 domainsIntent.putExtra("ssl_start_date", startDateLong);
1804 domainsIntent.putExtra("ssl_end_date", endDateLong);
1807 // Check to see if the current IP addresses have been received.
1808 if (currentWebView.hasCurrentIpAddresses()) {
1809 // Add the current IP addresses to the intent.
1810 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1814 startActivity(domainsIntent);
1817 // Consume the event.
1820 case R.id.ad_consent:
1821 // Instantiate the ad consent dialog.
1822 DialogFragment adConsentDialogFragment = new AdConsentDialog();
1824 // Display the ad consent dialog.
1825 adConsentDialogFragment.show(getSupportFragmentManager(), getString(R.string.ad_consent));
1827 // Consume the event.
1831 // Don't consume the event.
1832 return super.onOptionsItemSelected(menuItem);
1836 // removeAllCookies is deprecated, but it is required for API < 21.
1838 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1839 // Get the menu item ID.
1840 int menuItemId = menuItem.getItemId();
1842 // Get a handle for the shared preferences.
1843 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1845 // Run the commands that correspond to the selected menu item.
1846 switch (menuItemId) {
1847 case R.id.clear_and_exit:
1848 // Clear and exit Privacy Browser.
1853 // Load the homepage.
1854 loadUrl(currentWebView, sharedPreferences.getString("homepage", getString(R.string.homepage_default_value)));
1858 if (currentWebView.canGoBack()) {
1859 // Get the current web back forward list.
1860 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
1862 // Get the previous entry URL.
1863 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
1865 // Apply the domain settings.
1866 applyDomainSettings(currentWebView, previousUrl, false, false);
1868 // Load the previous website in the history.
1869 currentWebView.goBack();
1874 if (currentWebView.canGoForward()) {
1875 // Get the current web back forward list.
1876 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
1878 // Get the next entry URL.
1879 String nextUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() + 1).getUrl();
1881 // Apply the domain settings.
1882 applyDomainSettings(currentWebView, nextUrl, false, false);
1884 // Load the next website in the history.
1885 currentWebView.goForward();
1890 // Instantiate the URL history dialog.
1891 DialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(currentWebView.getWebViewFragmentId());
1893 // Show the URL history dialog.
1894 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
1898 // Instantiate the open file dialog.
1899 DialogFragment openDialogFragment = new OpenDialog();
1901 // Show the open file dialog.
1902 openDialogFragment.show(getSupportFragmentManager(), getString(R.string.open));
1906 // Populate the resource requests.
1907 RequestsActivity.resourceRequests = currentWebView.getResourceRequests();
1909 // Create an intent to launch the Requests activity.
1910 Intent requestsIntent = new Intent(this, RequestsActivity.class);
1912 // Add the block third-party requests status to the intent.
1913 requestsIntent.putExtra("block_all_third_party_requests", currentWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS));
1916 startActivity(requestsIntent);
1919 case R.id.downloads:
1920 // Launch the system Download Manager.
1921 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1923 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1924 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1927 startActivity(downloadManagerIntent);
1931 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
1932 reapplyDomainSettingsOnRestart = true;
1934 // Launch the domains activity.
1935 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1937 // Add the extra information to the intent.
1938 domainsIntent.putExtra("current_url", currentWebView.getUrl());
1940 // Get the current certificate.
1941 SslCertificate sslCertificate = currentWebView.getCertificate();
1943 // Check to see if the SSL certificate is populated.
1944 if (sslCertificate != null) {
1945 // Extract the certificate to strings.
1946 String issuedToCName = sslCertificate.getIssuedTo().getCName();
1947 String issuedToOName = sslCertificate.getIssuedTo().getOName();
1948 String issuedToUName = sslCertificate.getIssuedTo().getUName();
1949 String issuedByCName = sslCertificate.getIssuedBy().getCName();
1950 String issuedByOName = sslCertificate.getIssuedBy().getOName();
1951 String issuedByUName = sslCertificate.getIssuedBy().getUName();
1952 long startDateLong = sslCertificate.getValidNotBeforeDate().getTime();
1953 long endDateLong = sslCertificate.getValidNotAfterDate().getTime();
1955 // Add the certificate to the intent.
1956 domainsIntent.putExtra("ssl_issued_to_cname", issuedToCName);
1957 domainsIntent.putExtra("ssl_issued_to_oname", issuedToOName);
1958 domainsIntent.putExtra("ssl_issued_to_uname", issuedToUName);
1959 domainsIntent.putExtra("ssl_issued_by_cname", issuedByCName);
1960 domainsIntent.putExtra("ssl_issued_by_oname", issuedByOName);
1961 domainsIntent.putExtra("ssl_issued_by_uname", issuedByUName);
1962 domainsIntent.putExtra("ssl_start_date", startDateLong);
1963 domainsIntent.putExtra("ssl_end_date", endDateLong);
1966 // Check to see if the current IP addresses have been received.
1967 if (currentWebView.hasCurrentIpAddresses()) {
1968 // Add the current IP addresses to the intent.
1969 domainsIntent.putExtra("current_ip_addresses", currentWebView.getCurrentIpAddresses());
1973 startActivity(domainsIntent);
1977 // Set the flag to reapply app settings on restart when returning from Settings.
1978 reapplyAppSettingsOnRestart = true;
1980 // Set the flag to reapply the domain settings on restart when returning from Settings.
1981 reapplyDomainSettingsOnRestart = true;
1983 // Launch the settings activity.
1984 Intent settingsIntent = new Intent(this, SettingsActivity.class);
1985 startActivity(settingsIntent);
1988 case R.id.import_export:
1989 // Launch the import/export activity.
1990 Intent importExportIntent = new Intent (this, ImportExportActivity.class);
1991 startActivity(importExportIntent);
1995 // Launch the logcat activity.
1996 Intent logcatIntent = new Intent(this, LogcatActivity.class);
1997 startActivity(logcatIntent);
2001 // Launch `GuideActivity`.
2002 Intent guideIntent = new Intent(this, GuideActivity.class);
2003 startActivity(guideIntent);
2007 // Create an intent to launch the about activity.
2008 Intent aboutIntent = new Intent(this, AboutActivity.class);
2010 // Create a string array for the blocklist versions.
2011 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],
2012 ultraList.get(0).get(0)[0], ultraPrivacy.get(0).get(0)[0]};
2014 // Add the blocklist versions to the intent.
2015 aboutIntent.putExtra("blocklist_versions", blocklistVersions);
2018 startActivity(aboutIntent);
2022 // Get a handle for the drawer layout.
2023 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
2025 // Close the navigation drawer.
2026 drawerLayout.closeDrawer(GravityCompat.START);
2031 public void onPostCreate(Bundle savedInstanceState) {
2032 // Run the default commands.
2033 super.onPostCreate(savedInstanceState);
2035 // Sync the state of the DrawerToggle after the default `onRestoreInstanceState()` has finished. This creates the navigation drawer icon.
2036 actionBarDrawerToggle.syncState();
2040 public void onConfigurationChanged(@NonNull Configuration newConfig) {
2041 // Run the default commands.
2042 super.onConfigurationChanged(newConfig);
2044 // Reload the ad for the free flavor if not in full screen mode.
2045 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2046 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2047 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
2050 // `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:
2051 // https://code.google.com/p/android/issues/detail?id=20493#c8
2052 // ActivityCompat.invalidateOptionsMenu(this);
2056 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2057 // Store the hit test result.
2058 final WebView.HitTestResult hitTestResult = currentWebView.getHitTestResult();
2060 // Define the URL strings.
2061 final String imageUrl;
2062 final String linkUrl;
2064 // Get handles for the system managers.
2065 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2067 // Remove the lint errors below that the clipboard manager might be null.
2068 assert clipboardManager != null;
2070 // Process the link according to the type.
2071 switch (hitTestResult.getType()) {
2072 // `SRC_ANCHOR_TYPE` is a link.
2073 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2074 // Get the target URL.
2075 linkUrl = hitTestResult.getExtra();
2077 // Set the target URL as the title of the `ContextMenu`.
2078 menu.setHeaderTitle(linkUrl);
2080 // Add an Open in New Tab entry.
2081 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2082 // Load the link URL in a new tab and move to it.
2083 addNewTab(linkUrl, true);
2085 // Consume the event.
2089 // Add an Open in Background entry.
2090 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2091 // Load the link URL in a new tab but do not move to it.
2092 addNewTab(linkUrl, false);
2094 // Consume the event.
2098 // Add an Open with App entry.
2099 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2100 openWithApp(linkUrl);
2102 // Consume the event.
2106 // Add an Open with Browser entry.
2107 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2108 openWithBrowser(linkUrl);
2110 // Consume the event.
2114 // Add a Copy URL entry.
2115 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2116 // Save the link URL in a `ClipData`.
2117 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2119 // Set the `ClipData` as the clipboard's primary clip.
2120 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2122 // Consume the event.
2126 // Add a Save URL entry.
2127 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2128 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2129 new PrepareSaveDialog(this, this, getSupportFragmentManager(), StoragePermissionDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
2130 currentWebView.getAcceptFirstPartyCookies()).execute(linkUrl);
2132 // Consume the event.
2136 // Add an empty Cancel entry, which by default closes the context menu.
2137 menu.add(R.string.cancel);
2140 // `IMAGE_TYPE` is an image.
2141 case WebView.HitTestResult.IMAGE_TYPE:
2142 // Get the image URL.
2143 imageUrl = hitTestResult.getExtra();
2145 // Set the image URL as the title of the context menu.
2146 menu.setHeaderTitle(imageUrl);
2148 // Add an Open in New Tab entry.
2149 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2150 // Load the image in a new tab.
2151 addNewTab(imageUrl, true);
2153 // Consume the event.
2157 // Add an Open with App entry.
2158 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2159 // Open the image URL with an external app.
2160 openWithApp(imageUrl);
2162 // Consume the event.
2166 // Add an Open with Browser entry.
2167 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2168 // Open the image URL with an external browser.
2169 openWithBrowser(imageUrl);
2171 // Consume the event.
2175 // Add a View Image entry.
2176 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2177 // Load the image in the current tab.
2178 loadUrl(currentWebView, imageUrl);
2180 // Consume the event.
2184 // Add a Save Image entry.
2185 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2186 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2187 new PrepareSaveDialog(this, this, getSupportFragmentManager(), StoragePermissionDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
2188 currentWebView.getAcceptFirstPartyCookies()).execute(imageUrl);
2190 // Consume the event.
2194 // Add a Copy URL entry.
2195 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2196 // Save the image URL in a clip data.
2197 ClipData imageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2199 // Set the clip data as the clipboard's primary clip.
2200 clipboardManager.setPrimaryClip(imageTypeClipData);
2202 // Consume the event.
2206 // Add an empty Cancel entry, which by default closes the context menu.
2207 menu.add(R.string.cancel);
2210 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2211 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2212 // Get the image URL.
2213 imageUrl = hitTestResult.getExtra();
2215 // Instantiate a handler.
2216 Handler handler = new Handler();
2218 // Get a message from the handler.
2219 Message message = handler.obtainMessage();
2221 // Request the image details from the last touched node be returned in the message.
2222 currentWebView.requestFocusNodeHref(message);
2224 // Get the link URL from the message data.
2225 linkUrl = message.getData().getString("url");
2227 // Set the link URL as the title of the context menu.
2228 menu.setHeaderTitle(linkUrl);
2230 // Add an Open in New Tab entry.
2231 menu.add(R.string.open_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2232 // Load the link URL in a new tab and move to it.
2233 addNewTab(linkUrl, true);
2235 // Consume the event.
2239 // Add an Open in Background entry.
2240 menu.add(R.string.open_in_background).setOnMenuItemClickListener((MenuItem item) -> {
2241 // Lod the link URL in a new tab but do not move to it.
2242 addNewTab(linkUrl, false);
2244 // Consume the event.
2248 // Add an Open Image in New Tab entry.
2249 menu.add(R.string.open_image_in_new_tab).setOnMenuItemClickListener((MenuItem item) -> {
2250 // Load the image in a new tab and move to it.
2251 addNewTab(imageUrl, true);
2253 // Consume the event.
2257 // Add an Open with App entry.
2258 menu.add(R.string.open_with_app).setOnMenuItemClickListener((MenuItem item) -> {
2259 // Open the link URL with an external app.
2260 openWithApp(linkUrl);
2262 // Consume the event.
2266 // Add an Open with Browser entry.
2267 menu.add(R.string.open_with_browser).setOnMenuItemClickListener((MenuItem item) -> {
2268 // Open the link URL with an external browser.
2269 openWithBrowser(linkUrl);
2271 // Consume the event.
2275 // Add a View Image entry.
2276 menu.add(R.string.view_image).setOnMenuItemClickListener((MenuItem item) -> {
2277 // View the image in the current tab.
2278 loadUrl(currentWebView, imageUrl);
2280 // Consume the event.
2284 // Add a Save Image entry.
2285 menu.add(R.string.save_image).setOnMenuItemClickListener((MenuItem item) -> {
2286 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2287 new PrepareSaveDialog(this, this, getSupportFragmentManager(), StoragePermissionDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
2288 currentWebView.getAcceptFirstPartyCookies()).execute(imageUrl);
2290 // Consume the event.
2294 // Add a Copy URL entry.
2295 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2296 // Save the link URL in a clip data.
2297 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2299 // Set the clip data as the clipboard's primary clip.
2300 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2302 // Consume the event.
2306 // Add a Save URL entry.
2307 menu.add(R.string.save_url).setOnMenuItemClickListener((MenuItem item) -> {
2308 // Prepare the save dialog. The dialog will be displayed once the file size and the content disposition have been acquired.
2309 new PrepareSaveDialog(this, this, getSupportFragmentManager(), StoragePermissionDialog.SAVE_URL, currentWebView.getSettings().getUserAgentString(),
2310 currentWebView.getAcceptFirstPartyCookies()).execute(linkUrl);
2312 // Consume the event.
2316 // Add an empty Cancel entry, which by default closes the context menu.
2317 menu.add(R.string.cancel);
2320 case WebView.HitTestResult.EMAIL_TYPE:
2321 // Get the target URL.
2322 linkUrl = hitTestResult.getExtra();
2324 // Set the target URL as the title of the `ContextMenu`.
2325 menu.setHeaderTitle(linkUrl);
2327 // Add a Write Email entry.
2328 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2329 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2330 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2332 // Parse the url and set it as the data for the `Intent`.
2333 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2335 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2336 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2339 startActivity(emailIntent);
2341 // Consume the event.
2345 // Add a Copy Email Address entry.
2346 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2347 // Save the email address in a `ClipData`.
2348 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2350 // Set the `ClipData` as the clipboard's primary clip.
2351 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2353 // Consume the event.
2357 // Add an empty Cancel entry, which by default closes the context menu.
2358 menu.add(R.string.cancel);
2364 public void onCreateBookmark(DialogFragment dialogFragment, Bitmap favoriteIconBitmap) {
2365 // Get a handle for the bookmarks list view.
2366 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2369 Dialog dialog = dialogFragment.getDialog();
2371 // Remove the incorrect lint warning below that the dialog might be null.
2372 assert dialog != null;
2374 // Get the views from the dialog fragment.
2375 EditText createBookmarkNameEditText = dialog.findViewById(R.id.create_bookmark_name_edittext);
2376 EditText createBookmarkUrlEditText = dialog.findViewById(R.id.create_bookmark_url_edittext);
2378 // Extract the strings from the edit texts.
2379 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2380 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2382 // Create a favorite icon byte array output stream.
2383 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2385 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2386 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2388 // Convert the favorite icon byte array stream to a byte array.
2389 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2391 // Display the new bookmark below the current items in the (0 indexed) list.
2392 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2394 // Create the bookmark.
2395 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2397 // Update the bookmarks cursor with the current contents of this folder.
2398 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2400 // Update the list view.
2401 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2403 // Scroll to the new bookmark.
2404 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2408 public void onCreateBookmarkFolder(DialogFragment dialogFragment, @NonNull Bitmap favoriteIconBitmap) {
2409 // Get a handle for the bookmarks list view.
2410 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
2413 Dialog dialog = dialogFragment.getDialog();
2415 // Remove the incorrect lint warning below that the dialog might be null.
2416 assert dialog != null;
2418 // Get handles for the views in the dialog fragment.
2419 EditText createFolderNameEditText = dialog.findViewById(R.id.create_folder_name_edittext);
2420 RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.create_folder_default_icon_radiobutton);
2421 ImageView folderIconImageView = dialog.findViewById(R.id.create_folder_default_icon);
2423 // Get new folder name string.
2424 String folderNameString = createFolderNameEditText.getText().toString();
2426 // Create a folder icon bitmap.
2427 Bitmap folderIconBitmap;
2429 // Set the folder icon bitmap according to the dialog.
2430 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
2431 // Get the default folder icon drawable.
2432 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2434 // Convert the folder icon drawable to a bitmap drawable.
2435 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2437 // Convert the folder icon bitmap drawable to a bitmap.
2438 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2439 } else { // Use the WebView favorite icon.
2440 // Copy the favorite icon bitmap to the folder icon bitmap.
2441 folderIconBitmap = favoriteIconBitmap;
2444 // Create a folder icon byte array output stream.
2445 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2447 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2448 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2450 // Convert the folder icon byte array stream to a byte array.
2451 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2453 // Move all the bookmarks down one in the display order.
2454 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2455 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2456 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2459 // Create the folder, which will be placed at the top of the `ListView`.
2460 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2462 // Update the bookmarks cursor with the current contents of this folder.
2463 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2465 // Update the `ListView`.
2466 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2468 // Scroll to the new folder.
2469 bookmarksListView.setSelection(0);
2473 public void onSaveBookmarkFolder(DialogFragment dialogFragment, int selectedFolderDatabaseId, Bitmap favoriteIconBitmap) {
2475 Dialog dialog = dialogFragment.getDialog();
2477 // Remove the incorrect lint warning below that the dialog might be null.
2478 assert dialog != null;
2480 // Get handles for the views from `dialogFragment`.
2481 EditText editFolderNameEditText = dialog.findViewById(R.id.edit_folder_name_edittext);
2482 RadioButton currentFolderIconRadioButton = dialog.findViewById(R.id.edit_folder_current_icon_radiobutton);
2483 RadioButton defaultFolderIconRadioButton = dialog.findViewById(R.id.edit_folder_default_icon_radiobutton);
2484 ImageView defaultFolderIconImageView = dialog.findViewById(R.id.edit_folder_default_icon_imageview);
2486 // Get the new folder name.
2487 String newFolderNameString = editFolderNameEditText.getText().toString();
2489 // Check if the favorite icon has changed.
2490 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
2491 // Update the name in the database.
2492 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2493 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
2494 // Create the new folder icon Bitmap.
2495 Bitmap folderIconBitmap;
2497 // Populate the new folder icon bitmap.
2498 if (defaultFolderIconRadioButton.isChecked()) {
2499 // Get the default folder icon drawable.
2500 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2502 // Convert the folder icon drawable to a bitmap drawable.
2503 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2505 // Convert the folder icon bitmap drawable to a bitmap.
2506 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2507 } else { // Use the `WebView` favorite icon.
2508 // Copy the favorite icon bitmap to the folder icon bitmap.
2509 folderIconBitmap = favoriteIconBitmap;
2512 // Create a folder icon byte array output stream.
2513 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2515 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2516 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2518 // Convert the folder icon byte array stream to a byte array.
2519 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2521 // Update the folder icon in the database.
2522 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, newFolderIconByteArray);
2523 } else { // The folder icon and the name have changed.
2524 // Get the new folder icon `Bitmap`.
2525 Bitmap folderIconBitmap;
2526 if (defaultFolderIconRadioButton.isChecked()) {
2527 // Get the default folder icon drawable.
2528 Drawable folderIconDrawable = defaultFolderIconImageView.getDrawable();
2530 // Convert the folder icon drawable to a bitmap drawable.
2531 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2533 // Convert the folder icon bitmap drawable to a bitmap.
2534 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2535 } else { // Use the `WebView` favorite icon.
2536 // Copy the favorite icon bitmap to the folder icon bitmap.
2537 folderIconBitmap = favoriteIconBitmap;
2540 // Create a folder icon byte array output stream.
2541 ByteArrayOutputStream newFolderIconByteArrayOutputStream = new ByteArrayOutputStream();
2543 // Convert the folder icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2544 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFolderIconByteArrayOutputStream);
2546 // Convert the folder icon byte array stream to a byte array.
2547 byte[] newFolderIconByteArray = newFolderIconByteArrayOutputStream.toByteArray();
2549 // Update the folder name and icon in the database.
2550 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, newFolderIconByteArray);
2553 // Update the bookmarks cursor with the current contents of this folder.
2554 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
2556 // Update the `ListView`.
2557 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2560 // Override `onBackPressed` to handle the navigation drawer and and the WebViews.
2562 public void onBackPressed() {
2563 // Get a handle for the drawer layout and the tab layout.
2564 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
2565 TabLayout tabLayout = findViewById(R.id.tablayout);
2567 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
2568 // Close the navigation drawer.
2569 drawerLayout.closeDrawer(GravityCompat.START);
2570 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
2571 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
2572 // close the bookmarks drawer.
2573 drawerLayout.closeDrawer(GravityCompat.END);
2574 } else { // A subfolder is displayed.
2575 // Place the former parent folder in `currentFolder`.
2576 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolderName(currentBookmarksFolder);
2578 // Load the new folder.
2579 loadBookmarksFolder();
2581 } else if (displayingFullScreenVideo) { // A full screen video is shown.
2582 // Get a handle for the layouts.
2583 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
2584 RelativeLayout mainContentRelativeLayout = findViewById(R.id.main_content_relativelayout);
2585 FrameLayout fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
2587 // Re-enable the screen timeout.
2588 fullScreenVideoFrameLayout.setKeepScreenOn(false);
2590 // Unset the full screen video flag.
2591 displayingFullScreenVideo = false;
2593 // Remove all the views from the full screen video frame layout.
2594 fullScreenVideoFrameLayout.removeAllViews();
2596 // Hide the full screen video frame layout.
2597 fullScreenVideoFrameLayout.setVisibility(View.GONE);
2599 // Enable the sliding drawers.
2600 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
2602 // Show the main content relative layout.
2603 mainContentRelativeLayout.setVisibility(View.VISIBLE);
2605 // Apply the appropriate full screen mode flags.
2606 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
2607 // Hide the banner ad in the free flavor.
2608 if (BuildConfig.FLAVOR.contentEquals("free")) {
2609 AdHelper.hideAd(findViewById(R.id.adview));
2612 /* Hide the system bars.
2613 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2614 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
2615 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2616 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
2618 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
2619 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
2621 // Reload the website if the app bar is hidden. Otherwise, there is some bug in Android that causes the WebView to be entirely black.
2623 // Reload the WebView.
2624 currentWebView.reload();
2626 } else { // Switch to normal viewing mode.
2627 // Remove the `SYSTEM_UI` flags from the root frame layout.
2628 rootFrameLayout.setSystemUiVisibility(0);
2631 // Reload the ad for the free flavor if not in full screen mode.
2632 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2634 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
2636 } else if (currentWebView.canGoBack()) { // There is at least one item in the current WebView history.
2637 // Get the current web back forward list.
2638 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
2640 // Get the previous entry URL.
2641 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
2643 // Apply the domain settings.
2644 applyDomainSettings(currentWebView, previousUrl, false, false);
2647 currentWebView.goBack();
2648 } else if (tabLayout.getTabCount() > 1) { // There are at least two tabs.
2649 // Close the current tab.
2651 } else { // There isn't anything to do in Privacy Browser.
2652 // Close Privacy Browser. `finishAndRemoveTask()` also removes Privacy Browser from the recent app list.
2653 if (Build.VERSION.SDK_INT >= 21) {
2654 finishAndRemoveTask();
2659 // Manually kill Privacy Browser. Otherwise, it is glitchy when restarted.
2664 // Process the results of a file browse.
2666 public void onActivityResult(int requestCode, int resultCode, Intent returnedIntent) {
2667 // Run the default commands.
2668 super.onActivityResult(requestCode, resultCode, returnedIntent);
2670 // Run the commands that correlate to the specified request code.
2671 switch (requestCode) {
2672 case BROWSE_FILE_UPLOAD_REQUEST_CODE:
2673 // File uploads only work on API >= 21.
2674 if (Build.VERSION.SDK_INT >= 21) {
2675 // Pass the file to the WebView.
2676 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, returnedIntent));
2680 case BROWSE_SAVE_WEBPAGE_REQUEST_CODE:
2681 // Don't do anything if the user pressed back from the file picker.
2682 if (resultCode == Activity.RESULT_OK) {
2683 // Get a handle for the save dialog fragment.
2684 DialogFragment saveWebpageDialogFragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.save_dialog));
2686 // Only update the file name if the dialog still exists.
2687 if (saveWebpageDialogFragment != null) {
2688 // Get a handle for the save webpage dialog.
2689 Dialog saveWebpageDialog = saveWebpageDialogFragment.getDialog();
2691 // Remove the incorrect lint warning below that the dialog might be null.
2692 assert saveWebpageDialog != null;
2694 // Get a handle for the file name edit text.
2695 EditText fileNameEditText = saveWebpageDialog.findViewById(R.id.file_name_edittext);
2696 TextView fileExistsWarningTextView = saveWebpageDialog.findViewById(R.id.file_exists_warning_textview);
2698 // Instantiate the file name helper.
2699 FileNameHelper fileNameHelper = new FileNameHelper();
2701 // Get the file path if it isn't null.
2702 if (returnedIntent.getData() != null) {
2703 // Convert the file name URI to a file name path.
2704 String fileNamePath = fileNameHelper.convertUriToFileNamePath(returnedIntent.getData());
2706 // Set the file name path as the text of the file name edit text.
2707 fileNameEditText.setText(fileNamePath);
2709 // Move the cursor to the end of the file name edit text.
2710 fileNameEditText.setSelection(fileNamePath.length());
2712 // Hide the file exists warning.
2713 fileExistsWarningTextView.setVisibility(View.GONE);
2719 case BROWSE_OPEN_REQUEST_CODE:
2720 // Don't do anything if the user pressed back from the file picker.
2721 if (resultCode == Activity.RESULT_OK) {
2722 // Get a handle for the open dialog fragment.
2723 DialogFragment openDialogFragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.open));
2725 // Only update the file name if the dialog still exists.
2726 if (openDialogFragment != null) {
2727 // Get a handle for the open dialog.
2728 Dialog openDialog = openDialogFragment.getDialog();
2730 // Remove the incorrect lint warning below that the dialog might be null.
2731 assert openDialog != null;
2733 // Get a handle for the file name edit text.
2734 EditText fileNameEditText = openDialog.findViewById(R.id.file_name_edittext);
2736 // Instantiate the file name helper.
2737 FileNameHelper fileNameHelper = new FileNameHelper();
2739 // Get the file path if it isn't null.
2740 if (returnedIntent.getData() != null) {
2741 // Convert the file name URI to a file name path.
2742 String fileNamePath = fileNameHelper.convertUriToFileNamePath(returnedIntent.getData());
2744 // Set the file name path as the text of the file name edit text.
2745 fileNameEditText.setText(fileNamePath);
2747 // Move the cursor to the end of the file name edit text.
2748 fileNameEditText.setSelection(fileNamePath.length());
2756 private void loadUrlFromTextBox() {
2757 // Get a handle for the URL edit text.
2758 EditText urlEditText = findViewById(R.id.url_edittext);
2760 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2761 String unformattedUrlString = urlEditText.getText().toString().trim();
2763 // Initialize the formatted URL string.
2766 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
2767 if (unformattedUrlString.startsWith("content://")) { // This is a Content URL.
2768 // Load the entire content URL.
2769 url = unformattedUrlString;
2770 } else if (Patterns.WEB_URL.matcher(unformattedUrlString).matches() || unformattedUrlString.startsWith("http://") || unformattedUrlString.startsWith("https://") ||
2771 unformattedUrlString.startsWith("file://")) { // This is a standard URL.
2772 // Add `https://` at the beginning if there is no protocol. Otherwise the app will segfault.
2773 if (!unformattedUrlString.startsWith("http") && !unformattedUrlString.startsWith("file://") && !unformattedUrlString.startsWith("content://")) {
2774 unformattedUrlString = "https://" + unformattedUrlString;
2777 // Initialize `unformattedUrl`.
2778 URL unformattedUrl = null;
2780 // 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.
2782 unformattedUrl = new URL(unformattedUrlString);
2783 } catch (MalformedURLException e) {
2784 e.printStackTrace();
2787 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2788 String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2789 String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2790 String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2791 String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2792 String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2795 Uri.Builder uri = new Uri.Builder();
2796 uri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2798 // Decode the URI as a UTF-8 string in.
2800 url = URLDecoder.decode(uri.build().toString(), "UTF-8");
2801 } catch (UnsupportedEncodingException exception) {
2802 // Do nothing. The formatted URL string will remain blank.
2804 } else if (!unformattedUrlString.isEmpty()){ // This is not a URL, but rather a search string.
2805 // Create an encoded URL String.
2806 String encodedUrlString;
2808 // Sanitize the search input.
2810 encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2811 } catch (UnsupportedEncodingException exception) {
2812 encodedUrlString = "";
2815 // Add the base search URL.
2816 url = searchURL + encodedUrlString;
2819 // 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.
2820 urlEditText.clearFocus();
2823 loadUrl(currentWebView, url);
2826 private void loadUrl(NestedScrollWebView nestedScrollWebView, String url) {
2827 // Sanitize the URL.
2828 url = sanitizeUrl(url);
2830 // Apply the domain settings.
2831 applyDomainSettings(nestedScrollWebView, url, true, false);
2834 nestedScrollWebView.loadUrl(url, customHeaders);
2837 public void findPreviousOnPage(View view) {
2838 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
2839 currentWebView.findNext(false);
2842 public void findNextOnPage(View view) {
2843 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2844 currentWebView.findNext(true);
2847 public void closeFindOnPage(View view) {
2848 // Get a handle for the views.
2849 Toolbar toolbar = findViewById(R.id.toolbar);
2850 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
2851 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
2853 // Delete the contents of `find_on_page_edittext`.
2854 findOnPageEditText.setText(null);
2856 // Clear the highlighted phrases if the WebView is not null.
2857 if (currentWebView != null) {
2858 currentWebView.clearMatches();
2861 // Hide the find on page linear layout.
2862 findOnPageLinearLayout.setVisibility(View.GONE);
2864 // Show the toolbar.
2865 toolbar.setVisibility(View.VISIBLE);
2867 // Get a handle for the input method manager.
2868 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
2870 // Remove the lint warning below that the input method manager might be null.
2871 assert inputMethodManager != null;
2873 // Hide the keyboard.
2874 inputMethodManager.hideSoftInputFromWindow(toolbar.getWindowToken(), 0);
2878 public void onApplyNewFontSize(DialogFragment dialogFragment) {
2880 Dialog dialog = dialogFragment.getDialog();
2882 // Remove the incorrect lint warning below tha the dialog might be null.
2883 assert dialog != null;
2885 // Get a handle for the font size edit text.
2886 EditText fontSizeEditText = dialog.findViewById(R.id.font_size_edittext);
2888 // Initialize the new font size variable with the current font size.
2889 int newFontSize = currentWebView.getSettings().getTextZoom();
2891 // Get the font size from the edit text.
2893 newFontSize = Integer.parseInt(fontSizeEditText.getText().toString());
2894 } catch (Exception exception) {
2895 // If the edit text does not contain a valid font size do nothing.
2898 // Apply the new font size.
2899 currentWebView.getSettings().setTextZoom(newFontSize);
2903 public void onOpen(DialogFragment dialogFragment) {
2905 Dialog dialog = dialogFragment.getDialog();
2907 // Remove the incorrect lint warning below that the dialog might be null.
2908 assert dialog != null;
2910 // Get a handle for the file name edit text.
2911 EditText fileNameEditText = dialog.findViewById(R.id.file_name_edittext);
2913 // Get the file path string.
2914 openFilePath = fileNameEditText.getText().toString();
2916 // Check to see if the storage permission is needed.
2917 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // The storage permission has been granted.
2919 currentWebView.loadUrl("file://" + openFilePath);
2920 } else { // The storage permission has not been granted.
2921 // Get the external private directory file.
2922 File externalPrivateDirectoryFile = getExternalFilesDir(null);
2924 // Remove the incorrect lint error below that the file might be null.
2925 assert externalPrivateDirectoryFile != null;
2927 // Get the external private directory string.
2928 String externalPrivateDirectory = externalPrivateDirectoryFile.toString();
2930 // Check to see if the file path is in the external private directory.
2931 if (openFilePath.startsWith(externalPrivateDirectory)) { // the file path is in the external private directory.
2933 currentWebView.loadUrl("file://" + openFilePath);
2934 } else { // The file path is in a public directory.
2935 // Check if the user has previously denied the storage permission.
2936 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2937 // Instantiate the storage permission alert dialog.
2938 DialogFragment storagePermissionDialogFragment = StoragePermissionDialog.displayDialog(StoragePermissionDialog.OPEN);
2940 // Show the storage permission alert dialog. The permission will be requested the the dialog is closed.
2941 storagePermissionDialogFragment.show(getSupportFragmentManager(), getString(R.string.storage_permission));
2942 } else { // Show the permission request directly.
2943 // Request the write external storage permission. The file will be opened when it finishes.
2944 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_OPEN_REQUEST_CODE);
2951 public void onSaveWebpage(int saveType, DialogFragment dialogFragment) {
2953 Dialog dialog = dialogFragment.getDialog();
2955 // Remove the incorrect lint warning below that the dialog might be null.
2956 assert dialog != null;
2958 // Get a handle for the edit texts.
2959 EditText urlEditText = dialog.findViewById(R.id.url_edittext);
2960 EditText fileNameEditText = dialog.findViewById(R.id.file_name_edittext);
2962 // Get the strings from the edit texts.
2963 saveWebpageUrl = urlEditText.getText().toString();
2964 saveWebpageFilePath = fileNameEditText.getText().toString();
2966 // Check to see if the storage permission is needed.
2967 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // The storage permission has been granted.
2968 //Save the webpage according to the save type.
2970 case StoragePermissionDialog.SAVE_URL:
2972 new SaveUrl(this, this, saveWebpageFilePath, currentWebView.getSettings().getUserAgentString(), currentWebView.getAcceptFirstPartyCookies()).execute(saveWebpageUrl);
2975 case StoragePermissionDialog.SAVE_AS_ARCHIVE:
2976 // Save the webpage archive.
2977 currentWebView.saveWebArchive(saveWebpageFilePath);
2980 case StoragePermissionDialog.SAVE_AS_IMAGE:
2981 // Save the webpage image.
2982 new SaveWebpageImage(this, currentWebView).execute(saveWebpageFilePath);
2985 } else { // The storage permission has not been granted.
2986 // Get the external private directory file.
2987 File externalPrivateDirectoryFile = getExternalFilesDir(null);
2989 // Remove the incorrect lint error below that the file might be null.
2990 assert externalPrivateDirectoryFile != null;
2992 // Get the external private directory string.
2993 String externalPrivateDirectory = externalPrivateDirectoryFile.toString();
2995 // Check to see if the file path is in the external private directory.
2996 if (saveWebpageFilePath.startsWith(externalPrivateDirectory)) { // The file path is in the external private directory.
2997 // Save the webpage according to the save type.
2999 case StoragePermissionDialog.SAVE_URL:
3001 new SaveUrl(this, this, saveWebpageFilePath, currentWebView.getSettings().getUserAgentString(), currentWebView.getAcceptFirstPartyCookies()).execute(saveWebpageUrl);
3004 case StoragePermissionDialog.SAVE_AS_ARCHIVE:
3005 // Save the webpage archive.
3006 currentWebView.saveWebArchive(saveWebpageFilePath);
3009 case StoragePermissionDialog.SAVE_AS_IMAGE:
3010 // Save the webpage image.
3011 new SaveWebpageImage(this, currentWebView).execute(saveWebpageFilePath);
3014 } else { // The file path is in a public directory.
3015 // Check if the user has previously denied the storage permission.
3016 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
3017 // Instantiate the storage permission alert dialog.
3018 DialogFragment storagePermissionDialogFragment = StoragePermissionDialog.displayDialog(saveType);
3020 // Show the storage permission alert dialog. The permission will be requested when the dialog is closed.
3021 storagePermissionDialogFragment.show(getSupportFragmentManager(), getString(R.string.storage_permission));
3022 } else { // Show the permission request directly.
3024 case StoragePermissionDialog.SAVE_URL:
3025 // Request the write external storage permission. The URL will be saved when it finishes.
3026 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_SAVE_URL_REQUEST_CODE);
3028 case StoragePermissionDialog.SAVE_AS_ARCHIVE:
3029 // Request the write external storage permission. The webpage archive will be saved when it finishes.
3030 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_SAVE_AS_ARCHIVE_REQUEST_CODE);
3033 case StoragePermissionDialog.SAVE_AS_IMAGE:
3034 // Request the write external storage permission. The webpage image will be saved when it finishes.
3035 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_SAVE_AS_IMAGE_REQUEST_CODE);
3044 public void onCloseStoragePermissionDialog(int requestType) {
3045 switch (requestType) {
3046 case StoragePermissionDialog.OPEN:
3047 // Request the write external storage permission. The file will be opened when it finishes.
3048 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_OPEN_REQUEST_CODE);
3051 case StoragePermissionDialog.SAVE_URL:
3052 // Request the write external storage permission. The URL will be saved when it finishes.
3053 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_SAVE_URL_REQUEST_CODE);
3056 case StoragePermissionDialog.SAVE_AS_ARCHIVE:
3057 // Request the write external storage permission. The webpage archive will be saved when it finishes.
3058 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_SAVE_AS_ARCHIVE_REQUEST_CODE);
3061 case StoragePermissionDialog.SAVE_AS_IMAGE:
3062 // Request the write external storage permission. The webpage image will be saved when it finishes.
3063 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_SAVE_AS_IMAGE_REQUEST_CODE);
3069 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
3070 //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).
3071 if (grantResults.length > 0) {
3072 switch (requestCode) {
3073 case PERMISSION_OPEN_REQUEST_CODE:
3074 // Check to see if the storage permission was granted. If the dialog was canceled the grant results will be empty.
3075 if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // The storage permission was granted.
3077 currentWebView.loadUrl("file://" + openFilePath);
3078 } else { // The storage permission was not granted.
3079 // Display an error snackbar.
3080 Snackbar.make(currentWebView, getString(R.string.cannot_use_location), Snackbar.LENGTH_LONG).show();
3083 // Reset the open file path.
3087 case PERMISSION_SAVE_URL_REQUEST_CODE:
3088 // Check to see if the storage permission was granted. If the dialog was canceled the grant results will be empty.
3089 if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // The storage permission was granted.
3090 // Save the raw URL.
3091 new SaveUrl(this, this, saveWebpageFilePath, currentWebView.getSettings().getUserAgentString(), currentWebView.getAcceptFirstPartyCookies()).execute(saveWebpageUrl);
3092 } else { // The storage permission was not granted.
3093 // Display an error snackbar.
3094 Snackbar.make(currentWebView, getString(R.string.cannot_use_location), Snackbar.LENGTH_LONG).show();
3097 // Reset the save strings.
3098 saveWebpageUrl = "";
3099 saveWebpageFilePath = "";
3102 case PERMISSION_SAVE_AS_ARCHIVE_REQUEST_CODE:
3103 // Check to see if the storage permission was granted. If the dialog was canceled the grant results will be empty.
3104 if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // The storage permission was granted.
3105 // Save the webpage archive.
3106 currentWebView.saveWebArchive(saveWebpageFilePath);
3107 } else { // The storage permission was not granted.
3108 // Display an error snackbar.
3109 Snackbar.make(currentWebView, getString(R.string.cannot_use_location), Snackbar.LENGTH_LONG).show();
3112 // Reset the save webpage file path.
3113 saveWebpageFilePath = "";
3116 case PERMISSION_SAVE_AS_IMAGE_REQUEST_CODE:
3117 // Check to see if the storage permission was granted. If the dialog was canceled the grant results will be empty.
3118 if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // The storage permission was granted.
3119 // Save the webpage image.
3120 new SaveWebpageImage(this, currentWebView).execute(saveWebpageFilePath);
3121 } else { // The storage permission was not granted.
3122 // Display an error snackbar.
3123 Snackbar.make(currentWebView, getString(R.string.cannot_use_location), Snackbar.LENGTH_LONG).show();
3126 // Reset the save webpage file path.
3127 saveWebpageFilePath = "";
3133 private void applyAppSettings() {
3134 // 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.
3135 if (webViewDefaultUserAgent == null) {
3139 // Get a handle for the shared preferences.
3140 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3142 // Store the values from the shared preferences in variables.
3143 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3144 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3145 sanitizeGoogleAnalytics = sharedPreferences.getBoolean("google_analytics", true);
3146 sanitizeFacebookClickIds = sharedPreferences.getBoolean("facebook_click_ids", true);
3147 sanitizeTwitterAmpRedirects = sharedPreferences.getBoolean("twitter_amp_redirects", true);
3148 proxyMode = sharedPreferences.getString("proxy", getString(R.string.proxy_default_value));
3149 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3150 hideAppBar = sharedPreferences.getBoolean("hide_app_bar", true);
3151 scrollAppBar = sharedPreferences.getBoolean("scroll_app_bar", true);
3153 // Get the search string.
3154 String searchString = sharedPreferences.getString("search", getString(R.string.search_default_value));
3156 // Set the search string.
3157 if (searchString.equals("Custom URL")) { // A custom search string is used.
3158 searchURL = sharedPreferences.getString("search_custom_url", getString(R.string.search_custom_url_default_value));
3159 } else { // A custom search string is not used.
3160 searchURL = searchString;
3163 // Get a handle for the app compat delegate.
3164 AppCompatDelegate appCompatDelegate = getDelegate();
3166 // Get handles for the views that need to be modified.
3167 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
3168 AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
3169 ActionBar actionBar = appCompatDelegate.getSupportActionBar();
3170 Toolbar toolbar = findViewById(R.id.toolbar);
3171 LinearLayout findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
3172 LinearLayout tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
3173 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
3175 // Remove the incorrect lint warning below that the action bar might be null.
3176 assert actionBar != null;
3181 // Set Do Not Track status.
3182 if (doNotTrackEnabled) {
3183 customHeaders.put("DNT", "1");
3185 customHeaders.remove("DNT");
3188 // Get the current layout parameters. Using coordinator layout parameters allows the `setBehavior()` command and using app bar layout parameters allows the `setScrollFlags()` command.
3189 CoordinatorLayout.LayoutParams swipeRefreshLayoutParams = (CoordinatorLayout.LayoutParams) swipeRefreshLayout.getLayoutParams();
3190 AppBarLayout.LayoutParams toolbarLayoutParams = (AppBarLayout.LayoutParams) toolbar.getLayoutParams();
3191 AppBarLayout.LayoutParams findOnPageLayoutParams = (AppBarLayout.LayoutParams) findOnPageLinearLayout.getLayoutParams();
3192 AppBarLayout.LayoutParams tabsLayoutParams = (AppBarLayout.LayoutParams) tabsLinearLayout.getLayoutParams();
3194 // Add the scrolling behavior to the layout parameters.
3196 // Enable scrolling of the app bar.
3197 swipeRefreshLayoutParams.setBehavior(new AppBarLayout.ScrollingViewBehavior());
3198 toolbarLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3199 findOnPageLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3200 tabsLayoutParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS | AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
3202 // Disable scrolling of the app bar.
3203 swipeRefreshLayoutParams.setBehavior(null);
3204 toolbarLayoutParams.setScrollFlags(0);
3205 findOnPageLayoutParams.setScrollFlags(0);
3206 tabsLayoutParams.setScrollFlags(0);
3208 // Expand the app bar if it is currently collapsed.
3209 appBarLayout.setExpanded(true);
3212 // Apply the modified layout parameters.
3213 swipeRefreshLayout.setLayoutParams(swipeRefreshLayoutParams);
3214 toolbar.setLayoutParams(toolbarLayoutParams);
3215 findOnPageLinearLayout.setLayoutParams(findOnPageLayoutParams);
3216 tabsLinearLayout.setLayoutParams(tabsLayoutParams);
3218 // Set the app bar scrolling for each WebView.
3219 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3220 // Get the WebView tab fragment.
3221 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3223 // Get the fragment view.
3224 View fragmentView = webViewTabFragment.getView();
3226 // Only modify the WebViews if they exist.
3227 if (fragmentView != null) {
3228 // Get the nested scroll WebView from the tab fragment.
3229 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3231 // Set the app bar scrolling.
3232 nestedScrollWebView.setNestedScrollingEnabled(scrollAppBar);
3236 // Update the full screen browsing mode settings.
3237 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
3238 // Update the visibility of the app bar, which might have changed in the settings.
3240 // Hide the tab linear layout.
3241 tabsLinearLayout.setVisibility(View.GONE);
3243 // Hide the action bar.
3246 // Show the tab linear layout.
3247 tabsLinearLayout.setVisibility(View.VISIBLE);
3249 // Show the action bar.
3253 // Hide the banner ad in the free flavor.
3254 if (BuildConfig.FLAVOR.contentEquals("free")) {
3255 AdHelper.hideAd(findViewById(R.id.adview));
3258 /* Hide the system bars.
3259 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3260 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
3261 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3262 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3264 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
3265 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3266 } else { // Privacy Browser is not in full screen browsing mode.
3267 // 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.
3268 inFullScreenBrowsingMode = false;
3270 // Show the tab linear layout.
3271 tabsLinearLayout.setVisibility(View.VISIBLE);
3273 // Show the action bar.
3276 // Show the banner ad in the free flavor.
3277 if (BuildConfig.FLAVOR.contentEquals("free")) {
3278 // Initialize the ads. If this isn't the first run, `loadAd()` will be automatically called instead.
3279 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getSupportFragmentManager(), getString(R.string.google_app_id), getString(R.string.ad_unit_id));
3282 // Remove the `SYSTEM_UI` flags from the root frame layout.
3283 rootFrameLayout.setSystemUiVisibility(0);
3287 private void initializeApp() {
3288 // Get a handle for the input method.
3289 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
3291 // Remove the lint warning below that the input method manager might be null.
3292 assert inputMethodManager != null;
3294 // Initialize the foreground color spans for highlighting the URLs. We have to use the deprecated `getColor()` until API >= 23.
3295 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
3296 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
3297 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
3299 // Get handles for the URL views.
3300 EditText urlEditText = findViewById(R.id.url_edittext);
3302 // Remove the formatting from the URL edit text when the user is editing the text.
3303 urlEditText.setOnFocusChangeListener((View v, boolean hasFocus) -> {
3304 if (hasFocus) { // The user is editing the URL text box.
3305 // Remove the highlighting.
3306 urlEditText.getText().removeSpan(redColorSpan);
3307 urlEditText.getText().removeSpan(initialGrayColorSpan);
3308 urlEditText.getText().removeSpan(finalGrayColorSpan);
3309 } else { // The user has stopped editing the URL text box.
3310 // Move to the beginning of the string.
3311 urlEditText.setSelection(0);
3313 // Reapply the highlighting.
3318 // Set the go button on the keyboard to load the URL in `urlTextBox`.
3319 urlEditText.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
3320 // If the event is a key-down event on the `enter` button, load the URL.
3321 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
3322 // Load the URL into the mainWebView and consume the event.
3323 loadUrlFromTextBox();
3325 // If the enter key was pressed, consume the event.
3328 // If any other key was pressed, do not consume the event.
3333 // Create an Orbot status broadcast receiver.
3334 orbotStatusBroadcastReceiver = new BroadcastReceiver() {
3336 public void onReceive(Context context, Intent intent) {
3337 // Store the content of the status message in `orbotStatus`.
3338 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
3340 // If Privacy Browser is waiting on the proxy, load the website now that Orbot is connected.
3341 if ((orbotStatus != null) && orbotStatus.equals("ON") && waitingForProxy) {
3342 // Reset the waiting for proxy status.
3343 waitingForProxy = false;
3345 // Get a handle for the waiting for proxy dialog.
3346 DialogFragment waitingForProxyDialogFragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.waiting_for_proxy_dialog));
3348 // Dismiss the waiting for proxy dialog if it is displayed.
3349 if (waitingForProxyDialogFragment != null) {
3350 waitingForProxyDialogFragment.dismiss();
3353 // Reload existing URLs and load any URLs that are waiting for the proxy.
3354 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
3355 // Get the WebView tab fragment.
3356 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
3358 // Get the fragment view.
3359 View fragmentView = webViewTabFragment.getView();
3361 // Only process the WebViews if they exist.
3362 if (fragmentView != null) {
3363 // Get the nested scroll WebView from the tab fragment.
3364 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
3366 // Get the waiting for proxy URL string.
3367 String waitingForProxyUrlString = nestedScrollWebView.getWaitingForProxyUrlString();
3369 // Load the pending URL if it exists.
3370 if (!waitingForProxyUrlString.isEmpty()) { // A URL is waiting to be loaded.
3372 loadUrl(nestedScrollWebView, waitingForProxyUrlString);
3374 // Reset the waiting for proxy URL string.
3375 nestedScrollWebView.resetWaitingForProxyUrlString();
3376 } else { // No URL is waiting to be loaded.
3377 // Reload the existing URL.
3378 nestedScrollWebView.reload();
3386 // Register the Orbot status broadcast receiver on `this` context.
3387 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
3389 // Get handles for views that need to be modified.
3390 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
3391 NavigationView navigationView = findViewById(R.id.navigationview);
3392 TabLayout tabLayout = findViewById(R.id.tablayout);
3393 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
3394 ViewPager webViewPager = findViewById(R.id.webviewpager);
3395 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
3396 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
3397 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
3398 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
3399 EditText findOnPageEditText = findViewById(R.id.find_on_page_edittext);
3401 // Listen for touches on the navigation menu.
3402 navigationView.setNavigationItemSelectedListener(this);
3404 // Get handles for the navigation menu and the back and forward menu items. The menu is 0 based.
3405 Menu navigationMenu = navigationView.getMenu();
3406 MenuItem navigationBackMenuItem = navigationMenu.getItem(2);
3407 MenuItem navigationForwardMenuItem = navigationMenu.getItem(3);
3408 MenuItem navigationHistoryMenuItem = navigationMenu.getItem(4);
3409 MenuItem navigationRequestsMenuItem = navigationMenu.getItem(6);
3411 // Update the web view pager every time a tab is modified.
3412 webViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
3414 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
3419 public void onPageSelected(int position) {
3420 // Close the find on page bar if it is open.
3421 closeFindOnPage(null);
3423 // Set the current WebView.
3424 setCurrentWebView(position);
3426 // 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.
3427 if (tabLayout.getSelectedTabPosition() != position) {
3428 // Create a handler to select the tab.
3429 Handler selectTabHandler = new Handler();
3431 // Create a runnable to select the tab.
3432 Runnable selectTabRunnable = () -> {
3433 // Get a handle for the tab.
3434 TabLayout.Tab tab = tabLayout.getTabAt(position);
3436 // Assert that the tab is not null.
3443 // Select the tab layout after 150 milliseconds, which leaves enough time for a new tab to be inflated.
3444 selectTabHandler.postDelayed(selectTabRunnable, 150);
3449 public void onPageScrollStateChanged(int state) {
3454 // Display the View SSL Certificate dialog when the currently selected tab is reselected.
3455 tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
3457 public void onTabSelected(TabLayout.Tab tab) {
3458 // Select the same page in the view pager.
3459 webViewPager.setCurrentItem(tab.getPosition());
3463 public void onTabUnselected(TabLayout.Tab tab) {
3468 public void onTabReselected(TabLayout.Tab tab) {
3469 // Instantiate the View SSL Certificate dialog.
3470 DialogFragment viewSslCertificateDialogFragment = ViewSslCertificateDialog.displayDialog(currentWebView.getWebViewFragmentId());
3472 // Display the View SSL Certificate dialog.
3473 viewSslCertificateDialogFragment.show(getSupportFragmentManager(), getString(R.string.view_ssl_certificate));
3477 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
3478 launchBookmarksActivityFab.setOnClickListener(v -> {
3479 // Get a copy of the favorite icon bitmap.
3480 Bitmap favoriteIconBitmap = currentWebView.getFavoriteOrDefaultIcon();
3482 // Create a favorite icon byte array output stream.
3483 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3485 // Convert the favorite icon bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
3486 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
3488 // Convert the favorite icon byte array stream to a byte array.
3489 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
3491 // Create an intent to launch the bookmarks activity.
3492 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
3494 // Add the extra information to the intent.
3495 bookmarksIntent.putExtra("current_url", currentWebView.getUrl());
3496 bookmarksIntent.putExtra("current_title", currentWebView.getTitle());
3497 bookmarksIntent.putExtra("current_folder", currentBookmarksFolder);
3498 bookmarksIntent.putExtra("favorite_icon_byte_array", favoriteIconByteArray);
3501 startActivity(bookmarksIntent);
3504 // Set the create new bookmark folder FAB to display an alert dialog.
3505 createBookmarkFolderFab.setOnClickListener(v -> {
3506 // Create a create bookmark folder dialog.
3507 DialogFragment createBookmarkFolderDialog = CreateBookmarkFolderDialog.createBookmarkFolder(currentWebView.getFavoriteOrDefaultIcon());
3509 // Show the create bookmark folder dialog.
3510 createBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.create_folder));
3513 // Set the create new bookmark FAB to display an alert dialog.
3514 createBookmarkFab.setOnClickListener(view -> {
3515 // Instantiate the create bookmark dialog.
3516 DialogFragment createBookmarkDialog = CreateBookmarkDialog.createBookmark(currentWebView.getUrl(), currentWebView.getTitle(), currentWebView.getFavoriteOrDefaultIcon());
3518 // Display the create bookmark dialog.
3519 createBookmarkDialog.show(getSupportFragmentManager(), getString(R.string.create_bookmark));
3522 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
3523 findOnPageEditText.addTextChangedListener(new TextWatcher() {
3525 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
3530 public void onTextChanged(CharSequence s, int start, int before, int count) {
3535 public void afterTextChanged(Editable s) {
3536 // 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.
3537 if (currentWebView != null) {
3538 currentWebView.findAllAsync(findOnPageEditText.getText().toString());
3543 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
3544 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
3545 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
3546 // Hide the soft keyboard.
3547 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3549 // Consume the event.
3551 } else { // A different key was pressed.
3552 // Do not consume the event.
3557 // Implement swipe to refresh.
3558 swipeRefreshLayout.setOnRefreshListener(() -> currentWebView.reload());
3560 // Store the default progress view offsets for use later in `initializeWebView()`.
3561 defaultProgressViewStartOffset = swipeRefreshLayout.getProgressViewStartOffset();
3562 defaultProgressViewEndOffset = swipeRefreshLayout.getProgressViewEndOffset();
3564 // Get the current theme status.
3565 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
3567 // Set the refresh color scheme according to the theme.
3568 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES) {
3569 swipeRefreshLayout.setColorSchemeResources(R.color.blue_500);
3571 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
3574 // Initialize a color background typed value.
3575 TypedValue colorBackgroundTypedValue = new TypedValue();
3577 // Get the color background from the theme.
3578 getTheme().resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true);
3580 // Get the color background int from the typed value.
3581 int colorBackgroundInt = colorBackgroundTypedValue.data;
3583 // Set the swipe refresh background color.
3584 swipeRefreshLayout.setProgressBackgroundColorSchemeColor(colorBackgroundInt);
3586 // The drawer titles identify the drawer layouts in accessibility mode.
3587 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
3588 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
3590 // Initialize the bookmarks database helper. The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
3591 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
3593 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
3594 currentBookmarksFolder = "";
3596 // Load the home folder, which is `""` in the database.
3597 loadBookmarksFolder();
3599 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
3600 // Convert the id from long to int to match the format of the bookmarks database.
3601 int databaseId = (int) id;
3603 // Get the bookmark cursor for this ID.
3604 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseId);
3606 // Move the bookmark cursor to the first row.
3607 bookmarkCursor.moveToFirst();
3609 // Act upon the bookmark according to the type.
3610 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
3611 // Store the new folder name in `currentBookmarksFolder`.
3612 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3614 // Load the new folder.
3615 loadBookmarksFolder();
3616 } else { // The selected bookmark is not a folder.
3617 // Load the bookmark URL.
3618 loadUrl(currentWebView, bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
3620 // Close the bookmarks drawer.
3621 drawerLayout.closeDrawer(GravityCompat.END);
3624 // Close the `Cursor`.
3625 bookmarkCursor.close();
3628 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
3629 // Convert the database ID from `long` to `int`.
3630 int databaseId = (int) id;
3632 // Find out if the selected bookmark is a folder.
3633 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
3636 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
3637 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3639 // Instantiate the edit folder bookmark dialog.
3640 DialogFragment editBookmarkFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId, currentWebView.getFavoriteOrDefaultIcon());
3642 // Show the edit folder bookmark dialog.
3643 editBookmarkFolderDialog.show(getSupportFragmentManager(), getString(R.string.edit_folder));
3645 // Get the bookmark cursor for this ID.
3646 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmark(databaseId);
3648 // Move the bookmark cursor to the first row.
3649 bookmarkCursor.moveToFirst();
3651 // Load the bookmark in a new tab but do not switch to the tab or close the drawer.
3652 addNewTab(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)), false);
3655 // Consume the event.
3659 // The drawer listener is used to update the navigation menu.
3660 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
3662 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
3666 public void onDrawerOpened(@NonNull View drawerView) {
3670 public void onDrawerClosed(@NonNull View drawerView) {
3674 public void onDrawerStateChanged(int newState) {
3675 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // A drawer is opening or closing.
3676 // Update the navigation menu items if the WebView is not null.
3677 if (currentWebView != null) {
3678 navigationBackMenuItem.setEnabled(currentWebView.canGoBack());
3679 navigationForwardMenuItem.setEnabled(currentWebView.canGoForward());
3680 navigationHistoryMenuItem.setEnabled((currentWebView.canGoBack() || currentWebView.canGoForward()));
3681 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + currentWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
3683 // Hide the keyboard (if displayed).
3684 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
3687 // 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.
3688 urlEditText.clearFocus();
3689 currentWebView.clearFocus();
3694 // 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).
3695 customHeaders.put("X-Requested-With", "");
3697 // Inflate a bare WebView to get the default user agent. It is not used to render content on the screen.
3698 @SuppressLint("InflateParams") View webViewLayout = getLayoutInflater().inflate(R.layout.bare_webview, null, false);
3700 // Get a handle for the WebView.
3701 WebView bareWebView = webViewLayout.findViewById(R.id.bare_webview);
3703 // Store the default user agent.
3704 webViewDefaultUserAgent = bareWebView.getSettings().getUserAgentString();
3706 // Destroy the bare WebView.
3707 bareWebView.destroy();
3711 public void navigateHistory(String url, int steps) {
3712 // Apply the domain settings.
3713 applyDomainSettings(currentWebView, url, false, false);
3715 // Load the history entry.
3716 currentWebView.goBackOrForward(steps);
3720 public void pinnedErrorGoBack() {
3721 // Get the current web back forward list.
3722 WebBackForwardList webBackForwardList = currentWebView.copyBackForwardList();
3724 // Get the previous entry URL.
3725 String previousUrl = webBackForwardList.getItemAtIndex(webBackForwardList.getCurrentIndex() - 1).getUrl();
3727 // Apply the domain settings.
3728 applyDomainSettings(currentWebView, previousUrl, false, false);
3731 currentWebView.goBack();
3734 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
3735 @SuppressLint("SetJavaScriptEnabled")
3736 private void applyDomainSettings(NestedScrollWebView nestedScrollWebView, String url, boolean resetTab, boolean reloadWebsite) {
3737 // Store the current URL.
3738 nestedScrollWebView.setCurrentUrl(url);
3740 // Parse the URL into a URI.
3741 Uri uri = Uri.parse(url);
3743 // Extract the domain from `uri`.
3744 String newHostName = uri.getHost();
3746 // Strings don't like to be null.
3747 if (newHostName == null) {
3751 // 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.
3752 if (!nestedScrollWebView.getCurrentDomainName().equals(newHostName) || newHostName.equals("")) {
3753 // Set the new host name as the current domain name.
3754 nestedScrollWebView.setCurrentDomainName(newHostName);
3756 // Reset the ignoring of pinned domain information.
3757 nestedScrollWebView.setIgnorePinnedDomainInformation(false);
3759 // Clear any pinned SSL certificate or IP addresses.
3760 nestedScrollWebView.clearPinnedSslCertificate();
3761 nestedScrollWebView.clearPinnedIpAddresses();
3763 // Reset the favorite icon if specified.
3765 // Initialize the favorite icon.
3766 nestedScrollWebView.initializeFavoriteIcon();
3768 // Get the current page position.
3769 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
3771 // Get a handle for the tab layout.
3772 TabLayout tabLayout = findViewById(R.id.tablayout);
3774 // Get the corresponding tab.
3775 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
3777 // Update the tab if it isn't null, which sometimes happens when restarting from the background.
3779 // Get the tab custom view.
3780 View tabCustomView = tab.getCustomView();
3782 // Remove the warning below that the tab custom view might be null.
3783 assert tabCustomView != null;
3785 // Get the tab views.
3786 ImageView tabFavoriteIconImageView = tabCustomView.findViewById(R.id.favorite_icon_imageview);
3787 TextView tabTitleTextView = tabCustomView.findViewById(R.id.title_textview);
3789 // Set the default favorite icon as the favorite icon for this tab.
3790 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(nestedScrollWebView.getFavoriteOrDefaultIcon(), 64, 64, true));
3792 // Set the loading title text.
3793 tabTitleTextView.setText(R.string.loading);
3797 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3798 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3800 // Get a full cursor from `domainsDatabaseHelper`.
3801 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3803 // Initialize `domainSettingsSet`.
3804 Set<String> domainSettingsSet = new HashSet<>();
3806 // Get the domain name column index.
3807 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3809 // Populate `domainSettingsSet`.
3810 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3811 // Move `domainsCursor` to the current row.
3812 domainNameCursor.moveToPosition(i);
3814 // Store the domain name in `domainSettingsSet`.
3815 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3818 // Close `domainNameCursor.
3819 domainNameCursor.close();
3821 // Initialize the domain name in database variable.
3822 String domainNameInDatabase = null;
3824 // Check the hostname against the domain settings set.
3825 if (domainSettingsSet.contains(newHostName)) { // The hostname is contained in the domain settings set.
3826 // Record the domain name in the database.
3827 domainNameInDatabase = newHostName;
3829 // Set the domain settings applied tracker to true.
3830 nestedScrollWebView.setDomainSettingsApplied(true);
3831 } else { // The hostname is not contained in the domain settings set.
3832 // Set the domain settings applied tracker to false.
3833 nestedScrollWebView.setDomainSettingsApplied(false);
3836 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3837 while (!nestedScrollWebView.getDomainSettingsApplied() && newHostName.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the host name.
3838 if (domainSettingsSet.contains("*." + newHostName)) { // Check the host name prepended by `*.`.
3839 // Set the domain settings applied tracker to true.
3840 nestedScrollWebView.setDomainSettingsApplied(true);
3842 // Store the applied domain names as it appears in the database.
3843 domainNameInDatabase = "*." + newHostName;
3846 // Strip out the lowest subdomain of of the host name.
3847 newHostName = newHostName.substring(newHostName.indexOf(".") + 1);
3851 // Get a handle for the shared preferences.
3852 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3854 // Store the general preference information.
3855 String defaultFontSizeString = sharedPreferences.getString("font_size", getString(R.string.font_size_default_value));
3856 String defaultUserAgentName = sharedPreferences.getString("user_agent", getString(R.string.user_agent_default_value));
3857 boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
3858 boolean wideViewport = sharedPreferences.getBoolean("wide_viewport", true);
3859 boolean displayWebpageImages = sharedPreferences.getBoolean("display_webpage_images", true);
3861 // Get a handle for the cookie manager.
3862 CookieManager cookieManager = CookieManager.getInstance();
3864 // Get handles for the views.
3865 RelativeLayout urlRelativeLayout = findViewById(R.id.url_relativelayout);
3866 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
3868 // Initialize the user agent array adapter and string array.
3869 ArrayAdapter<CharSequence> userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item);
3870 String[] userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
3872 if (nestedScrollWebView.getDomainSettingsApplied()) { // The url has custom domain settings.
3873 // Get a cursor for the current host and move it to the first position.
3874 Cursor currentDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3875 currentDomainSettingsCursor.moveToFirst();
3877 // Get the settings from the cursor.
3878 nestedScrollWebView.setDomainSettingsDatabaseId(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3879 nestedScrollWebView.getSettings().setJavaScriptEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3880 nestedScrollWebView.setAcceptFirstPartyCookies(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3881 boolean domainThirdPartyCookiesEnabled = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3882 nestedScrollWebView.getSettings().setDomStorageEnabled(currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3883 // Form data can be removed once the minimum API >= 26.
3884 boolean saveFormData = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3885 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASYLIST,
3886 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3887 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASYPRIVACY,
3888 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3889 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST,
3890 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3891 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST,
3892 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3893 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRALIST, currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ULTRALIST)) == 1);
3894 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRAPRIVACY,
3895 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1);
3896 nestedScrollWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS,
3897 currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
3898 String userAgentName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3899 int fontSize = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3900 int swipeToRefreshInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
3901 int webViewThemeInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.WEBVIEW_THEME));
3902 int wideViewportInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.WIDE_VIEWPORT));
3903 int displayWebpageImagesInt = currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3904 boolean pinnedSslCertificate = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3905 String pinnedSslIssuedToCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3906 String pinnedSslIssuedToOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3907 String pinnedSslIssuedToUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3908 String pinnedSslIssuedByCName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3909 String pinnedSslIssuedByOName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3910 String pinnedSslIssuedByUName = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3911 boolean pinnedIpAddresses = (currentDomainSettingsCursor.getInt(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_IP_ADDRESSES)) == 1);
3912 String pinnedHostIpAddresses = currentDomainSettingsCursor.getString(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.IP_ADDRESSES));
3914 // Create the pinned SSL date variables.
3915 Date pinnedSslStartDate;
3916 Date pinnedSslEndDate;
3918 // 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.
3919 if (currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
3920 pinnedSslStartDate = null;
3922 pinnedSslStartDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
3925 // 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.
3926 if (currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
3927 pinnedSslEndDate = null;
3929 pinnedSslEndDate = new Date(currentDomainSettingsCursor.getLong(currentDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
3932 // Close the current host domain settings cursor.
3933 currentDomainSettingsCursor.close();
3935 // If there is a pinned SSL certificate, store it in the WebView.
3936 if (pinnedSslCertificate) {
3937 nestedScrollWebView.setPinnedSslCertificate(pinnedSslIssuedToCName, pinnedSslIssuedToOName, pinnedSslIssuedToUName, pinnedSslIssuedByCName, pinnedSslIssuedByOName, pinnedSslIssuedByUName,
3938 pinnedSslStartDate, pinnedSslEndDate);
3941 // If there is a pinned IP address, store it in the WebView.
3942 if (pinnedIpAddresses) {
3943 nestedScrollWebView.setPinnedIpAddresses(pinnedHostIpAddresses);
3946 // Apply the cookie domain settings.
3947 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptFirstPartyCookies());
3949 // Set third-party cookies status if API >= 21.
3950 if (Build.VERSION.SDK_INT >= 21) {
3951 cookieManager.setAcceptThirdPartyCookies(nestedScrollWebView, domainThirdPartyCookiesEnabled);
3954 // Apply the form data setting if the API < 26.
3955 if (Build.VERSION.SDK_INT < 26) {
3956 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
3959 // Apply the font size.
3960 try { // Try the specified font size to see if it is valid.
3961 if (fontSize == 0) { // Apply the default font size.
3962 // Try to set the font size from the value in the app settings.
3963 nestedScrollWebView.getSettings().setTextZoom(Integer.parseInt(defaultFontSizeString));
3964 } else { // Apply the font size from domain settings.
3965 nestedScrollWebView.getSettings().setTextZoom(fontSize);
3967 } catch (Exception exception) { // The specified font size is invalid
3968 // Set the font size to be 100%
3969 nestedScrollWebView.getSettings().setTextZoom(100);
3972 // Set the user agent.
3973 if (userAgentName.equals(getString(R.string.system_default_user_agent))) { // Use the system default user agent.
3974 // Get the array position of the default user agent name.
3975 int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3977 // Set the user agent according to the system default.
3978 switch (defaultUserAgentArrayPosition) {
3979 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
3980 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3981 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
3984 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3985 // Set the user agent to `""`, which uses the default value.
3986 nestedScrollWebView.getSettings().setUserAgentString("");
3989 case SETTINGS_CUSTOM_USER_AGENT:
3990 // Set the default custom user agent.
3991 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
3995 // Get the user agent string from the user agent data array
3996 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
3998 } else { // Set the user agent according to the stored name.
3999 // Get the array position of the user agent name.
4000 int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
4002 switch (userAgentArrayPosition) {
4003 case UNRECOGNIZED_USER_AGENT: // The user agent name contains a custom user agent.
4004 nestedScrollWebView.getSettings().setUserAgentString(userAgentName);
4007 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4008 // Set the user agent to `""`, which uses the default value.
4009 nestedScrollWebView.getSettings().setUserAgentString("");
4013 // Get the user agent string from the user agent data array.
4014 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4018 // Set swipe to refresh.
4019 switch (swipeToRefreshInt) {
4020 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4021 // Store the swipe to refresh status in the nested scroll WebView.
4022 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
4024 // Update the swipe refresh layout.
4025 if (defaultSwipeToRefresh) { // Swipe to refresh is enabled.
4026 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
4027 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
4028 } else { // Swipe to refresh is disabled.
4029 // Disable the swipe refresh layout.
4030 swipeRefreshLayout.setEnabled(false);
4034 case DomainsDatabaseHelper.ENABLED:
4035 // Store the swipe to refresh status in the nested scroll WebView.
4036 nestedScrollWebView.setSwipeToRefresh(true);
4038 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
4039 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
4042 case DomainsDatabaseHelper.DISABLED:
4043 // Store the swipe to refresh status in the nested scroll WebView.
4044 nestedScrollWebView.setSwipeToRefresh(false);
4046 // Disable swipe to refresh.
4047 swipeRefreshLayout.setEnabled(false);
4050 // Check to see if WebView themes are supported.
4051 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
4052 // Set the WebView theme.
4053 switch (webViewThemeInt) {
4054 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4055 // // Ge the current system theme status.
4056 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4058 // Set the WebView theme according to the current system theme status.
4059 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES) { // The system is in night mode.
4060 // Turn on the WebView dark mode.
4061 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4062 } else { // The system is in day mode.
4063 // Turn off the WebView dark mode.
4064 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4068 case DomainsDatabaseHelper.LIGHT_THEME:
4069 // Turn off the WebView dark mode.
4070 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4073 case DomainsDatabaseHelper.DARK_THEME:
4074 // Turn on the WebView dark mode.
4075 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4080 // Set the viewport.
4081 switch (wideViewportInt) {
4082 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4083 nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
4086 case DomainsDatabaseHelper.ENABLED:
4087 nestedScrollWebView.getSettings().setUseWideViewPort(true);
4090 case DomainsDatabaseHelper.DISABLED:
4091 nestedScrollWebView.getSettings().setUseWideViewPort(false);
4095 // Set the loading of webpage images.
4096 switch (displayWebpageImagesInt) {
4097 case DomainsDatabaseHelper.SYSTEM_DEFAULT:
4098 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4101 case DomainsDatabaseHelper.ENABLED:
4102 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(true);
4105 case DomainsDatabaseHelper.DISABLED:
4106 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(false);
4110 // Get the current theme status.
4111 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4113 // Set a 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.
4114 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES) {
4115 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
4117 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
4119 } else { // The new URL does not have custom domain settings. Load the defaults.
4120 // Store the values from the shared preferences.
4121 nestedScrollWebView.getSettings().setJavaScriptEnabled(sharedPreferences.getBoolean("javascript", false));
4122 nestedScrollWebView.setAcceptFirstPartyCookies(sharedPreferences.getBoolean("first_party_cookies", false));
4123 boolean defaultThirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies", false);
4124 nestedScrollWebView.getSettings().setDomStorageEnabled(sharedPreferences.getBoolean("dom_storage", false));
4125 boolean saveFormData = sharedPreferences.getBoolean("save_form_data", false); // Form data can be removed once the minimum API >= 26.
4126 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASYLIST, sharedPreferences.getBoolean("easylist", true));
4127 nestedScrollWebView.enableBlocklist(NestedScrollWebView.EASYPRIVACY, sharedPreferences.getBoolean("easyprivacy", true));
4128 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST, sharedPreferences.getBoolean("fanboys_annoyance_list", true));
4129 nestedScrollWebView.enableBlocklist(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST, sharedPreferences.getBoolean("fanboys_social_blocking_list", true));
4130 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRALIST, sharedPreferences.getBoolean("ultralist", true));
4131 nestedScrollWebView.enableBlocklist(NestedScrollWebView.ULTRAPRIVACY, sharedPreferences.getBoolean("ultraprivacy", true));
4132 nestedScrollWebView.enableBlocklist(NestedScrollWebView.THIRD_PARTY_REQUESTS, sharedPreferences.getBoolean("block_all_third_party_requests", false));
4133 String webViewTheme = sharedPreferences.getString("webview_theme", getString(R.string.webview_theme_default_value));
4135 // Apply the default first-party cookie setting.
4136 cookieManager.setAcceptCookie(nestedScrollWebView.getAcceptFirstPartyCookies());
4138 // Apply the default font size setting.
4140 // Try to set the font size from the value in the app settings.
4141 nestedScrollWebView.getSettings().setTextZoom(Integer.parseInt(defaultFontSizeString));
4142 } catch (Exception exception) {
4143 // If the app settings value is invalid, set the font size to 100%.
4144 nestedScrollWebView.getSettings().setTextZoom(100);
4147 // Apply the form data setting if the API < 26.
4148 if (Build.VERSION.SDK_INT < 26) {
4149 nestedScrollWebView.getSettings().setSaveFormData(saveFormData);
4152 // Store the swipe to refresh status in the nested scroll WebView.
4153 nestedScrollWebView.setSwipeToRefresh(defaultSwipeToRefresh);
4155 // Update the swipe refresh layout.
4156 if (defaultSwipeToRefresh) { // Swipe to refresh is enabled.
4157 // Only enable the swipe refresh layout if the WebView is scrolled to the top. It is updated every time the scroll changes.
4158 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
4159 } else { // Swipe to refresh is disabled.
4160 // Disable the swipe refresh layout.
4161 swipeRefreshLayout.setEnabled(false);
4164 // Reset the pinned variables.
4165 nestedScrollWebView.setDomainSettingsDatabaseId(-1);
4167 // Set third-party cookies status if API >= 21.
4168 if (Build.VERSION.SDK_INT >= 21) {
4169 cookieManager.setAcceptThirdPartyCookies(nestedScrollWebView, defaultThirdPartyCookiesEnabled);
4172 // Get the array position of the user agent name.
4173 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4175 // Set the user agent.
4176 switch (userAgentArrayPosition) {
4177 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
4178 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4179 nestedScrollWebView.getSettings().setUserAgentString(defaultUserAgentName);
4182 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4183 // Set the user agent to `""`, which uses the default value.
4184 nestedScrollWebView.getSettings().setUserAgentString("");
4187 case SETTINGS_CUSTOM_USER_AGENT:
4188 // Set the default custom user agent.
4189 nestedScrollWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value)));
4193 // Get the user agent string from the user agent data array
4194 nestedScrollWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4197 // Get the WebView theme entry values string array.
4198 String[] webViewThemeEntryValuesStringArray = getResources().getStringArray(R.array.webview_theme_entry_values);
4200 // Apply the WebView theme if supported by the installed WebView.
4201 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
4202 // Set the WebView theme. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
4203 if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) { // The light theme is selected.
4204 // Turn off the WebView dark mode.
4205 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4206 } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) { // The dark theme is selected.
4207 // Turn on the WebView dark mode.
4208 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4209 } else { // The system default theme is selected.
4210 // Get the current system theme status.
4211 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4213 // Set the WebView theme according to the current system theme status.
4214 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES) { // The system is in night mode.
4215 // Turn on the WebView dark mode.
4216 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
4217 } else { // The system is in day mode.
4218 // Turn off the WebView dark mode.
4219 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
4224 // Set the viewport.
4225 nestedScrollWebView.getSettings().setUseWideViewPort(wideViewport);
4227 // Set the loading of webpage images.
4228 nestedScrollWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4230 // Set a transparent background on URL edit text. The deprecated `getResources().getDrawable()` must be used until the minimum API >= 21.
4231 urlRelativeLayout.setBackground(getResources().getDrawable(R.color.transparent));
4234 // Close the domains database helper.
4235 domainsDatabaseHelper.close();
4237 // Update the privacy icons.
4238 updatePrivacyIcons(true);
4241 // Reload the website if returning from the Domains activity.
4242 if (reloadWebsite) {
4243 nestedScrollWebView.reload();
4247 private void applyProxy(boolean reloadWebViews) {
4248 // Get a handle for the app bar layout.
4249 AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
4251 // Set the proxy according to the mode. `this` refers to the current activity where an alert dialog might be displayed.
4252 ProxyHelper.setProxy(getApplicationContext(), appBarLayout, proxyMode);
4254 // Reset the waiting for proxy tracker.
4255 waitingForProxy = false;
4257 // Get the current theme status.
4258 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4260 // Update the user interface and reload the WebViews if requested.
4261 switch (proxyMode) {
4262 case ProxyHelper.NONE:
4263 // Initialize a color background typed value.
4264 TypedValue colorBackgroundTypedValue = new TypedValue();
4266 // Get the color background from the theme.
4267 getTheme().resolveAttribute(android.R.attr.colorBackground, colorBackgroundTypedValue, true);
4269 // Get the color background int from the typed value.
4270 int colorBackgroundInt = colorBackgroundTypedValue.data;
4272 // Set the default app bar layout background.
4273 appBarLayout.setBackgroundColor(colorBackgroundInt);
4276 case ProxyHelper.TOR:
4277 // Set the app bar background to indicate proxying through Orbot is enabled.
4278 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES) {
4279 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4281 appBarLayout.setBackgroundResource(R.color.blue_50);
4284 // Check to see if Orbot is installed.
4286 // Get the package manager.
4287 PackageManager packageManager = getPackageManager();
4289 // 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.
4290 packageManager.getPackageInfo("org.torproject.android", 0);
4292 // Check to see if the proxy is ready.
4293 if (!orbotStatus.equals("ON")) { // Orbot is not ready.
4294 // Set the waiting for proxy status.
4295 waitingForProxy = true;
4297 // Show the waiting for proxy dialog if it isn't already displayed.
4298 if (getSupportFragmentManager().findFragmentByTag(getString(R.string.waiting_for_proxy_dialog)) == null) {
4299 // Get a handle for the waiting for proxy alert dialog.
4300 DialogFragment waitingForProxyDialogFragment = new WaitingForProxyDialog();
4302 // Display the waiting for proxy alert dialog.
4303 waitingForProxyDialogFragment.show(getSupportFragmentManager(), getString(R.string.waiting_for_proxy_dialog));
4306 } catch (PackageManager.NameNotFoundException exception) { // Orbot is not installed.
4307 // Show the Orbot not installed dialog if it is not already displayed.
4308 if (getSupportFragmentManager().findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
4309 // Get a handle for the Orbot not installed alert dialog.
4310 DialogFragment orbotNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode);
4312 // Display the Orbot not installed alert dialog.
4313 orbotNotInstalledDialogFragment.show(getSupportFragmentManager(), getString(R.string.proxy_not_installed_dialog));
4318 case ProxyHelper.I2P:
4319 // Set the app bar background to indicate proxying through Orbot is enabled.
4320 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES) {
4321 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4323 appBarLayout.setBackgroundResource(R.color.blue_50);
4326 // Check to see if I2P is installed.
4328 // Get the package manager.
4329 PackageManager packageManager = getPackageManager();
4331 // 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.
4332 packageManager.getPackageInfo("org.torproject.android", 0);
4333 } catch (PackageManager.NameNotFoundException exception) { // I2P is not installed.
4334 // Sow the I2P not installed dialog if it is not already displayed.
4335 if (getSupportFragmentManager().findFragmentByTag(getString(R.string.proxy_not_installed_dialog)) == null) {
4336 // Get a handle for the waiting for proxy alert dialog.
4337 DialogFragment i2pNotInstalledDialogFragment = ProxyNotInstalledDialog.displayDialog(proxyMode);
4339 // Display the I2P not installed alert dialog.
4340 i2pNotInstalledDialogFragment.show(getSupportFragmentManager(), getString(R.string.proxy_not_installed_dialog));
4345 case ProxyHelper.CUSTOM:
4346 // Set the app bar background to indicate proxying through Orbot is enabled.
4347 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES) {
4348 appBarLayout.setBackgroundResource(R.color.dark_blue_30);
4350 appBarLayout.setBackgroundResource(R.color.blue_50);
4355 // Reload the WebViews if requested and not waiting for the proxy.
4356 if (reloadWebViews && !waitingForProxy) {
4357 // Reload the WebViews.
4358 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4359 // Get the WebView tab fragment.
4360 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4362 // Get the fragment view.
4363 View fragmentView = webViewTabFragment.getView();
4365 // Only reload the WebViews if they exist.
4366 if (fragmentView != null) {
4367 // Get the nested scroll WebView from the tab fragment.
4368 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4370 // Reload the WebView.
4371 nestedScrollWebView.reload();
4377 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
4378 // Only update the privacy icons if the options menu and the current WebView have already been populated.
4379 if ((optionsMenu != null) && (currentWebView != null)) {
4380 // Get handles for the menu items.
4381 MenuItem privacyMenuItem = optionsMenu.findItem(R.id.toggle_javascript);
4382 MenuItem firstPartyCookiesMenuItem = optionsMenu.findItem(R.id.toggle_first_party_cookies);
4383 MenuItem domStorageMenuItem = optionsMenu.findItem(R.id.toggle_dom_storage);
4384 MenuItem refreshMenuItem = optionsMenu.findItem(R.id.refresh);
4386 // Update the privacy icon.
4387 if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is enabled.
4388 privacyMenuItem.setIcon(R.drawable.javascript_enabled);
4389 } else if (currentWebView.getAcceptFirstPartyCookies()) { // JavaScript is disabled but cookies are enabled.
4390 privacyMenuItem.setIcon(R.drawable.warning);
4391 } else { // All the dangerous features are disabled.
4392 privacyMenuItem.setIcon(R.drawable.privacy_mode);
4395 // Get the current theme status.
4396 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4398 // Update the first-party cookies icon.
4399 if (currentWebView.getAcceptFirstPartyCookies()) { // First-party cookies are enabled.
4400 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
4401 } else { // First-party cookies are disabled.
4402 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES) {
4403 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_night);
4405 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_day);
4409 // Update the DOM storage icon.
4410 if (currentWebView.getSettings().getJavaScriptEnabled() && currentWebView.getSettings().getDomStorageEnabled()) { // Both JavaScript and DOM storage are enabled.
4411 domStorageMenuItem.setIcon(R.drawable.dom_storage_enabled);
4412 } else if (currentWebView.getSettings().getJavaScriptEnabled()) { // JavaScript is enabled but DOM storage is disabled.
4413 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES) {
4414 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_night);
4416 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_day);
4418 } else { // JavaScript is disabled, so DOM storage is ghosted.
4419 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES) {
4420 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_night);
4422 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_day);
4426 // Update the refresh icon.
4427 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES) {
4428 refreshMenuItem.setIcon(R.drawable.refresh_enabled_night);
4430 refreshMenuItem.setIcon(R.drawable.refresh_enabled_day);
4433 // `invalidateOptionsMenu()` calls `onPrepareOptionsMenu()` and redraws the icons in the app bar.
4434 if (runInvalidateOptionsMenu) {
4435 invalidateOptionsMenu();
4440 private void highlightUrlText() {
4441 // Get a handle for the URL edit text.
4442 EditText urlEditText = findViewById(R.id.url_edittext);
4444 // Only highlight the URL text if the box is not currently selected.
4445 if (!urlEditText.hasFocus()) {
4446 // Get the URL string.
4447 String urlString = urlEditText.getText().toString();
4449 // Highlight the URL according to the protocol.
4450 if (urlString.startsWith("file://") || urlString.startsWith("content://")) { // This is a file or content URL.
4451 // De-emphasize everything before the file name.
4452 urlEditText.getText().setSpan(initialGrayColorSpan, 0, urlString.lastIndexOf("/") + 1,Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4453 } else { // This is a web URL.
4454 // Get the index of the `/` immediately after the domain name.
4455 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
4457 // Create a base URL string.
4460 // Get the base URL.
4461 if (endOfDomainName > 0) { // There is at least one character after the base URL.
4462 // Get the base URL.
4463 baseUrl = urlString.substring(0, endOfDomainName);
4464 } else { // There are no characters after the base URL.
4465 // Set the base URL to be the entire URL string.
4466 baseUrl = urlString;
4469 // Get the index of the last `.` in the domain.
4470 int lastDotIndex = baseUrl.lastIndexOf(".");
4472 // Get the index of the penultimate `.` in the domain.
4473 int penultimateDotIndex = baseUrl.lastIndexOf(".", lastDotIndex - 1);
4475 // Markup the beginning of the URL.
4476 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
4477 urlEditText.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4479 // De-emphasize subdomains.
4480 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
4481 urlEditText.getText().setSpan(initialGrayColorSpan, 7, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4483 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
4484 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
4485 // De-emphasize the protocol and the additional subdomains.
4486 urlEditText.getText().setSpan(initialGrayColorSpan, 0, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4487 } else { // There is only one subdomain in the domain name.
4488 // De-emphasize only the protocol.
4489 urlEditText.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4493 // De-emphasize the text after the domain name.
4494 if (endOfDomainName > 0) {
4495 urlEditText.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4501 private void loadBookmarksFolder() {
4502 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
4503 bookmarksCursor = bookmarksDatabaseHelper.getBookmarksByDisplayOrder(currentBookmarksFolder);
4505 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
4506 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
4508 public View newView(Context context, Cursor cursor, ViewGroup parent) {
4509 // Inflate the individual item layout. `false` does not attach it to the root.
4510 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
4514 public void bindView(View view, Context context, Cursor cursor) {
4515 // Get handles for the views.
4516 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
4517 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
4519 // Get the favorite icon byte array from the cursor.
4520 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
4522 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
4523 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
4525 // Display the bitmap in `bookmarkFavoriteIcon`.
4526 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4528 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4529 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
4530 bookmarkNameTextView.setText(bookmarkNameString);
4532 // Make the font bold for folders.
4533 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4534 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4535 } else { // Reset the font to default for normal bookmarks.
4536 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4541 // Get a handle for the bookmarks list view.
4542 ListView bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
4544 // Populate the list view with the adapter.
4545 bookmarksListView.setAdapter(bookmarksCursorAdapter);
4547 // Get a handle for the bookmarks title text view.
4548 TextView bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
4550 // Set the bookmarks drawer title.
4551 if (currentBookmarksFolder.isEmpty()) {
4552 bookmarksTitleTextView.setText(R.string.bookmarks);
4554 bookmarksTitleTextView.setText(currentBookmarksFolder);
4558 private void openWithApp(String url) {
4559 // Create an open with app intent with `ACTION_VIEW`.
4560 Intent openWithAppIntent = new Intent(Intent.ACTION_VIEW);
4562 // Set the URI but not the MIME type. This should open all available apps.
4563 openWithAppIntent.setData(Uri.parse(url));
4565 // Flag the intent to open in a new task.
4566 openWithAppIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4570 // Show the chooser.
4571 startActivity(openWithAppIntent);
4572 } catch (ActivityNotFoundException exception) { // There are no apps available to open the URL.
4573 // Show a snackbar with the error.
4574 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
4578 private void openWithBrowser(String url) {
4579 // Create an open with browser intent with `ACTION_VIEW`.
4580 Intent openWithBrowserIntent = new Intent(Intent.ACTION_VIEW);
4582 // Set the URI and the MIME type. `"text/html"` should load browser options.
4583 openWithBrowserIntent.setDataAndType(Uri.parse(url), "text/html");
4585 // Flag the intent to open in a new task.
4586 openWithBrowserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4590 // Show the chooser.
4591 startActivity(openWithBrowserIntent);
4592 } catch (ActivityNotFoundException exception) { // There are no browsers available to open the URL.
4593 // Show a snackbar with the error.
4594 Snackbar.make(currentWebView, getString(R.string.error) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
4598 private String sanitizeUrl(String url) {
4599 // Sanitize Google Analytics.
4600 if (sanitizeGoogleAnalytics) {
4602 if (url.contains("?utm_")) {
4603 url = url.substring(0, url.indexOf("?utm_"));
4607 if (url.contains("&utm_")) {
4608 url = url.substring(0, url.indexOf("&utm_"));
4612 // Sanitize Facebook Click IDs.
4613 if (sanitizeFacebookClickIds) {
4614 // Remove `?fbclid=`.
4615 if (url.contains("?fbclid=")) {
4616 url = url.substring(0, url.indexOf("?fbclid="));
4619 // Remove `&fbclid=`.
4620 if (url.contains("&fbclid=")) {
4621 url = url.substring(0, url.indexOf("&fbclid="));
4624 // Remove `?fbadid=`.
4625 if (url.contains("?fbadid=")) {
4626 url = url.substring(0, url.indexOf("?fbadid="));
4629 // Remove `&fbadid=`.
4630 if (url.contains("&fbadid=")) {
4631 url = url.substring(0, url.indexOf("&fbadid="));
4635 // Sanitize Twitter AMP redirects.
4636 if (sanitizeTwitterAmpRedirects) {
4638 if (url.contains("?amp=1")) {
4639 url = url.substring(0, url.indexOf("?amp=1"));
4643 // Return the sanitized URL.
4647 public void finishedPopulatingBlocklists(ArrayList<ArrayList<List<String[]>>> combinedBlocklists) {
4648 // Store the blocklists.
4649 easyList = combinedBlocklists.get(0);
4650 easyPrivacy = combinedBlocklists.get(1);
4651 fanboysAnnoyanceList = combinedBlocklists.get(2);
4652 fanboysSocialList = combinedBlocklists.get(3);
4653 ultraList = combinedBlocklists.get(4);
4654 ultraPrivacy = combinedBlocklists.get(5);
4656 // Add the first tab.
4657 addNewTab("", true);
4660 public void addTab(View view) {
4661 // Add a new tab with a blank URL.
4662 addNewTab("", true);
4665 private void addNewTab(String url, boolean moveToTab) {
4666 // Sanitize the URL.
4667 url = sanitizeUrl(url);
4669 // Get a handle for the tab layout and the view pager.
4670 TabLayout tabLayout = findViewById(R.id.tablayout);
4671 ViewPager webViewPager = findViewById(R.id.webviewpager);
4673 // Get the new page number. The page numbers are 0 indexed, so the new page number will match the current count.
4674 int newTabNumber = tabLayout.getTabCount();
4677 tabLayout.addTab(tabLayout.newTab());
4680 TabLayout.Tab newTab = tabLayout.getTabAt(newTabNumber);
4682 // Remove the lint warning below that the current tab might be null.
4683 assert newTab != null;
4685 // Set a custom view on the new tab.
4686 newTab.setCustomView(R.layout.tab_custom_view);
4688 // Add the new WebView page.
4689 webViewPagerAdapter.addPage(newTabNumber, webViewPager, url, moveToTab);
4692 public void closeTab(View view) {
4693 // Get a handle for the tab layout.
4694 TabLayout tabLayout = findViewById(R.id.tablayout);
4696 // Run the command according to the number of tabs.
4697 if (tabLayout.getTabCount() > 1) { // There is more than one tab open.
4698 // Close the current tab.
4700 } else { // There is only one tab open.
4705 private void closeCurrentTab() {
4706 // Get handles for the views.
4707 AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
4708 TabLayout tabLayout = findViewById(R.id.tablayout);
4709 ViewPager webViewPager = findViewById(R.id.webviewpager);
4711 // Get the current tab number.
4712 int currentTabNumber = tabLayout.getSelectedTabPosition();
4714 // Delete the current tab.
4715 tabLayout.removeTabAt(currentTabNumber);
4717 // 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.
4718 if (webViewPagerAdapter.deletePage(currentTabNumber, webViewPager)) {
4719 setCurrentWebView(currentTabNumber);
4722 // Expand the app bar if it is currently collapsed.
4723 appBarLayout.setExpanded(true);
4726 private void clearAndExit() {
4727 // Get a handle for the shared preferences.
4728 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4730 // Close the bookmarks cursor and database.
4731 bookmarksCursor.close();
4732 bookmarksDatabaseHelper.close();
4734 // Get the status of the clear everything preference.
4735 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
4737 // Get a handle for the runtime.
4738 Runtime runtime = Runtime.getRuntime();
4740 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
4741 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
4742 String privateDataDirectoryString = getApplicationInfo().dataDir;
4745 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
4746 // The command to remove cookies changed slightly in API 21.
4747 if (Build.VERSION.SDK_INT >= 21) {
4748 CookieManager.getInstance().removeAllCookies(null);
4750 CookieManager.getInstance().removeAllCookie();
4753 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4755 // Two commands must be used because `Runtime.exec()` does not like `*`.
4756 Process deleteCookiesProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
4757 Process deleteCookiesJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
4759 // Wait until the processes have finished.
4760 deleteCookiesProcess.waitFor();
4761 deleteCookiesJournalProcess.waitFor();
4762 } catch (Exception exception) {
4763 // Do nothing if an error is thrown.
4767 // Clear DOM storage.
4768 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
4769 // Ask `WebStorage` to clear the DOM storage.
4770 WebStorage webStorage = WebStorage.getInstance();
4771 webStorage.deleteAllData();
4773 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4775 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4776 Process deleteLocalStorageProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
4778 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
4779 Process deleteIndexProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
4780 Process deleteQuotaManagerProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
4781 Process deleteQuotaManagerJournalProcess = runtime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
4782 Process deleteDatabaseProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
4784 // Wait until the processes have finished.
4785 deleteLocalStorageProcess.waitFor();
4786 deleteIndexProcess.waitFor();
4787 deleteQuotaManagerProcess.waitFor();
4788 deleteQuotaManagerJournalProcess.waitFor();
4789 deleteDatabaseProcess.waitFor();
4790 } catch (Exception exception) {
4791 // Do nothing if an error is thrown.
4795 // Clear form data if the API < 26.
4796 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
4797 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
4798 webViewDatabase.clearFormData();
4800 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
4802 // A string array must be used because the database contains a space and `Runtime.exec` will not otherwise escape the string correctly.
4803 Process deleteWebDataProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
4804 Process deleteWebDataJournalProcess = runtime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
4806 // Wait until the processes have finished.
4807 deleteWebDataProcess.waitFor();
4808 deleteWebDataJournalProcess.waitFor();
4809 } catch (Exception exception) {
4810 // Do nothing if an error is thrown.
4815 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
4816 // Clear the cache from each WebView.
4817 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4818 // Get the WebView tab fragment.
4819 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4821 // Get the fragment view.
4822 View fragmentView = webViewTabFragment.getView();
4824 // Only clear the cache if the WebView exists.
4825 if (fragmentView != null) {
4826 // Get the nested scroll WebView from the tab fragment.
4827 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4829 // Clear the cache for this WebView.
4830 nestedScrollWebView.clearCache(true);
4834 // Manually delete the cache directories.
4836 // Delete the main cache directory.
4837 Process deleteCacheProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/cache");
4839 // Delete the secondary `Service Worker` cache directory.
4840 // A string array must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
4841 Process deleteServiceWorkerProcess = runtime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
4843 // Wait until the processes have finished.
4844 deleteCacheProcess.waitFor();
4845 deleteServiceWorkerProcess.waitFor();
4846 } catch (Exception exception) {
4847 // Do nothing if an error is thrown.
4851 // Wipe out each WebView.
4852 for (int i = 0; i < webViewPagerAdapter.getCount(); i++) {
4853 // Get the WebView tab fragment.
4854 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(i);
4856 // Get the fragment view.
4857 View fragmentView = webViewTabFragment.getView();
4859 // Only wipe out the WebView if it exists.
4860 if (fragmentView != null) {
4861 // Get the nested scroll WebView from the tab fragment.
4862 NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4864 // Clear SSL certificate preferences for this WebView.
4865 nestedScrollWebView.clearSslPreferences();
4867 // Clear the back/forward history for this WebView.
4868 nestedScrollWebView.clearHistory();
4870 // Destroy the internal state of `mainWebView`.
4871 nestedScrollWebView.destroy();
4875 // Clear the custom headers.
4876 customHeaders.clear();
4878 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
4879 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
4880 if (clearEverything) {
4882 // Delete the folder.
4883 Process deleteAppWebviewProcess = runtime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
4885 // Wait until the process has finished.
4886 deleteAppWebviewProcess.waitFor();
4887 } catch (Exception exception) {
4888 // Do nothing if an error is thrown.
4892 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
4893 if (Build.VERSION.SDK_INT >= 21) {
4894 finishAndRemoveTask();
4899 // Remove the terminated program from RAM. The status code is `0`.
4903 private void setCurrentWebView(int pageNumber) {
4904 // Get handles for the URL views.
4905 RelativeLayout urlRelativeLayout = findViewById(R.id.url_relativelayout);
4906 EditText urlEditText = findViewById(R.id.url_edittext);
4907 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
4909 // Stop the swipe to refresh indicator if it is running
4910 swipeRefreshLayout.setRefreshing(false);
4912 // Get the WebView tab fragment.
4913 WebViewTabFragment webViewTabFragment = webViewPagerAdapter.getPageFragment(pageNumber);
4915 // Get the fragment view.
4916 View fragmentView = webViewTabFragment.getView();
4918 // Set the current WebView if the fragment view is not null.
4919 if (fragmentView != null) { // The fragment has been populated.
4920 // Store the current WebView.
4921 currentWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
4923 // Update the status of swipe to refresh.
4924 if (currentWebView.getSwipeToRefresh()) { // Swipe to refresh is enabled.
4925 // Enable the swipe refresh layout if the WebView is scrolled all the way to the top. It is updated every time the scroll changes.
4926 swipeRefreshLayout.setEnabled(currentWebView.getY() == 0);
4927 } else { // Swipe to refresh is disabled.
4928 // Disable the swipe refresh layout.
4929 swipeRefreshLayout.setEnabled(false);
4932 // Get a handle for the cookie manager.
4933 CookieManager cookieManager = CookieManager.getInstance();
4935 // Set the first-party cookie status.
4936 cookieManager.setAcceptCookie(currentWebView.getAcceptFirstPartyCookies());
4938 // Update the privacy icons. `true` redraws the icons in the app bar.
4939 updatePrivacyIcons(true);
4941 // Get a handle for the input method manager.
4942 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
4944 // Remove the lint warning below that the input method manager might be null.
4945 assert inputMethodManager != null;
4947 // Get the current URL.
4948 String url = currentWebView.getUrl();
4950 // Update the URL edit text if not loading a new intent. Otherwise, this will be handled by `onPageStarted()` (if called) and `onPageFinished()`.
4951 if (!loadingNewIntent) { // A new intent is not being loaded.
4952 if ((url == null) || url.equals("about:blank")) { // The WebView is blank.
4953 // Display the hint in the URL edit text.
4954 urlEditText.setText("");
4956 // Request focus for the URL text box.
4957 urlEditText.requestFocus();
4959 // Display the keyboard.
4960 inputMethodManager.showSoftInput(urlEditText, 0);
4961 } else { // The WebView has a loaded URL.
4962 // Clear the focus from the URL text box.
4963 urlEditText.clearFocus();
4965 // Hide the soft keyboard.
4966 inputMethodManager.hideSoftInputFromWindow(currentWebView.getWindowToken(), 0);
4968 // Display the current URL in the URL text box.
4969 urlEditText.setText(url);
4971 // Highlight the URL text.
4974 } else { // A new intent is being loaded.
4975 // Reset the loading new intent tracker.
4976 loadingNewIntent = false;
4979 // Set the background to indicate the domain settings status.
4980 if (currentWebView.getDomainSettingsApplied()) {
4981 // Get the current theme status.
4982 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
4984 // 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.
4985 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES) {
4986 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
4988 urlRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
4991 urlRelativeLayout.setBackground(getResources().getDrawable(R.color.transparent));
4993 } else { // The fragment has not been populated. Try again in 100 milliseconds.
4994 // Create a handler to set the current WebView.
4995 Handler setCurrentWebViewHandler = new Handler();
4997 // Create a runnable to set the current WebView.
4998 Runnable setCurrentWebWebRunnable = () -> {
4999 // Set the current WebView.
5000 setCurrentWebView(pageNumber);
5003 // Try setting the current WebView again after 100 milliseconds.
5004 setCurrentWebViewHandler.postDelayed(setCurrentWebWebRunnable, 100);
5009 public void initializeWebView(NestedScrollWebView nestedScrollWebView, int pageNumber, ProgressBar progressBar, String url) {
5010 // Get a handle for the shared preferences.
5011 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
5013 // Get the WebView theme.
5014 String webViewTheme = sharedPreferences.getString("webview_theme", getString(R.string.webview_theme_default_value));
5016 // Get the WebView theme entry values string array.
5017 String[] webViewThemeEntryValuesStringArray = getResources().getStringArray(R.array.webview_theme_entry_values);
5019 // Apply the WebView theme if supported by the installed WebView.
5020 if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
5021 // Set the WebView theme. A switch statement cannot be used because the WebView theme entry values string array is not a compile time constant.
5022 if (webViewTheme.equals(webViewThemeEntryValuesStringArray[1])) { // The light theme is selected.
5023 // Turn off the WebView dark mode.
5024 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
5025 } else if (webViewTheme.equals(webViewThemeEntryValuesStringArray[2])) { // The dark theme is selected.
5026 // Turn on the WebView dark mode.
5027 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
5028 } else { // The system default theme is selected.
5029 // Get the current system theme status.
5030 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
5032 // Set the WebView theme according to the current system theme status.
5033 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES) { // The system is in night mode.
5034 // Turn on the WebView dark mode.
5035 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_ON);
5036 } else { // The system is in day mode.
5037 // Turn off the WebView dark mode.
5038 WebSettingsCompat.setForceDark(nestedScrollWebView.getSettings(), WebSettingsCompat.FORCE_DARK_OFF);
5043 // Get a handle for the app compat delegate.
5044 AppCompatDelegate appCompatDelegate = getDelegate();
5046 // Get handles for the activity views.
5047 FrameLayout rootFrameLayout = findViewById(R.id.root_framelayout);
5048 DrawerLayout drawerLayout = findViewById(R.id.drawerlayout);
5049 RelativeLayout mainContentRelativeLayout = findViewById(R.id.main_content_relativelayout);
5050 ActionBar actionBar = appCompatDelegate.getSupportActionBar();
5051 LinearLayout tabsLinearLayout = findViewById(R.id.tabs_linearlayout);
5052 EditText urlEditText = findViewById(R.id.url_edittext);
5053 TabLayout tabLayout = findViewById(R.id.tablayout);
5054 SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
5056 // Remove the incorrect lint warning below that the action bar might be null.
5057 assert actionBar != null;
5059 // Get a handle for the activity
5060 Activity activity = this;
5062 // Get a handle for the input method manager.
5063 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
5065 // Instantiate the blocklist helper.
5066 BlocklistHelper blocklistHelper = new BlocklistHelper();
5068 // Remove the lint warning below that the input method manager might be null.
5069 assert inputMethodManager != null;
5071 // Initialize the favorite icon.
5072 nestedScrollWebView.initializeFavoriteIcon();
5074 // Set the app bar scrolling.
5075 nestedScrollWebView.setNestedScrollingEnabled(sharedPreferences.getBoolean("scroll_app_bar", true));
5077 // Allow pinch to zoom.
5078 nestedScrollWebView.getSettings().setBuiltInZoomControls(true);
5080 // Hide zoom controls.
5081 nestedScrollWebView.getSettings().setDisplayZoomControls(false);
5083 // Don't allow mixed content (HTTP and HTTPS) on the same website.
5084 if (Build.VERSION.SDK_INT >= 21) {
5085 nestedScrollWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);
5088 // Set the WebView to load in overview mode (zoomed out to the maximum width).
5089 nestedScrollWebView.getSettings().setLoadWithOverviewMode(true);
5091 // Explicitly disable geolocation.
5092 nestedScrollWebView.getSettings().setGeolocationEnabled(false);
5094 // Create a double-tap gesture detector to toggle full-screen mode.
5095 GestureDetector doubleTapGestureDetector = new GestureDetector(getApplicationContext(), new GestureDetector.SimpleOnGestureListener() {
5096 // Override `onDoubleTap()`. All other events are handled using the default settings.
5098 public boolean onDoubleTap(MotionEvent event) {
5099 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
5100 // Toggle the full screen browsing mode tracker.
5101 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
5103 // Toggle the full screen browsing mode.
5104 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
5105 // Hide the app bar if specified.
5107 // Close the find on page bar if it is visible.
5108 closeFindOnPage(null);
5110 // Hide the tab linear layout.
5111 tabsLinearLayout.setVisibility(View.GONE);
5113 // Hide the action bar.
5116 // If the app bar is not being scrolled, the swipe refresh layout needs to be adjusted.
5117 if (!scrollAppBar) {
5118 // Remove the padding from the top of the swipe refresh layout.
5119 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5121 // The swipe refresh circle must be moved above the now removed status bar location.
5122 swipeRefreshLayout.setProgressViewOffset(false, -200, defaultProgressViewEndOffset);
5126 // Hide the banner ad in the free flavor.
5127 if (BuildConfig.FLAVOR.contentEquals("free")) {
5128 AdHelper.hideAd(findViewById(R.id.adview));
5131 /* Hide the system bars.
5132 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5133 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5134 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5135 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5137 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5138 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5139 } else { // Switch to normal viewing mode.
5140 // Show the app bar if it was hidden.
5142 // Show the tab linear layout.
5143 tabsLinearLayout.setVisibility(View.VISIBLE);
5145 // Show the action bar.
5148 // If the app bar is not being scrolled, the swipe refresh layout needs to be adjusted.
5149 if (!scrollAppBar) {
5150 // The swipe refresh layout must be manually moved below the app bar layout.
5151 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0);
5153 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5154 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight);
5158 // Show the banner ad in the free flavor.
5159 if (BuildConfig.FLAVOR.contentEquals("free")) {
5161 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
5164 // Remove the `SYSTEM_UI` flags from the root frame layout.
5165 rootFrameLayout.setSystemUiVisibility(0);
5168 // Consume the double-tap.
5170 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
5176 // Pass all touch events on the WebView through the double-tap gesture detector.
5177 nestedScrollWebView.setOnTouchListener((View view, MotionEvent event) -> {
5178 // Call `performClick()` on the view, which is required for accessibility.
5179 view.performClick();
5181 // Send the event to the gesture detector.
5182 return doubleTapGestureDetector.onTouchEvent(event);
5185 // Register the WebView for a context menu. This is used to see link targets and download images.
5186 registerForContextMenu(nestedScrollWebView);
5188 // Allow the downloading of files.
5189 nestedScrollWebView.setDownloadListener((String downloadUrl, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
5190 // Define a formatted file size string.
5191 String formattedFileSizeString;
5193 // Process the content length if it contains data.
5194 if (contentLength > 0) { // The content length is greater than 0.
5195 // Format the content length as a string.
5196 formattedFileSizeString = NumberFormat.getInstance().format(contentLength) + " " + getString(R.string.bytes);
5197 } else { // The content length is not greater than 0.
5198 // Set the formatted file size string to be `unknown size`.
5199 formattedFileSizeString = getString(R.string.unknown_size);
5202 // Get the file name from the content disposition.
5203 String fileNameString = PrepareSaveDialog.getFileNameFromContentDisposition(this, contentDisposition, downloadUrl);
5205 // Instantiate the save dialog.
5206 DialogFragment saveDialogFragment = SaveDialog.saveUrl(StoragePermissionDialog.SAVE_URL, downloadUrl, formattedFileSizeString, fileNameString, userAgent,
5207 nestedScrollWebView.getAcceptFirstPartyCookies());
5209 // Show the save dialog. It must be named `save_dialog` so that the file picker can update the file name.
5210 saveDialogFragment.show(getSupportFragmentManager(), getString(R.string.save_dialog));
5213 // Update the find on page count.
5214 nestedScrollWebView.setFindListener(new WebView.FindListener() {
5215 // Get a handle for `findOnPageCountTextView`.
5216 final TextView findOnPageCountTextView = findViewById(R.id.find_on_page_count_textview);
5219 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
5220 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
5221 // Set `findOnPageCountTextView` to `0/0`.
5222 findOnPageCountTextView.setText(R.string.zero_of_zero);
5223 } else if (isDoneCounting) { // There are matches.
5224 // `activeMatchOrdinal` is zero-based.
5225 int activeMatch = activeMatchOrdinal + 1;
5227 // Build the match string.
5228 String matchString = activeMatch + "/" + numberOfMatches;
5230 // Set `findOnPageCountTextView`.
5231 findOnPageCountTextView.setText(matchString);
5236 // Update the status of swipe to refresh based on the scroll position of the nested scroll WebView. Also reinforce full screen browsing mode.
5237 // On API < 23, `getViewTreeObserver().addOnScrollChangedListener()` must be used, but it is a little bit buggy and appears to get garbage collected from time to time.
5238 if (Build.VERSION.SDK_INT >= 23) {
5239 nestedScrollWebView.setOnScrollChangeListener((view, i, i1, i2, i3) -> {
5240 if (nestedScrollWebView.getSwipeToRefresh()) {
5241 // Only enable swipe to refresh if the WebView is scrolled to the top.
5242 swipeRefreshLayout.setEnabled(nestedScrollWebView.getScrollY() == 0);
5244 // Disable swipe to refresh.
5245 swipeRefreshLayout.setEnabled(false);
5248 // Reinforce the system UI visibility flags if in full screen browsing mode.
5249 // This hides the status and navigation bars, which are displayed if other elements are shown, like dialog boxes, the options menu, or the keyboard.
5250 if (inFullScreenBrowsingMode) {
5251 /* Hide the system bars.
5252 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5253 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5254 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5255 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5257 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5258 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5262 nestedScrollWebView.getViewTreeObserver().addOnScrollChangedListener(() -> {
5263 if (nestedScrollWebView.getSwipeToRefresh()) {
5264 // Only enable swipe to refresh if the WebView is scrolled to the top.
5265 swipeRefreshLayout.setEnabled(nestedScrollWebView.getScrollY() == 0);
5267 // Disable swipe to refresh.
5268 swipeRefreshLayout.setEnabled(false);
5272 // Reinforce the system UI visibility flags if in full screen browsing mode.
5273 // This hides the status and navigation bars, which are displayed if other elements are shown, like dialog boxes, the options menu, or the keyboard.
5274 if (inFullScreenBrowsingMode) {
5275 /* Hide the system bars.
5276 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5277 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5278 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5279 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5281 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5282 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5287 // Set the web chrome client.
5288 nestedScrollWebView.setWebChromeClient(new WebChromeClient() {
5289 // Update the progress bar when a page is loading.
5291 public void onProgressChanged(WebView view, int progress) {
5292 // Update the progress bar.
5293 progressBar.setProgress(progress);
5295 // Set the visibility of the progress bar.
5296 if (progress < 100) {
5297 // Show the progress bar.
5298 progressBar.setVisibility(View.VISIBLE);
5300 // Hide the progress bar.
5301 progressBar.setVisibility(View.GONE);
5303 //Stop the swipe to refresh indicator if it is running
5304 swipeRefreshLayout.setRefreshing(false);
5307 // If this is a new tab, the current WebView would have been created invisible in `webview_framelayout` to prevent a white background splash in night mode.
5308 if (progress >= 50) {
5309 // Make the current WebView visible.
5310 currentWebView.setVisibility(View.VISIBLE);
5314 // Set the favorite icon when it changes.
5316 public void onReceivedIcon(WebView view, Bitmap icon) {
5317 // Only update the favorite icon if the website has finished loading.
5318 if (progressBar.getVisibility() == View.GONE) {
5319 // Store the new favorite icon.
5320 nestedScrollWebView.setFavoriteOrDefaultIcon(icon);
5322 // Get the current page position.
5323 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5325 // Get the current tab.
5326 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
5328 // Check to see if the tab has been populated.
5330 // Get the custom view from the tab.
5331 View tabView = tab.getCustomView();
5333 // Check to see if the custom tab view has been populated.
5334 if (tabView != null) {
5335 // Get the favorite icon image view from the tab.
5336 ImageView tabFavoriteIconImageView = tabView.findViewById(R.id.favorite_icon_imageview);
5338 // Display the favorite icon in the tab.
5339 tabFavoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
5345 // Save a copy of the title when it changes.
5347 public void onReceivedTitle(WebView view, String title) {
5348 // Get the current page position.
5349 int currentPosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5351 // Get the current tab.
5352 TabLayout.Tab tab = tabLayout.getTabAt(currentPosition);
5354 // Only populate the title text view if the tab has been fully created.
5356 // Get the custom view from the tab.
5357 View tabView = tab.getCustomView();
5359 // Remove the incorrect warning below that the current tab view might be null.
5360 assert tabView != null;
5362 // Get the title text view from the tab.
5363 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
5365 // Set the title according to the URL.
5366 if (title.equals("about:blank")) {
5367 // Set the title to indicate a new tab.
5368 tabTitleTextView.setText(R.string.new_tab);
5370 // Set the title as the tab text.
5371 tabTitleTextView.setText(title);
5376 // Enter full screen video.
5378 public void onShowCustomView(View video, CustomViewCallback callback) {
5379 // Get a handle for the full screen video frame layout.
5380 FrameLayout fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
5382 // Set the full screen video flag.
5383 displayingFullScreenVideo = true;
5385 // Pause the ad if this is the free flavor.
5386 if (BuildConfig.FLAVOR.contentEquals("free")) {
5387 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
5388 AdHelper.pauseAd(findViewById(R.id.adview));
5391 // Hide the keyboard.
5392 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
5394 // Hide the main content relative layout.
5395 mainContentRelativeLayout.setVisibility(View.GONE);
5397 /* Hide the system bars.
5398 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5399 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5400 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5401 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5403 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5404 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5406 // Disable the sliding drawers.
5407 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
5409 // Add the video view to the full screen video frame layout.
5410 fullScreenVideoFrameLayout.addView(video);
5412 // Show the full screen video frame layout.
5413 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
5415 // Disable the screen timeout while the video is playing. YouTube does this automatically, but not all other videos do.
5416 fullScreenVideoFrameLayout.setKeepScreenOn(true);
5419 // Exit full screen video.
5421 public void onHideCustomView() {
5422 // Get a handle for the full screen video frame layout.
5423 FrameLayout fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
5425 // Re-enable the screen timeout.
5426 fullScreenVideoFrameLayout.setKeepScreenOn(false);
5428 // Unset the full screen video flag.
5429 displayingFullScreenVideo = false;
5431 // Remove all the views from the full screen video frame layout.
5432 fullScreenVideoFrameLayout.removeAllViews();
5434 // Hide the full screen video frame layout.
5435 fullScreenVideoFrameLayout.setVisibility(View.GONE);
5437 // Enable the sliding drawers.
5438 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
5440 // Show the main content relative layout.
5441 mainContentRelativeLayout.setVisibility(View.VISIBLE);
5443 // Apply the appropriate full screen mode flags.
5444 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
5445 // Hide the app bar if specified.
5447 // Hide the tab linear layout.
5448 tabsLinearLayout.setVisibility(View.GONE);
5450 // Hide the action bar.
5454 // Hide the banner ad in the free flavor.
5455 if (BuildConfig.FLAVOR.contentEquals("free")) {
5456 AdHelper.hideAd(findViewById(R.id.adview));
5459 /* Hide the system bars.
5460 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
5461 * SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN makes the root frame layout fill the area that is normally reserved for the status bar.
5462 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
5463 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
5465 rootFrameLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
5466 View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
5467 } else { // Switch to normal viewing mode.
5468 // Remove the `SYSTEM_UI` flags from the root frame layout.
5469 rootFrameLayout.setSystemUiVisibility(0);
5472 // Reload the ad for the free flavor if not in full screen mode.
5473 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
5475 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
5481 public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
5482 // Show the file chooser if the device is running API >= 21.
5483 if (Build.VERSION.SDK_INT >= 21) {
5484 // Store the file path callback.
5485 fileChooserCallback = filePathCallback;
5487 // Create an intent to open a chooser based on the file chooser parameters.
5488 Intent fileChooserIntent = fileChooserParams.createIntent();
5490 // Get a handle for the package manager.
5491 PackageManager packageManager = getPackageManager();
5493 // Check to see if the file chooser intent resolves to an installed package.
5494 if (fileChooserIntent.resolveActivity(packageManager) != null) { // The file chooser intent is fine.
5495 // Start the file chooser intent.
5496 startActivityForResult(fileChooserIntent, BROWSE_FILE_UPLOAD_REQUEST_CODE);
5497 } else { // The file chooser intent will cause a crash.
5498 // Create a generic intent to open a chooser.
5499 Intent genericFileChooserIntent = new Intent(Intent.ACTION_GET_CONTENT);
5501 // Request an openable file.
5502 genericFileChooserIntent.addCategory(Intent.CATEGORY_OPENABLE);
5504 // Set the file type to everything.
5505 genericFileChooserIntent.setType("*/*");
5507 // Start the generic file chooser intent.
5508 startActivityForResult(genericFileChooserIntent, BROWSE_FILE_UPLOAD_REQUEST_CODE);
5515 nestedScrollWebView.setWebViewClient(new WebViewClient() {
5516 // `shouldOverrideUrlLoading` makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
5517 // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
5519 public boolean shouldOverrideUrlLoading(WebView view, String url) {
5520 // Sanitize the url.
5521 url = sanitizeUrl(url);
5523 // Handle the URL according to the type.
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 applyDomainSettings(nestedScrollWebView, url, true, false);
5528 // Load the URL. By using `loadUrl()`, instead of `loadUrlFromBase()`, the Referer header will never be sent.
5529 nestedScrollWebView.loadUrl(url, customHeaders);
5531 // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
5532 // Custom headers cannot be added if false is returned and the WebView handles the loading of the URL.
5534 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
5535 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
5536 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
5538 // Parse the url and set it as the data for the intent.
5539 emailIntent.setData(Uri.parse(url));
5541 // Open the email program in a new task instead of as part of Privacy Browser.
5542 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5545 startActivity(emailIntent);
5547 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5549 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
5550 // Open the dialer and load the phone number, but wait for the user to place the call.
5551 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
5553 // Add the phone number to the intent.
5554 dialIntent.setData(Uri.parse(url));
5556 // Open the dialer in a new task instead of as part of Privacy Browser.
5557 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5560 startActivity(dialIntent);
5562 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5564 } else { // Load a system chooser to select an app that can handle the URL.
5565 // Open an app that can handle the URL.
5566 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
5568 // Add the URL to the intent.
5569 genericIntent.setData(Uri.parse(url));
5571 // List all apps that can handle the URL instead of just opening the first one.
5572 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
5574 // Open the app in a new task instead of as part of Privacy Browser.
5575 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
5577 // Start the app or display a snackbar if no app is available to handle the URL.
5579 startActivity(genericIntent);
5580 } catch (ActivityNotFoundException exception) {
5581 Snackbar.make(nestedScrollWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
5584 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
5589 // Check requests against the block lists. The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
5591 public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
5592 // Check to see if the resource request is for the main URL.
5593 if (url.equals(nestedScrollWebView.getCurrentUrl())) {
5594 // `return null` loads the resource request, which should never be blocked if it is the main URL.
5598 // 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.
5599 while (ultraPrivacy == null) {
5600 // The wait must be synchronized, which only lets one thread run on it at a time, or `java.lang.IllegalMonitorStateException` is thrown.
5601 synchronized (this) {
5603 // Check to see if the blocklists have been populated after 100 ms.
5605 } catch (InterruptedException exception) {
5611 // Sanitize the URL.
5612 url = sanitizeUrl(url);
5614 // Get a handle for the navigation view.
5615 NavigationView navigationView = findViewById(R.id.navigationview);
5617 // Get a handle for the navigation menu.
5618 Menu navigationMenu = navigationView.getMenu();
5620 // Get a handle for the navigation requests menu item. The menu is 0 based.
5621 MenuItem navigationRequestsMenuItem = navigationMenu.getItem(6);
5623 // Create an empty web resource response to be used if the resource request is blocked.
5624 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
5626 // Reset the whitelist results tracker.
5627 String[] whitelistResultStringArray = null;
5629 // Initialize the third party request tracker.
5630 boolean isThirdPartyRequest = false;
5632 // Get the current URL. `.getUrl()` throws an error because operations on the WebView cannot be made from this thread.
5633 String currentBaseDomain = nestedScrollWebView.getCurrentDomainName();
5635 // Store a copy of the current domain for use in later requests.
5636 String currentDomain = currentBaseDomain;
5638 // Nobody is happy when comparing null strings.
5639 if ((currentBaseDomain != null) && (url != null)) {
5640 // Convert the request URL to a URI.
5641 Uri requestUri = Uri.parse(url);
5643 // Get the request host name.
5644 String requestBaseDomain = requestUri.getHost();
5646 // Only check for third-party requests if the current base domain is not empty and the request domain is not null.
5647 if (!currentBaseDomain.isEmpty() && (requestBaseDomain != null)) {
5648 // Determine the current base domain.
5649 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5650 // Remove the first subdomain.
5651 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
5654 // Determine the request base domain.
5655 while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
5656 // Remove the first subdomain.
5657 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
5660 // Update the third party request tracker.
5661 isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
5665 // Get the current WebView page position.
5666 int webViewPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5668 // Determine if the WebView is currently displayed.
5669 boolean webViewDisplayed = (webViewPagePosition == tabLayout.getSelectedTabPosition());
5671 // Block third-party requests if enabled.
5672 if (isThirdPartyRequest && nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.THIRD_PARTY_REQUESTS)) {
5673 // Add the result to the resource requests.
5674 nestedScrollWebView.addResourceRequest(new String[]{BlocklistHelper.REQUEST_THIRD_PARTY, url});
5676 // Increment the blocked requests counters.
5677 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5678 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS);
5680 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5681 if (webViewDisplayed) {
5682 // Updating the UI must be run from the UI thread.
5683 activity.runOnUiThread(() -> {
5684 // Update the menu item titles.
5685 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5687 // Update the options menu if it has been populated.
5688 if (optionsMenu != null) {
5689 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5690 optionsMenu.findItem(R.id.block_all_third_party_requests).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.THIRD_PARTY_REQUESTS) + " - " +
5691 getString(R.string.block_all_third_party_requests));
5696 // Return an empty web resource response.
5697 return emptyWebResourceResponse;
5700 // Check UltraList if it is enabled.
5701 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.ULTRALIST)) {
5702 // Check the URL against UltraList.
5703 String[] ultraListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraList);
5705 // Process the UltraList results.
5706 if (ultraListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched UltraLists's blacklist.
5707 // Add the result to the resource requests.
5708 nestedScrollWebView.addResourceRequest(new String[] {ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]});
5710 // Increment the blocked requests counters.
5711 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5712 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRALIST);
5714 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5715 if (webViewDisplayed) {
5716 // Updating the UI must be run from the UI thread.
5717 activity.runOnUiThread(() -> {
5718 // Update the menu item titles.
5719 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5721 // Update the options menu if it has been populated.
5722 if (optionsMenu != null) {
5723 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5724 optionsMenu.findItem(R.id.ultralist).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRALIST) + " - " + getString(R.string.ultralist));
5729 // The resource request was blocked. Return an empty web resource response.
5730 return emptyWebResourceResponse;
5731 } else if (ultraListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched UltraList's whitelist.
5732 // Add a whitelist entry to the resource requests array.
5733 nestedScrollWebView.addResourceRequest(new String[] {ultraListResults[0], ultraListResults[1], ultraListResults[2], ultraListResults[3], ultraListResults[4], ultraListResults[5]});
5735 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
5740 // Check UltraPrivacy if it is enabled.
5741 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.ULTRAPRIVACY)) {
5742 // Check the URL against UltraPrivacy.
5743 String[] ultraPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, ultraPrivacy);
5745 // Process the UltraPrivacy results.
5746 if (ultraPrivacyResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched UltraPrivacy's blacklist.
5747 // Add the result to the resource requests.
5748 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5749 ultraPrivacyResults[5]});
5751 // Increment the blocked requests counters.
5752 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5753 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.ULTRAPRIVACY);
5755 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5756 if (webViewDisplayed) {
5757 // Updating the UI must be run from the UI thread.
5758 activity.runOnUiThread(() -> {
5759 // Update the menu item titles.
5760 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5762 // Update the options menu if it has been populated.
5763 if (optionsMenu != null) {
5764 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5765 optionsMenu.findItem(R.id.ultraprivacy).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.ULTRAPRIVACY) + " - " + getString(R.string.ultraprivacy));
5770 // The resource request was blocked. Return an empty web resource response.
5771 return emptyWebResourceResponse;
5772 } else if (ultraPrivacyResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched UltraPrivacy's whitelist.
5773 // Add a whitelist entry to the resource requests array.
5774 nestedScrollWebView.addResourceRequest(new String[] {ultraPrivacyResults[0], ultraPrivacyResults[1], ultraPrivacyResults[2], ultraPrivacyResults[3], ultraPrivacyResults[4],
5775 ultraPrivacyResults[5]});
5777 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
5782 // Check EasyList if it is enabled.
5783 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.EASYLIST)) {
5784 // Check the URL against EasyList.
5785 String[] easyListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyList);
5787 // Process the EasyList results.
5788 if (easyListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched EasyList's blacklist.
5789 // Add the result to the resource requests.
5790 nestedScrollWebView.addResourceRequest(new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]});
5792 // Increment the blocked requests counters.
5793 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5794 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASYLIST);
5796 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5797 if (webViewDisplayed) {
5798 // Updating the UI must be run from the UI thread.
5799 activity.runOnUiThread(() -> {
5800 // Update the menu item titles.
5801 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5803 // Update the options menu if it has been populated.
5804 if (optionsMenu != null) {
5805 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5806 optionsMenu.findItem(R.id.easylist).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASYLIST) + " - " + getString(R.string.easylist));
5811 // The resource request was blocked. Return an empty web resource response.
5812 return emptyWebResourceResponse;
5813 } else if (easyListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched EasyList's whitelist.
5814 // Update the whitelist result string array tracker.
5815 whitelistResultStringArray = new String[] {easyListResults[0], easyListResults[1], easyListResults[2], easyListResults[3], easyListResults[4], easyListResults[5]};
5819 // Check EasyPrivacy if it is enabled.
5820 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.EASYPRIVACY)) {
5821 // Check the URL against EasyPrivacy.
5822 String[] easyPrivacyResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, easyPrivacy);
5824 // Process the EasyPrivacy results.
5825 if (easyPrivacyResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched EasyPrivacy's blacklist.
5826 // Add the result to the resource requests.
5827 nestedScrollWebView.addResourceRequest(new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4],
5828 easyPrivacyResults[5]});
5830 // Increment the blocked requests counters.
5831 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5832 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.EASYPRIVACY);
5834 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5835 if (webViewDisplayed) {
5836 // Updating the UI must be run from the UI thread.
5837 activity.runOnUiThread(() -> {
5838 // Update the menu item titles.
5839 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5841 // Update the options menu if it has been populated.
5842 if (optionsMenu != null) {
5843 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5844 optionsMenu.findItem(R.id.easyprivacy).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.EASYPRIVACY) + " - " + getString(R.string.easyprivacy));
5849 // The resource request was blocked. Return an empty web resource response.
5850 return emptyWebResourceResponse;
5851 } else if (easyPrivacyResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched EasyPrivacy's whitelist.
5852 // Update the whitelist result string array tracker.
5853 whitelistResultStringArray = new String[] {easyPrivacyResults[0], easyPrivacyResults[1], easyPrivacyResults[2], easyPrivacyResults[3], easyPrivacyResults[4], easyPrivacyResults[5]};
5857 // Check Fanboy’s Annoyance List if it is enabled.
5858 if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST)) {
5859 // Check the URL against Fanboy's Annoyance List.
5860 String[] fanboysAnnoyanceListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList);
5862 // Process the Fanboy's Annoyance List results.
5863 if (fanboysAnnoyanceListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Annoyance List's blacklist.
5864 // Add the result to the resource requests.
5865 nestedScrollWebView.addResourceRequest(new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5866 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]});
5868 // Increment the blocked requests counters.
5869 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5870 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST);
5872 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5873 if (webViewDisplayed) {
5874 // Updating the UI must be run from the UI thread.
5875 activity.runOnUiThread(() -> {
5876 // Update the menu item titles.
5877 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5879 // Update the options menu if it has been populated.
5880 if (optionsMenu != null) {
5881 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5882 optionsMenu.findItem(R.id.fanboys_annoyance_list).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_ANNOYANCE_LIST) + " - " +
5883 getString(R.string.fanboys_annoyance_list));
5888 // The resource request was blocked. Return an empty web resource response.
5889 return emptyWebResourceResponse;
5890 } else if (fanboysAnnoyanceListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)){ // The resource request matched Fanboy's Annoyance List's whitelist.
5891 // Update the whitelist result string array tracker.
5892 whitelistResultStringArray = new String[] {fanboysAnnoyanceListResults[0], fanboysAnnoyanceListResults[1], fanboysAnnoyanceListResults[2], fanboysAnnoyanceListResults[3],
5893 fanboysAnnoyanceListResults[4], fanboysAnnoyanceListResults[5]};
5895 } else if (nestedScrollWebView.isBlocklistEnabled(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST)) { // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
5896 // Check the URL against Fanboy's Annoyance List.
5897 String[] fanboysSocialListResults = blocklistHelper.checkBlocklist(currentDomain, url, isThirdPartyRequest, fanboysSocialList);
5899 // Process the Fanboy's Social Blocking List results.
5900 if (fanboysSocialListResults[0].equals(BlocklistHelper.REQUEST_BLOCKED)) { // The resource request matched Fanboy's Social Blocking List's blacklist.
5901 // Add the result to the resource requests.
5902 nestedScrollWebView.addResourceRequest(new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5903 fanboysSocialListResults[4], fanboysSocialListResults[5]});
5905 // Increment the blocked requests counters.
5906 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS);
5907 nestedScrollWebView.incrementRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST);
5909 // Update the titles of the blocklist menu items if the WebView is currently displayed.
5910 if (webViewDisplayed) {
5911 // Updating the UI must be run from the UI thread.
5912 activity.runOnUiThread(() -> {
5913 // Update the menu item titles.
5914 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5916 // Update the options menu if it has been populated.
5917 if (optionsMenu != null) {
5918 optionsMenu.findItem(R.id.blocklists).setTitle(getString(R.string.blocklists) + " - " + nestedScrollWebView.getRequestsCount(NestedScrollWebView.BLOCKED_REQUESTS));
5919 optionsMenu.findItem(R.id.fanboys_social_blocking_list).setTitle(nestedScrollWebView.getRequestsCount(NestedScrollWebView.FANBOYS_SOCIAL_BLOCKING_LIST) + " - " +
5920 getString(R.string.fanboys_social_blocking_list));
5925 // The resource request was blocked. Return an empty web resource response.
5926 return emptyWebResourceResponse;
5927 } else if (fanboysSocialListResults[0].equals(BlocklistHelper.REQUEST_ALLOWED)) { // The resource request matched Fanboy's Social Blocking List's whitelist.
5928 // Update the whitelist result string array tracker.
5929 whitelistResultStringArray = new String[] {fanboysSocialListResults[0], fanboysSocialListResults[1], fanboysSocialListResults[2], fanboysSocialListResults[3],
5930 fanboysSocialListResults[4], fanboysSocialListResults[5]};
5934 // Add the request to the log because it hasn't been processed by any of the previous checks.
5935 if (whitelistResultStringArray != null) { // The request was processed by a whitelist.
5936 nestedScrollWebView.addResourceRequest(whitelistResultStringArray);
5937 } else { // The request didn't match any blocklist entry. Log it as a default request.
5938 nestedScrollWebView.addResourceRequest(new String[]{BlocklistHelper.REQUEST_DEFAULT, url});
5941 // The resource request has not been blocked. `return null` loads the requested resource.
5945 // Handle HTTP authentication requests.
5947 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
5948 // Store the handler.
5949 nestedScrollWebView.setHttpAuthHandler(handler);
5951 // Instantiate an HTTP authentication dialog.
5952 DialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm, nestedScrollWebView.getWebViewFragmentId());
5954 // Show the HTTP authentication dialog.
5955 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
5959 public void onPageStarted(WebView view, String url, Bitmap favicon) {
5960 // Get the preferences.
5961 boolean scrollAppBar = sharedPreferences.getBoolean("scroll_app_bar", true);
5963 // Get a handler for the app bar layout.
5964 AppBarLayout appBarLayout = findViewById(R.id.appbar_layout);
5966 // Set the top padding of the swipe refresh layout according to the app bar scrolling preference. This can't be done in `appAppSettings()` because the app bar is not yet populated there.
5967 if (scrollAppBar || (inFullScreenBrowsingMode && hideAppBar)) {
5968 // No padding is needed because it will automatically be placed below the app bar layout due to the scrolling layout behavior.
5969 swipeRefreshLayout.setPadding(0, 0, 0, 0);
5971 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5972 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10, defaultProgressViewEndOffset);
5974 // Get the app bar layout height. This can't be done in `applyAppSettings()` because the app bar is not yet populated there.
5975 appBarHeight = appBarLayout.getHeight();
5977 // The swipe refresh layout must be manually moved below the app bar layout.
5978 swipeRefreshLayout.setPadding(0, appBarHeight, 0, 0);
5980 // The swipe to refresh circle doesn't always hide itself completely unless it is moved up 10 pixels.
5981 swipeRefreshLayout.setProgressViewOffset(false, defaultProgressViewStartOffset - 10 + appBarHeight, defaultProgressViewEndOffset + appBarHeight);
5984 // Reset the list of resource requests.
5985 nestedScrollWebView.clearResourceRequests();
5987 // Reset the requests counters.
5988 nestedScrollWebView.resetRequestsCounters();
5990 // Hide the keyboard.
5991 inputMethodManager.hideSoftInputFromWindow(nestedScrollWebView.getWindowToken(), 0);
5993 // Get the current page position.
5994 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
5996 // Update the URL text bar if the page is currently selected.
5997 if (tabLayout.getSelectedTabPosition() == currentPagePosition) {
5998 // Clear the focus from the URL edit text.
5999 urlEditText.clearFocus();
6001 // Display the formatted URL text.
6002 urlEditText.setText(url);
6004 // Apply text highlighting to `urlTextBox`.
6008 // Reset the list of host IP addresses.
6009 nestedScrollWebView.clearCurrentIpAddresses();
6011 // Get a URI for the current URL.
6012 Uri currentUri = Uri.parse(url);
6014 // Get the IP addresses for the host.
6015 new GetHostIpAddresses(activity, getSupportFragmentManager(), nestedScrollWebView).execute(currentUri.getHost());
6017 // Replace Refresh with Stop if the options menu has been created. (The first WebView typically begins loading before the menu items are instantiated.)
6018 if (optionsMenu != null) {
6019 // Get a handle for the refresh menu item.
6020 MenuItem refreshMenuItem = optionsMenu.findItem(R.id.refresh);
6023 refreshMenuItem.setTitle(R.string.stop);
6025 // Get the app bar and theme preferences.
6026 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
6028 // If the icon is displayed in the AppBar, set it according to the theme.
6029 if (displayAdditionalAppBarIcons) {
6030 // Get the current theme status.
6031 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
6033 // Set the stop icon according to the theme.
6034 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES) {
6035 refreshMenuItem.setIcon(R.drawable.close_night);
6037 refreshMenuItem.setIcon(R.drawable.close_day);
6044 public void onPageFinished(WebView view, String url) {
6045 // Flush any cookies to persistent storage. The cookie manager has become very lazy about flushing cookies in recent versions.
6046 if (nestedScrollWebView.getAcceptFirstPartyCookies() && Build.VERSION.SDK_INT >= 21) {
6047 CookieManager.getInstance().flush();
6050 // Update the Refresh menu item if the options menu has been created.
6051 if (optionsMenu != null) {
6052 // Get a handle for the refresh menu item.
6053 MenuItem refreshMenuItem = optionsMenu.findItem(R.id.refresh);
6055 // Reset the Refresh title.
6056 refreshMenuItem.setTitle(R.string.refresh);
6058 // Get the app bar and theme preferences.
6059 boolean displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
6061 // If the icon is displayed in the app bar, reset it according to the theme.
6062 if (displayAdditionalAppBarIcons) {
6063 // Get the current theme status.
6064 int currentThemeStatus = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
6066 // Set the icon according to the theme.
6067 if (currentThemeStatus == Configuration.UI_MODE_NIGHT_YES) {
6068 refreshMenuItem.setIcon(R.drawable.refresh_enabled_night);
6070 refreshMenuItem.setIcon(R.drawable.refresh_enabled_day);
6075 // Clear the cache and history if Incognito Mode is enabled.
6076 if (incognitoModeEnabled) {
6077 // Clear the cache. `true` includes disk files.
6078 nestedScrollWebView.clearCache(true);
6080 // Clear the back/forward history.
6081 nestedScrollWebView.clearHistory();
6083 // Manually delete cache folders.
6085 // Get the application's private data directory, which will be something like `/data/user/0/com.stoutner.privacybrowser.standard`,
6086 // which links to `/data/data/com.stoutner.privacybrowser.standard`.
6087 String privateDataDirectoryString = getApplicationInfo().dataDir;
6089 // Delete the main cache directory.
6090 Runtime.getRuntime().exec("rm -rf " + privateDataDirectoryString + "/cache");
6092 // Delete the secondary `Service Worker` cache directory.
6093 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
6094 Runtime.getRuntime().exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
6095 } catch (IOException e) {
6096 // Do nothing if an error is thrown.
6100 // Get the current page position.
6101 int currentPagePosition = webViewPagerAdapter.getPositionForId(nestedScrollWebView.getWebViewFragmentId());
6103 // Check the current website information against any pinned domain information if the current IP addresses have been loaded.
6104 if ((nestedScrollWebView.hasPinnedSslCertificate() || nestedScrollWebView.hasPinnedIpAddresses()) && nestedScrollWebView.hasCurrentIpAddresses() &&
6105 !nestedScrollWebView.ignorePinnedDomainInformation()) {
6106 CheckPinnedMismatchHelper.checkPinnedMismatch(getSupportFragmentManager(), nestedScrollWebView);
6109 // 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.
6110 String currentUrl = nestedScrollWebView.getUrl();
6112 // Get the current tab.
6113 TabLayout.Tab tab = tabLayout.getTabAt(currentPagePosition);
6115 // Update the URL text bar if the page is currently selected and the user is not currently typing in the URL edit text.
6116 // Crash records show that, in some crazy way, it is possible for the current URL to be blank at this point.
6117 // Probably some sort of race condition when Privacy Browser is being resumed.
6118 if ((tabLayout.getSelectedTabPosition() == currentPagePosition) && !urlEditText.hasFocus() && (currentUrl != null)) {
6119 // Check to see if the URL is `about:blank`.
6120 if (currentUrl.equals("about:blank")) { // The WebView is blank.
6121 // Display the hint in the URL edit text.
6122 urlEditText.setText("");
6124 // Request focus for the URL text box.
6125 urlEditText.requestFocus();
6127 // Display the keyboard.
6128 inputMethodManager.showSoftInput(urlEditText, 0);
6130 // Apply the domain settings. This clears any settings from the previous domain.
6131 applyDomainSettings(nestedScrollWebView, "", true, false);
6133 // Only populate the title text view if the tab has been fully created.
6135 // Get the custom view from the tab.
6136 View tabView = tab.getCustomView();
6138 // Remove the incorrect warning below that the current tab view might be null.
6139 assert tabView != null;
6141 // Get the title text view from the tab.
6142 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
6144 // Set the title as the tab text.
6145 tabTitleTextView.setText(R.string.new_tab);
6147 } else { // The WebView has loaded a webpage.
6148 // Update the URL edit text if it is not currently being edited.
6149 if (!urlEditText.hasFocus()) {
6150 // 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.
6151 String sanitizedUrl = sanitizeUrl(currentUrl);
6153 // Display the final URL. Getting the URL from the WebView instead of using the one provided by `onPageFinished()` makes websites like YouTube function correctly.
6154 urlEditText.setText(sanitizedUrl);
6156 // Apply text highlighting to the URL.
6160 // Only populate the title text view if the tab has been fully created.
6162 // Get the custom view from the tab.
6163 View tabView = tab.getCustomView();
6165 // Remove the incorrect warning below that the current tab view might be null.
6166 assert tabView != null;
6168 // Get the title text view from the tab.
6169 TextView tabTitleTextView = tabView.findViewById(R.id.title_textview);
6171 // Set the title as the tab text. Sometimes `onReceivedTitle()` is not called, especially when navigating history.
6172 tabTitleTextView.setText(nestedScrollWebView.getTitle());
6178 // Handle SSL Certificate errors.
6180 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
6181 // Get the current website SSL certificate.
6182 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
6184 // Extract the individual pieces of information from the current website SSL certificate.
6185 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
6186 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
6187 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
6188 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
6189 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
6190 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
6191 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
6192 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
6194 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
6195 if (nestedScrollWebView.hasPinnedSslCertificate()) {
6196 // Get the pinned SSL certificate.
6197 ArrayList<Object> pinnedSslCertificateArrayList = nestedScrollWebView.getPinnedSslCertificate();
6199 // Extract the arrays from the array list.
6200 String[] pinnedSslCertificateStringArray = (String[]) pinnedSslCertificateArrayList.get(0);
6201 Date[] pinnedSslCertificateDateArray = (Date[]) pinnedSslCertificateArrayList.get(1);
6203 // Check if the current SSL certificate matches the pinned certificate.
6204 if (currentWebsiteIssuedToCName.equals(pinnedSslCertificateStringArray[0]) && currentWebsiteIssuedToOName.equals(pinnedSslCertificateStringArray[1]) &&
6205 currentWebsiteIssuedToUName.equals(pinnedSslCertificateStringArray[2]) && currentWebsiteIssuedByCName.equals(pinnedSslCertificateStringArray[3]) &&
6206 currentWebsiteIssuedByOName.equals(pinnedSslCertificateStringArray[4]) && currentWebsiteIssuedByUName.equals(pinnedSslCertificateStringArray[5]) &&
6207 currentWebsiteSslStartDate.equals(pinnedSslCertificateDateArray[0]) && currentWebsiteSslEndDate.equals(pinnedSslCertificateDateArray[1])) {
6209 // An SSL certificate is pinned and matches the current domain certificate. Proceed to the website without displaying an error.
6212 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
6213 // Store the SSL error handler.
6214 nestedScrollWebView.setSslErrorHandler(handler);
6216 // Instantiate an SSL certificate error alert dialog.
6217 DialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error, nestedScrollWebView.getWebViewFragmentId());
6219 // Show the SSL certificate error dialog.
6220 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
6225 // Check to see if this is the first page.
6226 if (pageNumber == 0) {
6227 // Set this nested scroll WebView as the current WebView.
6228 currentWebView = nestedScrollWebView;
6230 // Apply the app settings from the shared preferences.
6233 // Initialize the URL to load string.
6234 String urlToLoadString;
6236 // Get the intent that started the app.
6237 Intent launchingIntent = getIntent();
6239 // Get the information from the intent.
6240 String launchingIntentAction = launchingIntent.getAction();
6241 Uri launchingIntentUriData = launchingIntent.getData();
6243 // Parse the launching intent URL.
6244 if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) { // The intent contains a search string.
6245 // Create an encoded URL string.
6246 String encodedUrlString;
6248 // Sanitize the search input and convert it to a search.
6250 encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
6251 } catch (UnsupportedEncodingException exception) {
6252 encodedUrlString = "";
6255 // Store the web search as the URL to load.
6256 urlToLoadString = searchURL + encodedUrlString;
6257 } else if (launchingIntentUriData != null){ // The intent contains a URL.
6259 urlToLoadString = launchingIntentUriData.toString();
6260 } else { // The is no URL in the intent.
6261 // Store the homepage to be loaded.
6262 urlToLoadString = sharedPreferences.getString("homepage", getString(R.string.homepage_default_value));
6265 // Load the website if not waiting for the proxy.
6266 if (waitingForProxy) { // Store the URL to be loaded in the Nested Scroll WebView.
6267 nestedScrollWebView.setWaitingForProxyUrlString(urlToLoadString);
6268 } else { // Load the URL.
6269 loadUrl(nestedScrollWebView, urlToLoadString);
6271 } else { // This is not the first tab.
6272 // Apply the domain settings.
6273 applyDomainSettings(nestedScrollWebView, url, false, false);
6276 nestedScrollWebView.loadUrl(url, customHeaders);
6278 // Set the focus and display the keyboard if the URL is blank.
6279 if (url.equals("")) {
6280 // Request focus for the URL text box.
6281 urlEditText.requestFocus();
6283 // Create a display keyboard handler.
6284 Handler displayKeyboardHandler = new Handler();
6286 // Create a display keyboard runnable.
6287 Runnable displayKeyboardRunnable = () -> {
6288 // Display the keyboard.
6289 inputMethodManager.showSoftInput(urlEditText, 0);
6292 // Display the keyboard after 100 milliseconds, which leaves enough time for the tab to transition.
6293 displayKeyboardHandler.postDelayed(displayKeyboardRunnable, 100);